Exemplo n.º 1
0
def ensure_adb_alive():
    if check_adb_alive():
        return
    logger.common('尝试启动 adb server')
    import subprocess
    adbbin = RootData.get('device/adb_binary', None)
    if adbbin is None:
        adb_binaries = [
            'adb',
            os.path.join(RootData.get("ADB_SERVER", ("127.0.0.1", 5037)),
                         'adb')
        ]
        findadb = find_adb_from_android_sdk()
        if findadb is not None:
            adb_binaries.append(findadb)
    else:
        adb_binaries = [adbbin]
    for adbbin in adb_binaries:
        try:
            logger.debug('trying %r' % adbbin)
            subprocess.run([adbbin, 'start-server'], check=True)
            return True
        except FileNotFoundError:
            pass
        except subprocess.CalledProcessError:
            pass
    raise OSError("can't start adb server")
Exemplo n.º 2
0
    def __init__(self, adb_serial=None):
        # os.chdir(ADB_ROOT)
        self.ADB_ROOT = RootData.get("ADB_ROOT")
        self.adb_serial = adb_serial
        self.host_session_factory = lambda: ADBClientSession(
            RootData.get("ADB_SERVER", ("127.0.0.1", 5037)))
        self.rch = None
        if self.adb_serial is None:
            self.adb_serial = self.__adb_device_name_detector()
        self.device_session_factory = lambda: self.host_session_factory(
        ).device(self.adb_serial)
        self.cache_screenshot = RootData.get('device/cache_screenshot', True)
        self.last_screenshot_timestamp = 0
        self.last_screenshot_duration = 0
        self.last_screenshot = None

        if RootData.get('device/try_emulator_enhanced_mode', True):
            loopbacks = self._detect_loopbacks()
            if len(loopbacks):
                logger.debug('possible loopback addresses: %s' %
                             repr(loopbacks))
                self.rch = revconn.ReverseConnectionHost()
                self.rch.start()
                if self._test_reverse_connection(loopbacks):
                    logger.common('正在使用模拟器优化模式')
                    self.screencap = self._reverse_connection_screencap
                else:
                    self.rch.stop()
        else:
            self.loopback = None
Exemplo n.º 3
0
    def __adb_device_name_detector(self):
        devices = [
            x for x in self.host_session_factory().devices()
            if x[1] != 'offline'
        ]

        if len(devices) == 0:
            auto_connect = RootData.get('device/adb_auto_connect', None)
            if auto_connect is not None:
                logger.common('没有已连接设备,尝试连接 %s' % auto_connect)
                with contextlib.suppress(RuntimeError):
                    self.host_session_factory().disconnect(auto_connect)
                for x in self.host_session_factory().devices():
                    if x[1] == 'offline':
                        with contextlib.suppress(RuntimeError):
                            self.host_session_factory().disconnect(x[0])
                self.host_session_factory().connect(auto_connect)
                time.sleep(1)
            else:
                raise RuntimeError('找不到可用设备')
        devices = [
            x for x in self.host_session_factory().devices()
            if x[1] != 'offline'
        ]

        always_use_device = RootData.get('device/adb_always_use_device', None)
        if always_use_device is not None:
            if always_use_device not in (x[0] for x in devices):
                raise RuntimeError('设备 %s 未连接' % always_use_device)
            return always_use_device
        logger.debug(f"devices({devices})")
        if len(devices) == 1:
            device_name = devices[0][0]
        elif len(devices) > 1:
            logger.common("检测到多台设备")
            for i, (serial, status) in enumerate(devices):
                print("%2d. %s" % (i, serial))
            num = 0
            while True:
                try:
                    num = int(input("请输入序号选择设备: "))
                    if not 0 <= num < len(devices):
                        raise ValueError()
                    break
                except ValueError:
                    logger.error("输入不合法,请重新输入")
            device_name = devices[num][0]
        else:
            raise RuntimeError('找不到可用设备')
        logger.system("确认设备名称:" + device_name)
        return device_name
Exemplo n.º 4
0
 def __init__(self, data=None, cfgdata=None, Magic='cfg', file=None):
     super(Config, self).__init__(data, Magic, file)
     self._cfgread = False
     if cfgdata:
         self.cfg = configTree(importdata=cfgdata)
     else:
         self.cfg = configTree()
     self.version = RootData.get("Config_version")
     self.read = self.cfg
     self.__u = []
Exemplo n.º 5
0
def check_adb_alive():
    try:
        sess = ADBClientSession(RootData.get("ADB_SERVER",
                                             ("127.0.0.1", 5037)))
        version = int(
            sess.service('host:version').read_response().decode(), 16)
        logger.debug('ADB server version %d' % version)
        return True
    except ConnectionRefusedError:
        return False
    except RuntimeError:
        return False
Exemplo n.º 6
0
    def readConfig(self,
                   config=None,
                   keepseek=False,
                   inner=False,
                   debug=False):
        # logger.system('<+>读取配置文件中...',flush=True)
        # TODO:处理空文件时异常:mrfzdata.mr ->list型数据
        # F = Config(cfgdata=json.load(open('.\MRFZdata\ArknightsGameData\excel\mission_table.json','rb')),Magic='mrfzd',file='mrfzdata2.mr')
        # D = Config(Magic='mrfzd',file='mrfzdata.mr')
        # R = Config(Magic='test',file='testcfg.t')
        # seek在mission->guide_1->unlockParam 166
        if config == None:
            config = self.cfg
        if self._fileopen:
            hand = self.data.tell()
        else:
            if hasattr(self, '_filename'):
                self.readFile(self._filename)
                hand = 0
            else:
                logger.error('<!>无可读取内容!配置不存在')
                return False
        if self._cfgread:
            self.cfg = configTree()
            config = self.cfg
        if self.checkHeader():
            self.version = struct.unpack('>f', self.readData(4))[0]
            if round(self.version,
                     1) < RootData.get("Config_version") and not inner:
                logger.error("<!>配置文件版本(%.1f)高于程序版本!无法读取" % self.version)
                return False
            elif round(self.version,
                       1) > RootData.get("Config_version") and not inner:
                logger.warning("<!>配置文件版本(%.1f)低于程序版本!保存时将使用当前版本存储配置!" %
                               self.version)
            if keepseek:
                self.data.seek(hand)
            _ts = time.time()
            if not inner:
                if self.readfromType(bool):
                    logger.error("<!>配置是空的!")
                    return False
                if debug is True:
                    logger.debug('<+>-----------ReadConfig-S-----------')
            while True:
                try:
                    name_len = struct.unpack('>h', self.readData(2))[0]  # 命名长度
                    name = self.readData(name_len).decode()
                    type_ = self.type(self.readData(1))

                    if not type_ == configTree:  # list? ---->item
                        value = self.readfromType(type_)
                        config.set(name, value)
                        if debug is True:
                            logger.debug('<+>[%s]%s.%s(%s): %s' %
                                         (self.data.tell(), config._root, name,
                                          name_len, str(type_)[8:-2:]))
                        if self.readfromType(bool):
                            if debug is True:
                                logger.debug('<+>[%s][t1]end,exit' %
                                             (self.data.tell()))
                            break
                    else:  # folder
                        config.addChild(name)
                        # ->
                        # empty folder ?
                        if self.readfromType(bool):
                            if debug is True:
                                logger.debug('<+>[%s][t2]end,exit' %
                                             (self.data.tell()))
                            break
                        # <-
                        self.readConfig(getattr(config, name),
                                        keepseek=True,
                                        inner=True,
                                        debug=debug)
                        if self.readfromType(bool):
                            if debug is True:
                                logger.debug('<+>[%s][t3]end,exit' %
                                             (self.data.tell()))
                            break
                        else:
                            self.data.seek(self.data.tell() - 1)
                except:
                    logger.error('<!>读取时出现错误 [seek:%s]' % self.data.tell())
                    # logger.system('<r>读取配置文件完成![用时%f秒]' % _ts)
                    return False
            _ts = time.time() - _ts
            if not inner:
                self._cfgread = True
                if debug is True:
                    logger.debug('<+>[%s]-----------ReadConfig-E-----------' %
                                 self.data.tell())
                logger.system('<+>读取配置文件完成![用时%.2f毫秒]' % (_ts * 1000))
            return True
        else:
            logger.error('<!>Magic Code不匹配!')
            return False
Exemplo n.º 7
0
 def createConfig(self):
     self.version = RootData.get("Config_version")
Exemplo n.º 8
0
from config.RootData import RootData
from utils.logger import root_logger as logger
import struct
import sys
import os
import time

RootData.set("Config_version", 1.1)


# 结构体-脚本前置
class Structure(object):
    def __init__(self, data=None, Magic=None, file=None):
        self._filename = None
        self._fileopen = False
        if Magic:
            self.magic = Magic
        if data:
            self.data = data
        if file:
            self.readFile(file)

    def readFile(self, filename):
        if not os.path.exists(filename):
            logger.warning("%s不存在,自动创建!" % filename)
            fn = '.\\' + filename
            f = open(fn, 'w')
            f.write('')
            f.close()
        self._filename = filename
        self.data = open(filename, 'rb')
Exemplo n.º 9
0
import os
import pickle
from functools import lru_cache
import importlib.util
from config.RootData import RootData
import numpy as np
from PIL import Image

import config

if RootData.get("use_archived_resources"):
    import zipfile

    root = 'resources/imgreco'
    archive = zipfile.ZipFile(open(RootData.get("resource_archive"), 'rb'),
                              'r')
    filelist = archive.namelist()

    def get_path(names):
        return '/'.join([root, *names])

    def open_file(path):
        return archive.open(path)

    def get_entries(base):
        prefix = 'resources/imgreco/' + base + '/'
        dirs = []
        files = []
        for name in filelist:
            if name.startswith(prefix):
                name = name[len(prefix):]