Răsfoiți Sursa

feat(device): connection

runhey 3 ani în urmă
părinte
comite
06e4404109

+ 0 - 2
.gitignore

@@ -24,8 +24,6 @@ test/
 *.user
 !module/gui/FluentUI/fluentuiplugin.dll
 build-fluentui-Desktop_*/
-!console.bat
-!oas.exe
 
 
 

+ 79 - 2
module/base/decorator.py

@@ -1,11 +1,88 @@
 # This Python file uses the following encoding: utf-8
-# @author runhey
-# github https://github.com/runhey
 from functools import wraps
 from typing import Callable, Generic, TypeVar
 
 T = TypeVar("T")
 
+
+class Config:
+    """
+    Decorator that calls different function with a same name according to config.
+
+    func_list likes:
+    func_list = {
+        'func1': [
+            {'options': {'ENABLE': True}, 'func': 1},
+            {'options': {'ENABLE': False}, 'func': 1}
+        ]
+    }
+    """
+    func_list = {}
+    """
+    这段代码定义了一个名为`Config`的类,其中包含一个名为`when`的装饰器方法。该装饰器用于根据配置的不同,在调用具有相同名称的函数时选择不同的函数。
+    在`Config`类中,有一个类变量`func_list`,用于存储函数的配置和对应的函数。`func_list`的结构是一个字典,其中键是函数的名称,值是一个列表,列表中的每个元素是一个字典,包含了选项和对应的函数。每个选项是一个字典,表示配置选项及其值,函数是一个可调用对象。
+    `when`装饰器的作用是将装饰的函数添加到`func_list`中。装饰器接受一个或多个关键字参数,这些参数是AzurLaneConfig中的选项。装饰器内部定义了一个`decorate`函数作为装饰器的实际实现。
+    在`decorate`函数内部,首先获取被装饰函数的名称和选项,并将它们保存在一个字典中。然后判断该函数名称是否已经存在于`func_list`中,如果不存在,则将该函数及其选项添加到`func_list`中;如果存在,则检查是否有相同选项的记录,如果有,则覆盖原有的函数;如果没有,则添加新的记录。
+    接下来,使用`@wraps(func)`装饰器来保留原始函数的元数据。然后定义了一个名为`wrapper`的内部函数作为装饰后的函数。在`wrapper`函数内部,遍历函数名称在`func_list`中的记录,对于每个记录,检查选项是否匹配当前的配置。如果匹配,则调用对应的函数并返回结果;如果没有匹配的选项,则使用最后定义的函数作为默认函数,并打印警告信息。最后,返回`wrapper`函数作为装饰后的函数。
+    通过使用`@Config.when()`语法将装饰器应用于函数,可以根据不同的配置选项选择不同的函数执行。
+    """
+
+    @classmethod
+    def when(cls, **kwargs):
+        """
+        Args:
+            **kwargs: Any option in AzurLaneConfig.
+
+        Examples:
+            @Config.when(USE_ONE_CLICK_RETIREMENT=True)
+            def retire_ships(self, amount=None, rarity=None):
+                pass
+
+            @Config.when(USE_ONE_CLICK_RETIREMENT=False)
+            def retire_ships(self, amount=None, rarity=None):
+                pass
+        """
+        from module.logger import logger
+        options = kwargs
+
+        def decorate(func):
+            name = func.__name__
+            data = {'options': options, 'func': func}
+            if name not in cls.func_list:
+                cls.func_list[name] = [data]
+            else:
+                override = False
+                for record in cls.func_list[name]:
+                    if record['options'] == data['options']:
+                        record['func'] = data['func']
+                        override = True
+                if not override:
+                    cls.func_list[name].append(data)
+
+            @wraps(func)
+            def wrapper(self, *args, **kwargs):
+                """
+                Args:
+                    self: ModuleBase instance.
+                    *args:
+                    **kwargs:
+                """
+                for record in cls.func_list[name]:
+
+                    flag = [value is None or self.config.__getattribute__(key) == value
+                            for key, value in record['options'].items()]
+                    if not all(flag):
+                        continue
+
+                    return record['func'](self, *args, **kwargs)
+
+                logger.warning(f'No option fits for {name}, using the last define func.')
+                return func(self, *args, **kwargs)
+
+            return wrapper
+
+        return decorate
+
 class cached_property(Generic[T]):
     """
     cached-property from https://github.com/pydanny/cached-property

+ 53 - 0
module/base/utils.py

@@ -0,0 +1,53 @@
+# This Python file uses the following encoding: utf-8
+import re
+
+import cv2
+import numpy as np
+from PIL import Image
+
+def random_normal_distribution_int(a, b, n=3):
+    """Generate a normal distribution int within the interval. Use the average value of several random numbers to
+    simulate normal distribution.
+
+    Args:
+        a (int): The minimum of the interval.
+        b (int): The maximum of the interval.
+        n (int): The amount of numbers in simulation. Default to 3.
+
+    Returns:
+        int
+    """
+    if a < b:
+        output = np.mean(np.random.randint(a, b, size=n))
+        return int(output.round())
+    else:
+        return b
+
+def ensure_time(second, n=3, precision=3):
+    """Ensure to be time.
+
+    Args:
+        second (int, float, tuple): time, such as 10, (10, 30), '10, 30'
+        n (int): The amount of numbers in simulation. Default to 5.
+        precision (int): Decimals.
+
+    Returns:
+        float:
+    """
+    if isinstance(second, tuple):
+        multiply = 10 ** precision
+        result = random_normal_distribution_int(second[0] * multiply, second[1] * multiply, n) / multiply
+        return round(result, precision)
+    elif isinstance(second, str):
+        if ',' in second:
+            lower, upper = second.replace(' ', '').split(',')
+            lower, upper = int(lower), int(upper)
+            return ensure_time((lower, upper), n=n, precision=precision)
+        if '-' in second:
+            lower, upper = second.replace(' ', '').split('-')
+            lower, upper = int(lower), int(upper)
+            return ensure_time((lower, upper), n=n, precision=precision)
+        else:
+            return int(second)
+    else:
+        return second

+ 14 - 0
module/config/config.py

@@ -33,7 +33,21 @@ class Config(ConfigManual, ConfigWatcher, ConfigUpdater):
         self.data = self.read_file(self.config_name)
 
 
+    def get_arg(self, task: str, group: str, argument: str):
+        """
+
+        :param task:
+        :param group:
+        :param argument:
+        :return: str/int/float
+        """
+        try:
+            return self.data[task][group][argument]
+        except:
+            logger.exception(f'have no arg {task}.{group}.{argument}')
+
 
 if __name__ == '__main__':
     config = Config(config_name='oas1')
     logger.info(config.data)
+    logger.info(config.get_arg("Script", "Device", "Serial"))

+ 21 - 0
module/config/utils.py

@@ -92,3 +92,24 @@ def write_file(file: str, data):
         else:
             print(f'Unsupported config file extension: {ext}')
 
+
+def deep_iter(data, depth=0, current_depth=1):
+    """
+    Iter a dictionary safely.
+
+    Args:
+        data (dict):
+        depth (int): Maximum depth to iter
+        current_depth (int):
+
+    Returns:
+        list: Key path
+        Any:
+    """
+    if isinstance(data, dict) \
+            and (depth and current_depth <= depth):
+        for key, value in data.items():
+            for child_path, child_value in deep_iter(value, depth=depth, current_depth=current_depth + 1):
+                yield [key] + child_path, child_value
+    else:
+        yield [], data

+ 850 - 0
module/device/connection.py

@@ -0,0 +1,850 @@
+# This Python file uses the following encoding: utf-8
+import ipaddress
+import logging
+import platform
+import re
+import socket
+import subprocess
+import time
+from functools import wraps
+
+import uiautomator2 as u2
+from adbutils import AdbClient, AdbDevice, AdbTimeout, ForwardItem, ReverseItem
+from adbutils.errors import AdbError
+
+from module.base.decorator import Config, cached_property, del_cached_property
+from module.base.utils import ensure_time
+from module.device.connection_attr import ConnectionAttr
+from module.device.method.utils import (
+    RETRY_TRIES, remove_shell_warning, retry_sleep,
+    handle_adb_error, PackageNotInstalled,
+    recv_all, possible_reasons,
+    random_port, get_serial_pair)
+from module.exception import RequestHumanTakeover, EmulatorNotRunningError
+from module.logger import logger
+
+
+def retry(func):
+    @wraps(func)
+    def retry_wrapper(self, *args, **kwargs):
+        """
+        Args:
+            self (Adb):
+        """
+        init = None
+        for _ in range(RETRY_TRIES):
+            try:
+                if callable(init):
+                    retry_sleep(_)
+                    init()
+                return func(self, *args, **kwargs)
+            # Can't handle
+            except RequestHumanTakeover:
+                break
+            # When adb server was killed
+            except ConnectionResetError as e:
+                logger.error(e)
+
+                def init():
+                    self.adb_reconnect()
+            # AdbError
+            except AdbError as e:
+                if handle_adb_error(e):
+                    def init():
+                        self.adb_reconnect()
+                else:
+                    break
+            # Package not installed
+            except PackageNotInstalled as e:
+                logger.error(e)
+
+                def init():
+                    self.detect_package()
+            # Unknown, probably a trucked image
+            except Exception as e:
+                logger.exception(e)
+
+                def init():
+                    pass
+
+        logger.critical(f'Retry {func.__name__}() failed')
+        raise RequestHumanTakeover
+
+    return retry_wrapper
+
+
+class AdbDeviceWithStatus(AdbDevice):
+    def __init__(self, client: AdbClient, serial: str, status: str):
+        self.status = status
+        super().__init__(client, serial)
+
+    def __str__(self):
+        return f'AdbDevice({self.serial}, {self.status})'
+
+    __repr__ = __str__
+
+    def __bool__(self):
+        return True
+
+
+class Connection(ConnectionAttr):
+    def __init__(self, config):
+        """
+        Args:
+            config (AzurLaneConfig, str): Name of the user config under ./config
+        """
+        super().__init__(config)
+        if not self.is_over_http:
+            self.detect_device()
+
+        # Connect
+        self.adb_connect(self.serial)
+        logger.attr('AdbDevice', self.adb)
+
+        # Package
+        # self.package = self.config.Emulator_PackageName
+        self.package = self.config.get_arg('Script', 'Device', 'PackageName')
+        if self.package == 'auto':
+            self.detect_package()
+        else:
+            pass
+            # set_server(self.package)
+        logger.attr('PackageName', self.package)
+        # logger.attr('Server', self.config.SERVER)
+
+    @Config.when(DEVICE_OVER_HTTP=False)
+    def adb_command(self, cmd, timeout=10):
+        """
+        Execute ADB commands in a subprocess,
+        usually to be used when pulling or pushing large files.
+
+        Args:
+            cmd (list):
+            timeout (int):
+
+        Returns:
+            str:
+        """
+        cmd = list(map(str, cmd))
+        cmd = [self.adb_binary, '-s', self.serial] + cmd
+        logger.info(f'Execute: {cmd}')
+
+        # Use shell=True to disable console window when using GUI.
+        # Although, there's still a window when you stop running in GUI, which cause by gooey.
+        # To disable it, edit gooey/gui/util/taskkill.py
+
+        # No gooey anymore, just shell=False
+        process = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=False)
+        try:
+            stdout, stderr = process.communicate(timeout=timeout)
+        except subprocess.TimeoutExpired:
+            process.kill()
+            stdout, stderr = process.communicate()
+            logger.warning(f'TimeoutExpired when calling {cmd}, stdout={stdout}, stderr={stderr}')
+        return stdout
+
+    @Config.when(DEVICE_OVER_HTTP=True)
+    def adb_command(self, cmd, timeout=10):
+        logger.warning(
+            f'adb_command() is not available when connecting over http: {self.serial}, '
+        )
+        raise RequestHumanTakeover
+
+    @Config.when(DEVICE_OVER_HTTP=False)
+    def adb_shell(self, cmd, stream=False, recvall=True, timeout=10, rstrip=True):
+        """
+        Equivalent to `adb -s <serial> shell <*cmd>`
+
+        Args:
+            cmd (list, str):
+            stream (bool): Return stream instead of string output (Default: False)
+            recvall (bool): Receive all data when stream=True (Default: True)
+            timeout (int): (Default: 10)
+            rstrip (bool): Strip the last empty line (Default: True)
+
+        Returns:
+            str if stream=False
+            bytes if stream=True and recvall=True
+            socket if stream=True and recvall=False
+        """
+        if not isinstance(cmd, str):
+            cmd = list(map(str, cmd))
+
+        if stream:
+            result = self.adb.shell(cmd, stream=stream, timeout=timeout, rstrip=rstrip)
+            if recvall:
+                # bytes
+                return recv_all(result)
+            else:
+                # socket
+                return result
+        else:
+            result = self.adb.shell(cmd, stream=stream, timeout=timeout, rstrip=rstrip)
+            result = remove_shell_warning(result)
+            # str
+            return result
+
+    @Config.when(DEVICE_OVER_HTTP=True)
+    def adb_shell(self, cmd, stream=False, recvall=True, timeout=10, rstrip=True):
+        """
+        Equivalent to http://127.0.0.1:7912/shell?command={command}
+
+        Args:
+            cmd (list, str):
+            stream (bool): Return stream instead of string output (Default: False)
+            recvall (bool): Receive all data when stream=True (Default: True)
+            timeout (int): (Default: 10)
+            rstrip (bool): Strip the last empty line (Default: True)
+
+        Returns:
+            str if stream=False
+            bytes if stream=True
+        """
+        if not isinstance(cmd, str):
+            cmd = list(map(str, cmd))
+
+        if stream:
+            result = self.u2.shell(cmd, stream=stream, timeout=timeout)
+            # Already received all, so `recvall` is ignored
+            result = remove_shell_warning(result.content)
+            # bytes
+            return result
+        else:
+            result = self.u2.shell(cmd, stream=stream, timeout=timeout).output
+            if rstrip:
+                result = result.rstrip()
+            result = remove_shell_warning(result)
+            # str
+            return result
+
+    @cached_property
+    def cpu_abi(self) -> str:
+        """
+        Returns:
+            str: arm64-v8a, armeabi-v7a, x86, x86_64
+        """
+        abi = self.adb_shell(['getprop', 'ro.product.cpu.abi']).strip()
+        if not len(abi):
+            logger.error(f'CPU ABI invalid: "{abi}"')
+        return abi
+
+    @cached_property
+    def sdk_ver(self) -> int:
+        """
+        Android SDK/API levels, see https://apilevels.com/
+        """
+        sdk = self.adb_shell(['getprop', 'ro.build.version.sdk']).strip()
+        try:
+            return int(sdk)
+        except ValueError:
+            logger.error(f'SDK version invalid: {sdk}')
+
+        return 0
+
+    @cached_property
+    def is_avd(self):
+        if get_serial_pair(self.serial)[0] is None:
+            return False
+        if 'ranchu' in self.adb_shell(['getprop', 'ro.hardware']):
+            return True
+        if 'goldfish' in self.adb_shell(['getprop', 'ro.hardware.audio.primary']):
+            return True
+        return False
+
+    @cached_property
+    def _nc_server_host_port(self):
+        """
+        Returns:
+            str, int, str, int:
+                server_listen_host, server_listen_port, client_connect_host, client_connect_port
+        """
+        # For BlueStacks hyper-v, use ADB reverse
+        if self.is_bluestacks_hyperv:
+            host = '127.0.0.1'
+            logger.info(f'Connecting to BlueStacks hyper-v, using host {host}')
+            port = self.adb_reverse(f'tcp:{self.config.REVERSE_SERVER_PORT}')
+            return host, port, host, self.config.REVERSE_SERVER_PORT
+        # For emulators, listen on current host
+        if self.is_emulator or self.is_over_http:
+            try:
+                host = socket.gethostbyname(socket.gethostname())
+            except socket.gaierror as e:
+                logger.error(e)
+                logger.error(f'Unknown host name: {socket.gethostname()}')
+                host = '127.0.0.1'
+            if platform.system() == 'Linux' and host == '127.0.1.1':
+                host = '127.0.0.1'
+            logger.info(f'Connecting to local emulator, using host {host}')
+            port = random_port(self.config.FORWARD_PORT_RANGE)
+
+            # For AVD instance
+            if self.is_avd:
+                return host, port, "10.0.2.2", port
+
+            return host, port, host, port
+        # For local network devices, listen on the host under the same network as target device
+        if self.is_network_device:
+            hosts = socket.gethostbyname_ex(socket.gethostname())[2]
+            logger.info(f'Current hosts: {hosts}')
+            ip = ipaddress.ip_address(self.serial.split(':')[0])
+            for host in hosts:
+                if ip in ipaddress.ip_interface(f'{host}/24').network:
+                    logger.info(f'Connecting to local network device, using host {host}')
+                    port = random_port(self.config.FORWARD_PORT_RANGE)
+                    return host, port, host, port
+        # For other devices, create an ADB reverse and listen on 127.0.0.1
+        host = '127.0.0.1'
+        logger.info(f'Connecting to unknown device, using host {host}')
+        port = self.adb_reverse(f'tcp:{self.config.REVERSE_SERVER_PORT}')
+        return host, port, host, self.config.REVERSE_SERVER_PORT
+
+    @cached_property
+    def reverse_server(self):
+        """
+        Setup a server on Alas, access it from emulator.
+        This will bypass adb shell and be faster.
+        """
+        del_cached_property(self, '_nc_server_host_port')
+        host_port = self._nc_server_host_port
+        logger.info(f'Reverse server listening on {host_port[0]}:{host_port[1]}, '
+                    f'client can send data to {host_port[2]}:{host_port[3]}')
+        server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+        server.bind(host_port[:2])
+        server.settimeout(5)
+        server.listen(5)
+        return server
+
+    @cached_property
+    def nc_command(self):
+        """
+        Returns:
+            list[str]: ['nc'] or ['busybox', 'nc']
+        """
+        sdk = self.sdk_ver
+        logger.info(f'sdk_ver: {sdk}')
+        if sdk >= 28:
+            # Android 9 emulators does not have `nc`, try `busybox nc`
+            # BlueStacks Pie (Android 9) has `nc` but cannot send data, try `busybox nc` first
+            trial = [
+                ['busybox', 'nc'],
+                ['nc'],
+            ]
+        else:
+            trial = [
+                ['nc'],
+                ['busybox', 'nc'],
+            ]
+        for command in trial:
+            # About 3ms
+            result = self.adb_shell(command)
+            # Result should be command help if success
+            # `/system/bin/sh: nc: not found`
+            if 'not found' in result:
+                continue
+            # `/system/bin/sh: busybox: inaccessible or not found\n`
+            if 'inaccessible' in result:
+                continue
+            logger.attr('nc command', command)
+            return command
+
+        logger.error('No `netcat` command available, please use screenshot methods without `_nc` suffix')
+        raise RequestHumanTakeover
+
+    def adb_shell_nc(self, cmd, timeout=5, chunk_size=262144):
+        """
+        Args:
+            cmd (list):
+            timeout (int):
+            chunk_size (int): Default to 262144
+
+        Returns:
+            bytes:
+        """
+        # Server start listening
+        server = self.reverse_server
+        server.settimeout(timeout)
+        # Client send data, waiting for server accept
+        # <command> | nc 127.0.0.1 {port}
+        cmd += ["|", *self.nc_command, *self._nc_server_host_port[2:]]
+        stream = self.adb_shell(cmd, stream=True, recvall=False)
+        try:
+            # Server accept connection
+            conn, conn_port = server.accept()
+        except socket.timeout:
+            output = recv_all(stream, chunk_size=chunk_size)
+            logger.warning(str(output))
+            raise AdbTimeout('reverse server accept timeout')
+
+        # Server receive data
+        data = recv_all(conn, chunk_size=chunk_size, recv_interval=0.001)
+
+        # Server close connection
+        conn.close()
+        return data
+
+    def adb_exec_out(self, cmd, serial=None):
+        cmd.insert(0, 'exec-out')
+        return self.adb_command(cmd, serial)
+
+    def adb_forward(self, remote):
+        """
+        Do `adb forward <local> <remote>`.
+        choose a random port in FORWARD_PORT_RANGE or reuse an existing forward,
+        and also remove redundant forwards.
+
+        Args:
+            remote (str):
+                tcp:<port>
+                localabstract:<unix domain socket name>
+                localreserved:<unix domain socket name>
+                localfilesystem:<unix domain socket name>
+                dev:<character device name>
+                jdwp:<process pid> (remote only)
+
+        Returns:
+            int: Port
+        """
+        port = 0
+        for forward in self.adb.forward_list():
+            if forward.serial == self.serial and forward.remote == remote and forward.local.startswith('tcp:'):
+                if not port:
+                    logger.info(f'Reuse forward: {forward}')
+                    port = int(forward.local[4:])
+                else:
+                    logger.info(f'Remove redundant forward: {forward}')
+                    self.adb_forward_remove(forward.local)
+
+        if port:
+            return port
+        else:
+            # Create new forward
+            port = random_port(self.config.FORWARD_PORT_RANGE)
+            forward = ForwardItem(self.serial, f'tcp:{port}', remote)
+            logger.info(f'Create forward: {forward}')
+            self.adb.forward(forward.local, forward.remote)
+            return port
+
+    def adb_reverse(self, remote):
+        port = 0
+        for reverse in self.adb.reverse_list():
+            if reverse.remote == remote and reverse.local.startswith('tcp:'):
+                if not port:
+                    logger.info(f'Reuse reverse: {reverse}')
+                    port = int(reverse.local[4:])
+                else:
+                    logger.info(f'Remove redundant forward: {reverse}')
+                    self.adb_forward_remove(reverse.local)
+
+        if port:
+            return port
+        else:
+            # Create new reverse
+            port = random_port(self.config.FORWARD_PORT_RANGE)
+            reverse = ReverseItem(f'tcp:{port}', remote)
+            logger.info(f'Create reverse: {reverse}')
+            self.adb.reverse(reverse.local, reverse.remote)
+            return port
+
+    def adb_forward_remove(self, local):
+        """
+        Equivalent to `adb -s <serial> forward --remove <local>`
+        More about the commands send to ADB server, see:
+        https://cs.android.com/android/platform/superproject/+/master:packages/modules/adb/SERVICES.TXT
+
+        Args:
+            local (str): Such as 'tcp:2437'
+        """
+        with self.adb_client._connect() as c:
+            list_cmd = f"host-serial:{self.serial}:killforward:{local}"
+            c.send_command(list_cmd)
+            c.check_okay()
+
+    def adb_reverse_remove(self, local):
+        """
+        Equivalent to `adb -s <serial> reverse --remove <local>`
+
+        Args:
+            local (str): Such as 'tcp:2437'
+        """
+        with self.adb_client._connect() as c:
+            c.send_command(f"host:transport:{self.serial}")
+            c.check_okay()
+            list_cmd = f"reverse:killforward:{local}"
+            c.send_command(list_cmd)
+            c.check_okay()
+
+    def adb_push(self, local, remote):
+        """
+        Args:
+            local (str):
+            remote (str):
+
+        Returns:
+            str:
+        """
+        cmd = ['push', local, remote]
+        return self.adb_command(cmd)
+
+    @Config.when(DEVICE_OVER_HTTP=False)
+    def adb_connect(self, serial):
+        """
+        Connect to a serial, try 3 times at max.
+        If there's an old ADB server running while Alas is using a newer one, which happens on Chinese emulators,
+        the first connection is used to kill the other one, and the second is the real connect.
+
+        Args:
+            serial (str):
+
+        Returns:
+            bool: If success
+        """
+        # Disconnect offline device before connecting
+        for device in self.list_device():
+            if device.status == 'offline':
+                logger.warning(f'Device {serial} is offline, disconnect it before connecting')
+                self.adb_disconnect(serial)
+            elif device.status == 'unauthorized':
+                logger.error(f'Device {serial} is unauthorized, please accept ADB debugging on your device')
+            elif device.status == 'device':
+                pass
+            else:
+                logger.warning(f'Device {serial} is is having a unknown status: {device.status}')
+
+        # Skip for emulator-5554
+        if 'emulator-' in serial:
+            logger.info(f'"{serial}" is a `emulator-*` serial, skip adb connect')
+            return True
+        if re.match(r'^[a-zA-Z0-9]+$', serial):
+            logger.info(f'"{serial}" seems to be a Android serial, skip adb connect')
+            return True
+
+        # Try to connect
+        for _ in range(3):
+            msg = self.adb_client.connect(serial)
+            logger.info(msg)
+            if 'connected' in msg:
+                # Connected to 127.0.0.1:59865
+                # Already connected to 127.0.0.1:59865
+                return True
+            elif 'bad port' in msg:
+                # bad port number '598265' in '127.0.0.1:598265'
+                logger.error(msg)
+                possible_reasons('Serial incorrect, might be a typo')
+                raise RequestHumanTakeover
+            elif '(10061)' in msg:
+                # cannot connect to 127.0.0.1:55555:
+                # No connection could be made because the target machine actively refused it. (10061)
+                logger.info(msg)
+                logger.warning('No such device exists, please restart the emulator or set a correct serial')
+                raise EmulatorNotRunningError
+
+        # Failed to connect
+        logger.warning(f'Failed to connect {serial} after 3 trial, assume connected')
+        self.detect_device()
+        return False
+
+    @Config.when(DEVICE_OVER_HTTP=True)
+    def adb_connect(self, serial):
+        # No adb connect if over http
+        return True
+
+    def adb_disconnect(self, serial):
+        msg = self.adb_client.disconnect(serial)
+        if msg:
+            logger.info(msg)
+
+        del_cached_property(self, 'hermit_session')
+        del_cached_property(self, 'droidcast_session')
+        del_cached_property(self, 'minitouch_builder')
+        del_cached_property(self, 'reverse_server')
+
+    def adb_restart(self):
+        """
+            Reboot adb client
+        """
+        logger.info('Restart adb')
+        # Kill current client
+        self.adb_client.server_kill()
+        # Init adb client
+        del_cached_property(self, 'adb_client')
+        _ = self.adb_client
+
+    @Config.when(DEVICE_OVER_HTTP=False)
+    def adb_reconnect(self):
+        """
+           Reboot adb client if no device found, otherwise try reconnecting device.
+        """
+        # if self.config.Emulator_AdbRestart and len(self.list_device()) == 0:
+        if self.config.get_arg('Script', 'Device', 'AdbRestart') and len(self.list_device()) == 0:
+            # Restart Adb
+            self.adb_restart()
+            # Connect to device
+            self.adb_connect(self.serial)
+            self.detect_device()
+        else:
+            self.adb_disconnect(self.serial)
+            self.adb_connect(self.serial)
+            self.detect_device()
+
+    @Config.when(DEVICE_OVER_HTTP=True)
+    def adb_reconnect(self):
+        logger.warning(
+            f'When connecting a device over http: {self.serial} '
+            f'adb_reconnect() is skipped, you may need to restart ATX manually'
+        )
+
+    def install_uiautomator2(self):
+        """
+        Init uiautomator2 and remove minicap.
+        """
+        logger.info('Install uiautomator2')
+        init = u2.init.Initer(self.adb, loglevel=logging.DEBUG)
+        # MuMu X has no ro.product.cpu.abi, pick abi from ro.product.cpu.abilist
+        if init.abi not in ['x86_64', 'x86', 'arm64-v8a', 'armeabi-v7a', 'armeabi']:
+            init.abi = init.abis[0]
+        init.set_atx_agent_addr('127.0.0.1:7912')
+        try:
+            init.install()
+        except ConnectionError:
+            u2.init.GITHUB_BASEURL = 'http://tool.appetizer.io/openatx'
+            init.install()
+        self.uninstall_minicap()
+
+    def uninstall_minicap(self):
+        """ minicap can't work or will send compressed images on some emulators. """
+        logger.info('Removing minicap')
+        self.adb_shell(["rm", "/data/local/tmp/minicap"])
+        self.adb_shell(["rm", "/data/local/tmp/minicap.so"])
+
+    @Config.when(DEVICE_OVER_HTTP=False)
+    def restart_atx(self):
+        """
+        Minitouch supports only one connection at a time.
+        Restart ATX to kick the existing one.
+        """
+        logger.info('Restart ATX')
+        atx_agent_path = '/data/local/tmp/atx-agent'
+        self.adb_shell([atx_agent_path, 'server', '--stop'])
+        self.adb_shell([atx_agent_path, 'server', '--nouia', '-d', '--addr', '127.0.0.1:7912'])
+
+    @Config.when(DEVICE_OVER_HTTP=True)
+    def restart_atx(self):
+        logger.warning(
+            f'When connecting a device over http: {self.serial} '
+            f'restart_atx() is skipped, you may need to restart ATX manually'
+        )
+
+    @staticmethod
+    def sleep(second):
+        """
+        Args:
+            second(int, float, tuple):
+        """
+        time.sleep(ensure_time(second))
+
+    _orientation_description = {
+        0: 'Normal',
+        1: 'HOME key on the right',
+        2: 'HOME key on the top',
+        3: 'HOME key on the left',
+    }
+    orientation = 0
+
+    @retry
+    def get_orientation(self):
+        """
+        Rotation of the phone
+
+        Returns:
+            int:
+                0: 'Normal'
+                1: 'HOME key on the right'
+                2: 'HOME key on the top'
+                3: 'HOME key on the left'
+        """
+        _DISPLAY_RE = re.compile(
+            r'.*DisplayViewport{.*valid=true, .*orientation=(?P<orientation>\d+), .*deviceWidth=(?P<width>\d+), deviceHeight=(?P<height>\d+).*'
+        )
+        output = self.adb_shell(['dumpsys', 'display'])
+
+        res = _DISPLAY_RE.search(output, 0)
+
+        if res:
+            o = int(res.group('orientation'))
+            if o in Connection._orientation_description:
+                pass
+            else:
+                o = 0
+                logger.warning(f'Invalid device orientation: {o}, assume it is normal')
+        else:
+            o = 0
+            logger.warning('Unable to get device orientation, assume it is normal')
+
+        self.orientation = o
+        logger.attr('Device Orientation', f'{o} ({Connection._orientation_description.get(o, "Unknown")})')
+        return o
+
+    @retry
+    def list_device(self):
+        """
+        Returns:
+            SelectedGrids[AdbDeviceWithStatus]:
+        """
+        devices = []
+        try:
+            with self.adb_client._connect() as c:
+                c.send_command("host:devices")
+                c.check_okay()
+                output = c.read_string_block()
+                for line in output.splitlines():
+                    parts = line.strip().split("\t")
+                    if len(parts) != 2:
+                        continue
+                    device = AdbDeviceWithStatus(self.adb_client, parts[0], parts[1])
+                    devices.append(device)
+        except ConnectionResetError as e:
+            # Happens only on CN users.
+            # ConnectionResetError: [WinError 10054] 远程主机强迫关闭了一个现有的连接。
+            logger.error(e)
+            if '强迫关闭' in str(e):
+                logger.critical('无法连接至ADB服务,请关闭UU加速器、原神私服、以及一些劣质代理软件。'
+                                '它们会劫持电脑上所有的网络连接,包括Alas与模拟器之间的本地连接。')
+        return devices
+
+    def detect_device(self):
+        """
+        Find available devices
+        If serial=='auto' and only 1 device detected, use it
+        """
+        logger.hr('Detect device')
+        logger.info('Here are the available devices, '
+                    'copy to Alas.Emulator.Serial to use it or set Alas.Emulator.Serial="auto"')
+        devices = self.list_device()
+
+        # Show available devices
+        available = devices.select(status='device')
+        for device in available:
+            logger.info(device.serial)
+        if not len(available):
+            logger.info('No available devices')
+
+        # Show unavailable devices if having any
+        unavailable = devices.delete(available)
+        if len(unavailable):
+            logger.info('Here are the devices detected but unavailable')
+            for device in unavailable:
+                logger.info(f'{device.serial} ({device.status})')
+
+        # Auto device detection
+        if self.config.get_arg('Script', 'Device', 'Serial') == 'auto':
+        # if self.config.Emulator_Serial == 'auto':
+            if available.count == 0:
+                logger.critical('No available device found, auto device detection cannot work, '
+                                'please set an exact serial in Alas.Emulator.Serial instead of using "auto"')
+                raise RequestHumanTakeover
+            elif available.count == 1:
+                logger.info(f'Auto device detection found only one device, using it')
+                self.serial = devices[0].serial
+                del_cached_property(self, 'adb')
+            else:
+                logger.critical('Multiple devices found, auto device detection cannot decide which to choose, '
+                                'please copy one of the available devices listed above to Alas.Emulator.Serial')
+                raise RequestHumanTakeover
+
+        # Handle LDPlayer
+        # LDPlayer serial jumps between `127.0.0.1:5555+{X}` and `emulator-5554+{X}`
+        port_serial, emu_serial = get_serial_pair(self.serial)
+        if port_serial and emu_serial:
+            # Might be LDPlayer, check connected devices
+            port_device = devices.select(serial=port_serial).first_or_none()
+            emu_device = devices.select(serial=emu_serial).first_or_none()
+            if port_device and emu_device:
+                # Paired devices found, check status to get the correct one
+                if port_device.status == 'device' and emu_device.status == 'offline':
+                    self.serial = port_serial
+                    logger.info(f'LDPlayer device pair found: {port_device}, {emu_device}. '
+                                f'Using serial: {self.serial}')
+                elif port_device.status == 'offline' and emu_device.status == 'device':
+                    self.serial = emu_serial
+                    logger.info(f'LDPlayer device pair found: {port_device}, {emu_device}. '
+                                f'Using serial: {self.serial}')
+            elif not devices.select(serial=self.serial):
+                # Current serial not found
+                if port_device and not emu_device:
+                    logger.info(f'Current serial {self.serial} not found but paired device {port_serial} found. '
+                                f'Using serial: {port_serial}')
+                    self.serial = port_serial
+                if not port_device and emu_device:
+                    logger.info(f'Current serial {self.serial} not found but paired device {emu_serial} found. '
+                                f'Using serial: {emu_serial}')
+                    self.serial = emu_serial
+
+    @retry
+    def list_package(self, show_log=True):
+        """
+        Find all packages on device.
+        Use dumpsys first for faster.
+        """
+        # 80ms
+        if show_log:
+            logger.info('Get package list')
+        output = self.adb_shell(r'dumpsys package | grep "Package \["')
+        packages = re.findall(r'Package \[([^\s]+)\]', output)
+        if len(packages):
+            return packages
+
+        # 200ms
+        if show_log:
+            logger.info('Get package list')
+        output = self.adb_shell(['pm', 'list', 'packages'])
+        packages = re.findall(r'package:([^\s]+)', output)
+        return packages
+
+    def list_azurlane_packages(self, keywords=('azurlane', 'blhx'), show_log=True):
+        """
+        Args:
+            keywords:
+            show_log:
+
+        Returns:
+            list[str]: List of package names
+        """
+        packages = self.list_package(show_log=show_log)
+        packages = [p for p in packages if any([k in p.lower() for k in keywords])]
+        return packages
+
+    def detect_package(self, keywords=('azurlane', 'blhx'), set_config=True):
+        """
+        Show all possible packages with the given keyword on this device.
+        """
+        logger.hr('Detect package')
+        packages = self.list_azurlane_packages(keywords=keywords)
+
+        # Show packages
+        logger.info(f'Here are the available packages in device "{self.serial}", '
+                    f'copy to Alas.Emulator.PackageName to use it')
+        if len(packages):
+            for package in packages:
+                logger.info(package)
+        else:
+            logger.info(f'No available packages on device "{self.serial}"')
+
+        # Auto package detection
+        if len(packages) == 0:
+            logger.critical(f'No {keywords[0]} package found, '
+                            f'please confirm {keywords[0]} has been installed on device "{self.serial}"')
+            raise RequestHumanTakeover
+        if len(packages) == 1:
+            logger.info('Auto package detection found only one package, using it')
+            self.package = packages[0]
+            # Set config
+            if set_config:
+                self.config.Emulator_PackageName = self.package
+            # Set server
+            logger.info('Server changed, release resources')
+            # set_server(self.package)
+        else:
+            logger.critical(
+                f'Multiple {keywords[0]} packages found, auto package detection cannot decide which to choose, '
+                'please copy one of the available devices listed above to Alas.Emulator.PackageName')
+            raise RequestHumanTakeover

+ 284 - 0
module/device/connection_attr.py

@@ -0,0 +1,284 @@
+# This Python file uses the following encoding: utf-8
+# copy from alas
+import os
+import re
+
+import adbutils
+import uiautomator2 as u2
+from adbutils import AdbClient, AdbDevice
+
+from module.base.decorator import cached_property
+from module.config.config import Config
+from module.config.utils import deep_iter
+from module.exception import RequestHumanTakeover
+from module.logger import logger
+
+class ConnectionAttr:
+    config: Config
+    serial: str
+
+    adb_binary_list = [
+        './bin/adb/adb.exe',
+        './toolkit/Lib/site-packages/adbutils/binaries/adb.exe',
+        '/usr/bin/adb'
+    ]
+
+    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 = Config(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(self.config.__class__, 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(8) + 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
+
+    def serial_check(self):
+        """
+        serial check
+        """
+        # Chinese colon
+        if ':' in self.serial:
+            self.serial = self.serial.replace(':', ':')
+            logger.warning(f'Serial {self.config.Emulator_Serial} is revised to {self.serial}')
+            self.config.Emulator_Serial = self.serial
+        if self.is_bluestacks4_hyperv:
+            self.serial = self.find_bluestacks4_hyperv(self.serial)
+        if self.is_bluestacks5_hyperv:
+            self.serial = self.find_bluestacks5_hyperv(self.serial)
+        if "127.0.0.1:58526" in self.serial:
+            logger.warning('Serial 127.0.0.1:58526 seems to be WSA, '
+                           'please use "wsa-0" or others instead')
+            raise RequestHumanTakeover
+        if self.is_wsa:
+            self.serial = '127.0.0.1:58526'
+            if self.config.Emulator_ScreenshotMethod != 'uiautomator2' \
+                    or self.config.Emulator_ControlMethod != 'uiautomator2':
+                with self.config.multi_set():
+                    self.config.Emulator_ScreenshotMethod = 'uiautomator2'
+                    self.config.Emulator_ControlMethod = 'uiautomator2'
+        if self.is_over_http:
+            if self.config.Emulator_ScreenshotMethod not in ["ADB", "uiautomator2", "aScreenCap"] \
+                    or self.config.Emulator_ControlMethod not in ["ADB", "uiautomator2", "minitouch"]:
+                logger.warning(
+                    f'When connecting to a device over http: {self.serial} '
+                    f'ScreenshotMethod can only use ["ADB", "uiautomator2", "aScreenCap"], '
+                    f'ControlMethod can only use ["ADB", "uiautomator2", "minitouch"]'
+                )
+                raise RequestHumanTakeover
+
+    @cached_property
+    def is_bluestacks4_hyperv(self):
+        return "bluestacks4-hyperv" in self.serial
+
+    @cached_property
+    def is_bluestacks5_hyperv(self):
+        return "bluestacks5-hyperv" in self.serial
+
+    @cached_property
+    def is_bluestacks_hyperv(self):
+        return self.is_bluestacks4_hyperv or self.is_bluestacks5_hyperv
+
+    @cached_property
+    def is_wsa(self):
+        return bool(re.match(r'^wsa', self.serial))
+
+    @cached_property
+    def is_mumu_family(self):
+        return self.serial == '127.0.0.1:7555'
+
+    @cached_property
+    def is_emulator(self):
+        return self.serial.startswith('emulator-') or self.serial.startswith('127.0.0.1:')
+
+    @cached_property
+    def is_network_device(self):
+        return bool(re.match(r'\d+\.\d+\.\d+\.\d+:\d+', self.serial))
+
+    @cached_property
+    def is_over_http(self):
+        return bool(re.match(r"^https?://", self.serial))
+
+    @cached_property
+    def is_chinac_phone_cloud(self):
+        # Phone cloud with public ADB connection
+        # Serial like xxx.xxx.xxx.xxx:301
+        return bool(re.search(r":30[0-9]$", self.serial))
+
+    @staticmethod
+    def find_bluestacks4_hyperv(serial):
+        """
+        Find dynamic serial of BlueStacks4 Hyper-V Beta.
+
+        Args:
+            serial (str): 'bluestacks4-hyperv', 'bluestacks4-hyperv-2' for multi instance, and so on.
+
+        Returns:
+            str: 127.0.0.1:{port}
+        """
+        from winreg import HKEY_LOCAL_MACHINE, OpenKey, QueryValueEx
+
+        logger.info("Use BlueStacks4 Hyper-V Beta")
+        logger.info("Reading Realtime adb port")
+
+        if serial == "bluestacks4-hyperv":
+            folder_name = "Android"
+        else:
+            folder_name = f"Android_{serial[19:]}"
+
+        try:
+            with OpenKey(HKEY_LOCAL_MACHINE,
+                         rf"SOFTWARE\BlueStacks_bgp64_hyperv\Guests\{folder_name}\Config") as key:
+                port = QueryValueEx(key, "BstAdbPort")[0]
+        except FileNotFoundError:
+            logger.error(rf'Unable to find registry HKEY_LOCAL_MACHINE\SOFTWARE\BlueStacks_bgp64_hyperv\Guests\{folder_name}\Config')
+            logger.error('Please confirm that your are using BlueStack 4 hyper-v and not regular BlueStacks 4')
+            logger.error(r'Please check if there is any other emulator instances under '
+                         r'registry HKEY_LOCAL_MACHINE\SOFTWARE\BlueStacks_bgp64_hyperv\Guests')
+            raise RequestHumanTakeover
+        logger.info(f"New adb port: {port}")
+        return f"127.0.0.1:{port}"
+
+    @staticmethod
+    def find_bluestacks5_hyperv(serial):
+        """
+        Find dynamic serial of BlueStacks5 Hyper-V.
+
+        Args:
+            serial (str): 'bluestacks5-hyperv', 'bluestacks5-hyperv-1' for multi instance, and so on.
+
+        Returns:
+            str: 127.0.0.1:{port}
+        """
+        from winreg import HKEY_LOCAL_MACHINE, OpenKey, QueryValueEx
+
+        logger.info("Use BlueStacks5 Hyper-V")
+        logger.info("Reading Realtime adb port")
+
+        if serial == "bluestacks5-hyperv":
+            parameter_name = r"bst\.instance\.(Nougat64|Pie64)\.status\.adb_port"
+        else:
+            parameter_name = rf"bst\.instance\.(Nougat64|Pie64)_{serial[19:]}\.status.adb_port"
+
+        try:
+            with OpenKey(HKEY_LOCAL_MACHINE, r"SOFTWARE\BlueStacks_nxt") as key:
+                directory = QueryValueEx(key, 'UserDefinedDir')[0]
+        except FileNotFoundError:
+            try:
+                with OpenKey(HKEY_LOCAL_MACHINE, r"SOFTWARE\BlueStacks_nxt_cn") as key:
+                    directory = QueryValueEx(key, 'UserDefinedDir')[0]
+            except FileNotFoundError:
+                logger.error('Unable to find registry HKEY_LOCAL_MACHINE\SOFTWARE\BlueStacks_nxt '
+                             'or HKEY_LOCAL_MACHINE\SOFTWARE\BlueStacks_nxt_cn')
+                logger.error('Please confirm that you are using BlueStacks 5 hyper-v and not regular BlueStacks 5')
+                raise RequestHumanTakeover
+        logger.info(f"Configuration file directory: {directory}")
+
+        with open(os.path.join(directory, 'bluestacks.conf'), encoding='utf-8') as f:
+            content = f.read()
+        port = re.search(rf'{parameter_name}="(\d+)"', content)
+        if port is None:
+            logger.warning(f"Did not match the result: {serial}.")
+            raise RequestHumanTakeover
+        port = port.group(2)
+        logger.info(f"Match to dynamic port: {port}")
+        return f"127.0.0.1:{port}"
+
+    @cached_property
+    def adb_binary(self):
+        # Try adb in deploy.yaml
+        # from module.webui.setting import State
+        # file = State.deploy_config.AdbExecutable
+        # file = file.replace('\\', '/')
+        # if os.path.exists(file):
+        #     return os.path.abspath(file)
+        #
+        # # Try existing adb.exe
+        # for file in self.adb_binary_list:
+        #     if os.path.exists(file):
+        #         return os.path.abspath(file)
+
+        # Try adb in python environment
+        import sys
+        file = os.path.join(sys.executable, '../Lib/site-packages/adbutils/binaries/adb.exe')
+        file = os.path.abspath(file).replace('\\', '/')
+        if os.path.exists(file):
+            return file
+
+        # Use adb in system PATH
+        file = 'adb'
+        return file
+
+    @cached_property
+    def adb_client(self) -> AdbClient:
+        host = '127.0.0.1'
+        port = 5037
+
+        # Trying to get adb port from env
+        env = os.environ.get('ANDROID_ADB_SERVER_PORT', None)
+        if env is not None:
+            try:
+                port = int(env)
+            except ValueError:
+                logger.warning(f'Invalid environ variable ANDROID_ADB_SERVER_PORT={port}, using default port')
+
+        logger.attr('AdbClient', f'AdbClient({host}, {port})')
+        return AdbClient(host, port)
+
+    @cached_property
+    def adb(self) -> AdbDevice:
+        return AdbDevice(self.adb_client, self.serial)
+
+    @cached_property
+    def u2(self) -> u2.Device:
+        if self.is_over_http:
+            # Using uiautomator2_http
+            device = u2.connect(self.serial)
+        else:
+            # Normal uiautomator2
+            if self.serial.startswith('emulator-') or self.serial.startswith('127.0.0.1:'):
+                device = u2.connect_usb(self.serial)
+            else:
+                device = u2.connect(self.serial)
+
+        # Stay alive
+        device.set_new_command_timeout(604800)
+
+        logger.attr('u2.Device', f'Device(atx_agent_url={device._get_atx_agent_url()})')
+        return device
+
+

+ 311 - 0
module/device/method/utils.py

@@ -0,0 +1,311 @@
+import random
+import re
+import socket
+import time
+
+import uiautomator2 as u2
+from adbutils import AdbTimeout, _AdbStreamConnection
+from lxml import etree
+
+from module.base.decorator import cached_property
+from module.logger import logger
+
+RETRY_TRIES = 5
+RETRY_DELAY = 3
+
+
+def is_port_using(port_num):
+    """ if port is using by others, return True. else return False """
+    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+    s.settimeout(2)
+
+    try:
+        s.bind(('127.0.0.1', port_num))
+        return False
+    except OSError:
+        # Address already bind
+        return True
+    finally:
+        s.close()
+
+
+def random_port(port_range):
+    """ get a random port from port set """
+    new_port = random.choice(list(range(*port_range)))
+    if is_port_using(new_port):
+        return random_port(port_range)
+    else:
+        return new_port
+
+
+def recv_all(stream, chunk_size=4096, recv_interval=0.000) -> bytes:
+    """
+    Args:
+        stream:
+        chunk_size:
+        recv_interval (float): Default to 0.000, use 0.001 if receiving as server
+
+    Returns:
+        bytes:
+
+    Raises:
+        AdbTimeout
+    """
+    if isinstance(stream, _AdbStreamConnection):
+        stream = stream.conn
+        stream.settimeout(10)
+    else:
+        stream.settimeout(10)
+
+    try:
+        fragments = []
+        while 1:
+            chunk = stream.recv(chunk_size)
+            if chunk:
+                fragments.append(chunk)
+                # See https://stackoverflow.com/questions/23837827/python-server-program-has-high-cpu-usage/41749820#41749820
+                time.sleep(recv_interval)
+            else:
+                break
+        return remove_shell_warning(b''.join(fragments))
+    except socket.timeout:
+        raise AdbTimeout('adb read timeout')
+
+
+def possible_reasons(*args):
+    """
+    Show possible reasons
+
+        Possible reason #1: <reason_1>
+        Possible reason #2: <reason_2>
+    """
+    for index, reason in enumerate(args):
+        index += 1
+        logger.critical(f'Possible reason #{index}: {reason}')
+
+
+class PackageNotInstalled(Exception):
+    pass
+
+
+class ImageTruncated(Exception):
+    pass
+
+
+def retry_sleep(trial):
+    # First trial
+    if trial == 0:
+        pass
+    # Failed once, fast retry
+    elif trial == 1:
+        pass
+    # Failed twice
+    elif trial == 2:
+        time.sleep(1)
+    # Failed more
+    else:
+        time.sleep(RETRY_DELAY)
+
+
+def handle_adb_error(e):
+    """
+    Args:
+        e (Exception):
+
+    Returns:
+        bool: If should retry
+    """
+    text = str(e)
+    if 'not found' in text:
+        # When you call `adb disconnect <serial>`
+        # Or when adb server was killed (low possibility)
+        # AdbError(device '127.0.0.1:59865' not found)
+        logger.error(e)
+        return True
+    elif 'timeout' in text:
+        # AdbTimeout(adb read timeout)
+        logger.error(e)
+        return True
+    elif 'closed' in text:
+        # AdbError(closed)
+        # Usually after AdbTimeout(adb read timeout)
+        # Disconnect and re-connect should fix this.
+        logger.error(e)
+        return True
+    elif 'device offline' in text:
+        # AdbError(device offline)
+        # When a device that has been connected wirelessly is disconnected passively,
+        # it does not disappear from the adb device list,
+        # but will be displayed as offline.
+        # In many cases, such as disconnection and recovery caused by network fluctuations,
+        # or after VMOS reboot when running Alas on a phone,
+        # the device is still available, but it needs to be disconnected and re-connected.
+        logger.error(e)
+        return True
+    elif 'is offline' in text:
+        # RuntimeError: USB device 127.0.0.1:7555 is offline
+        # Raised by uiautomator2 when current adb service is killed by another version of adb service.
+        logger.error(e)
+        return True
+    elif 'unknown host service' in text:
+        # AdbError(unknown host service)
+        # Another version of ADB service started, current ADB service has been killed.
+        # Usually because user opened a Chinese emulator, which uses ADB from the Stone Age.
+        logger.error(e)
+        return True
+    else:
+        # AdbError()
+        logger.exception(e)
+        possible_reasons(
+            'If you are using BlueStacks or LD player or WSA, please enable ADB in the settings of your emulator',
+            'Emulator died, please restart emulator',
+            'Serial incorrect, no such device exists or emulator is not running'
+        )
+        return False
+
+
+def get_serial_pair(serial):
+    """
+    Args:
+        serial (str):
+
+    Returns:
+        str, str: `127.0.0.1:5555+{X}` and `emulator-5554+{X}`, 0 <= X <= 32
+    """
+    if serial.startswith('127.0.0.1:'):
+        try:
+            port = int(serial[10:])
+            if 5555 <= port <= 5555 + 32:
+                return f'127.0.0.1:{port}', f'emulator-{port - 1}'
+        except (ValueError, IndexError):
+            pass
+    if serial.startswith('emulator-'):
+        try:
+            port = int(serial[9:])
+            if 5554 <= port <= 5554 + 32:
+                return f'127.0.0.1:{port + 1}', f'emulator-{port}'
+        except (ValueError, IndexError):
+            pass
+
+    return None, None
+
+
+def remove_prefix(s, prefix):
+    """
+    Remove prefix of a string or bytes like `string.removeprefix(prefix)`, which is on Python3.9+
+
+    Args:
+        s (str, bytes):
+        prefix (str, bytes):
+
+    Returns:
+        str, bytes:
+    """
+    return s[len(prefix):] if s.startswith(prefix) else s
+
+
+def remove_shell_warning(s):
+    """
+    Remove warnings from shell
+
+    Args:
+        s (str, bytes):
+
+    Returns:
+        str, bytes:
+    """
+    # WARNING: linker: [vdso]: unused DT entry: type 0x70000001 arg 0x0\n\x89PNG\r\n\x1a\n\x00\x00\x00\rIH
+    if isinstance(s, bytes):
+        if s.startswith(b'WARNING'):
+            try:
+                s = s.split(b'\n', maxsplit=1)[1]
+            except IndexError:
+                pass
+        return s
+        # return re.sub(b'^WARNING.+\n', b'', s)
+    elif isinstance(s, str):
+        if s.startswith('WARNING'):
+            try:
+                s = s.split('\n', maxsplit=1)[1]
+            except IndexError:
+                pass
+    return s
+
+
+class IniterNoMinicap(u2.init.Initer):
+    @property
+    def minicap_urls(self):
+        """
+        Don't install minicap on emulators, return empty urls.
+
+        binary from https://github.com/openatx/stf-binaries
+        only got abi: armeabi-v7a and arm64-v8a
+        """
+        return []
+
+
+class Device(u2.Device):
+    def show_float_window(self, show=True):
+        """
+        Don't show float windows.
+        """
+        pass
+
+
+# Monkey patch
+u2.init.Initer = IniterNoMinicap
+u2.Device = Device
+
+
+class HierarchyButton:
+    """
+    Convert UI hierarchy to an object like the Button in Alas.
+    """
+    _name_regex = re.compile('@.*?=[\'\"](.*?)[\'\"]')
+
+    def __init__(self, hierarchy: etree._Element, xpath: str):
+        self.hierarchy = hierarchy
+        self.xpath = xpath
+        self.nodes = hierarchy.xpath(xpath)
+
+    @cached_property
+    def name(self):
+        res = HierarchyButton._name_regex.findall(self.xpath)
+        if res:
+            return res[0]
+        else:
+            return 'HierarchyButton'
+
+    @cached_property
+    def count(self):
+        return len(self.nodes)
+
+    @cached_property
+    def exist(self):
+        return self.count == 1
+
+    @cached_property
+    def area(self):
+        if self.exist:
+            bounds = self.nodes[0].attrib.get("bounds")
+            lx, ly, rx, ry = map(int, re.findall(r"\d+", bounds))
+            return lx, ly, rx, ry
+        else:
+            return None
+
+    @cached_property
+    def button(self):
+        return self.area
+
+    def __bool__(self):
+        return self.exist
+
+    def __str__(self):
+        return self.name
+
+    @cached_property
+    def focused(self):
+        if self.exist:
+            return self.nodes[0].attrib.get("focused").lower() == 'true'
+        else:
+            return False

+ 59 - 0
module/exception.py

@@ -0,0 +1,59 @@
+class CampaignEnd(Exception):
+    pass
+
+
+class MapDetectionError(Exception):
+    pass
+
+
+class MapWalkError(Exception):
+    pass
+
+
+class MapEnemyMoved(Exception):
+    pass
+
+
+class CampaignNameError(Exception):
+    pass
+
+
+class ScriptError(Exception):
+    # This is likely to be a mistake of developers, but sometimes a random issue
+    pass
+
+
+class ScriptEnd(Exception):
+    pass
+
+
+class GameStuckError(Exception):
+    pass
+
+
+class GameBugError(Exception):
+    # An error has occurred in Azur Lane game client. Alas is unable to handle.
+    # A restart should fix it.
+    pass
+
+
+class GameTooManyClickError(Exception):
+    pass
+
+
+class EmulatorNotRunningError(Exception):
+    pass
+
+
+class GameNotRunningError(Exception):
+    pass
+
+
+class GamePageUnknownError(Exception):
+    pass
+
+
+class RequestHumanTakeover(Exception):
+    # Request human takeover
+    # Alas is unable to handle such error, probably because of wrong settings.
+    pass

+ 3 - 1
requirements-in.txt

@@ -3,4 +3,6 @@ adbutils==1.2.9
 uiautomator2==2.16.23
 
 rich==13.3.5
-pyyaml==6.0
+pyyaml==6.0
+numpy==1.24.3
+opencv-python==4.7.0.72