Răsfoiți Sursa

feat(device): update

runhey 3 ani în urmă
părinte
comite
58ec73f642

+ 2 - 2
README.md

@@ -48,12 +48,12 @@ oas目前还在开发中,我们期待你的加入,Q群: 465946275
 
 1. 打开本项目[主仓库](https://github.com/runhey/OnmyojiAutoScript/tree/master), 点击右上角的 `Fork`,然后点击下面绿色的 `Create fork`
 
-2. 进入自己账号下的 Alas 仓库,并 `clone` 其中的 `dev` 分支到本地
+2. 进入自己账号下的 oas仓库,并 `clone` 其中的 `dev` 分支到本地
 	```
 	git clone url -b dev
 	```
 
-3. 下载[最新环境包](https://github.com/runhey/OnmyojiAutoScript/releases), 解压复制`toolkit`,`deploy`两个文件夹和`consloe.bat`到本地的仓库根目录,`toolkit`里面包含python最小环境、git环境和GUI启动环境。
+3. 下载[最新环境包](https://github.com/runhey/OnmyojiAutoScript/releases), 解压复制`toolkit`,`deploy`两个文件夹和`console.bat`到本地的仓库根目录,`toolkit`里面包含python最小环境、git环境和GUI启动环境。
 
 3. 安装pip库, 安装后你可以执行`gui.py`启动进行测试
 

+ 0 - 33
config/template.json

@@ -1,33 +0,0 @@
-{
-  "script": {
-    "device": {
-      "serial": "127.0.0.1:7555",
-      "handle": "auto",
-      "package_name": "auto",
-      "screenshot_method": "window_background",
-      "control_method": "window_message",
-      "adb_restart": false
-    },
-    "error": {
-      "handle_error": false,
-      "save_error": false,
-      "screenshot_length": 1
-    },
-    "optimization": {
-      "screenshot_interval": 0.3,
-      "combat_screenshot_interval": 1.0,
-      "task_hoarding_duration": 0,
-      "when_task_queue_empty": "goto_home"
-    }
-  },
-  "restart": {
-    "scheduler": {
-      "enable": false,
-      "next_run": "2023-01-01 00:00:00",
-      "command": "Restart",
-      "success_interval": 0,
-      "failure_interval": 0,
-      "server_update": "00:00"
-    }
-  }
-}

+ 4 - 4
module/device/app_control.py

@@ -12,7 +12,7 @@ class AppControl(Adb, Uiautomator2):
     _app_u2_family = ['uiautomator2', 'minitouch', 'scrcpy']
 
     def app_is_running(self) -> bool:
-        method = self.config.get_arg("Script", 'Emulator', 'ControlMethod')
+        method = self.config.script.emulator.control_method
         # if self.is_wsa:
         #     package = self.app_current_wsa()
         if method in AppControl._app_u2_family:
@@ -25,7 +25,7 @@ class AppControl(Adb, Uiautomator2):
         return package == self.package
 
     def app_start(self):
-        method = self.config.get_arg('Script', 'Device', 'ScreenshotMethod')
+        method = self.config.script.device.screenshot_method
         logger.info(f'App start: {self.package}')
         # if self.config.Emulator_Serial == 'wsa-0':
         #     self.app_start_wsa(display=0)
@@ -35,7 +35,7 @@ class AppControl(Adb, Uiautomator2):
             self.app_start_adb()
 
     def app_stop(self):
-        method = self.config.get_arg('Script', 'Device', 'ScreenshotMethod')
+        method = self.config.script.device.screenshot_method
         logger.info(f'App stop: {self.package}')
         if method in AppControl._app_u2_family:
             self.app_stop_uiautomator2()
@@ -47,7 +47,7 @@ class AppControl(Adb, Uiautomator2):
         Returns:
             etree._Element: Select elements with `self.hierarchy.xpath('//*[@text="Hermit"]')` for example.
         """
-        method = self.config.get_arg('Script', 'Device', 'ScreenshotMethod')
+        method = self.config.script.device.screenshot_method
         if method in AppControl._app_u2_family:
             self.hierarchy = self.dump_hierarchy_uiautomator2()
         else:

+ 3 - 3
module/device/connection.py

@@ -104,7 +104,7 @@ class Connection(ConnectionAttr):
 
         # Package
         # self.package = self.config.Emulator_PackageName
-        self.package = self.config.get_arg('Script', 'Device', 'PackageName')
+        self.package = self.config.script.device.package_name
         if self.package == 'auto':
             self.detect_package()
         else:
@@ -576,7 +576,7 @@ class Connection(ConnectionAttr):
            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:
+        if self.config.script.device.adb_restart and len(self.list_device()) == 0:
             # Restart Adb
             self.adb_restart()
             # Connect to device
@@ -737,7 +737,7 @@ class Connection(ConnectionAttr):
                 logger.info(f'{device.serial} ({device.status})')
 
         # Auto device detection
-        if self.config.get_arg('Script', 'Device', 'Serial') == 'auto':
+        if self.config.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, '

+ 3 - 2
module/device/connection_attr.py

@@ -41,7 +41,8 @@ class ConnectionAttr:
         # Remove global proxies, or uiautomator2 will go through it
         count = 0
         d = dict(**os.environ)
-        d.update(self.config.args)
+        #----------------------------------------------------------------------------------下面的是我注释掉的
+        # d.update(self.config.args)
         for _, v in deep_iter(d, depth=3):
             if not isinstance(v, dict):
                 continue
@@ -64,7 +65,7 @@ class ConnectionAttr:
 
         # Parse custom serial
         # self.serial = str(self.config.Emulator_Serial)
-        self.serial = str(self.config.get_arg('Script', 'Device', 'Serial'))
+        self.serial = str(self.config.script.device.serial)
         self.serial_check()
         self.config.DEVICE_OVER_HTTP = self.is_over_http
 

+ 4 - 4
module/device/control.py

@@ -42,7 +42,7 @@ class Control(Minitouch, Scrcpy, Window):
             'Click %s @ %s' % (point2str(x, y), button)
         )
         method = self.click_methods.get(
-            self.config.get_arg("Script", 'Emulator', 'ControlMethod'),
+            self.config.script.emulator.control_method,
             self.click_adb
         )
         method(x, y)
@@ -79,7 +79,7 @@ class Control(Minitouch, Scrcpy, Window):
         logger.info(
             'Click %s @ %s, %s' % (point2str(x, y), button, duration)
         )
-        method = self.config.get_arg("Script", 'Emulator', 'ControlMethod')
+        method = self.config.script.emulator.control_method
         if method == 'minitouch':
             self.long_click_minitouch(x, y, duration)
         elif method == 'window_message':
@@ -97,7 +97,7 @@ class Control(Minitouch, Scrcpy, Window):
         self.handle_control_check(name)
         p1, p2 = ensure_int(p1, p2)
         duration = ensure_time(duration)
-        method = self.config.get_arg("Script", 'Emulator', 'ControlMethod')
+        method = self.config.script.emulator.control_method
         if method == 'minitouch':
             logger.info('Swipe %s -> %s' % (point2str(*p1), point2str(*p2)))
         elif method == 'window_message':
@@ -168,7 +168,7 @@ class Control(Minitouch, Scrcpy, Window):
         logger.info(
             'Drag %s -> %s' % (point2str(*p1), point2str(*p2))
         )
-        method = self.config.get_arg("Script", 'Emulator', 'ControlMethod')
+        method = self.config.script.emulator.control_method
         if method == 'minitouch':
             self.drag_minitouch(p1, p2, point_random=point_random)
         elif method == 'uiautomator2':

+ 5 - 1
module/device/device.py

@@ -32,7 +32,7 @@ class Device(Screenshot, Control, AppControl, EmulatorManager):
         self.screenshot_interval_set()
 
         # Auto-select the fastest screenshot method
-        if not self.config.is_template_config and self.config.get_arg("Script", 'Device', 'ScreenshotMethod') == 'auto':
+        if not self.config.is_template_config and self.config.script.device.screenshot_method == 'auto':
             self.run_simple_screenshot_benchmark()
 
     def run_simple_screenshot_benchmark(self):
@@ -213,3 +213,7 @@ class Device(Screenshot, Control, AppControl, EmulatorManager):
         super().app_stop()
         self.stuck_record_clear()
         self.click_record_clear()
+
+
+if __name__ == "__main__":
+    device = Device(config_name="oas1")

+ 2 - 2
module/device/handle.py

@@ -120,7 +120,7 @@ class Handle:
         # 获取根的句柄
         self.root_handle_title = ''
         self.root_handle_num = 0
-        self.root_handle = self.config.get_arg('Script', 'Device', 'Handle')
+        self.root_handle = self.config.script.device.handle
         if self.root_handle == "auto":
             logger.info('handle is auto. oas will find window emulator')
             window_list = Handle.all_windows()
@@ -134,7 +134,7 @@ class Handle:
                 self.root_handle_num = self.root_handle
         elif isinstance(self.root_handle, str):
             logger.info('handle is handle string. oas use it as root handle title')
-            if handle_title2num(self.root_handle) !=0:
+            if handle_title2num(self.root_handle) != 0:
                 self.root_handle_num = handle_title2num(self.root_handle)
                 self.root_handle_title = self.root_handle
         logger.info(f'the root handle title is {self.root_handle_title} and num is {self.root_handle_num}')

+ 1 - 0
module/device/method/window.py

@@ -275,5 +275,6 @@ class Window(Handle):
 
 if __name__ == "__main__":
     w = Window(config='oas1')
+    # w.screenshot_window_background()
     # w.click_window_message(x=350, y=220)
     w.swipe_window_message(startPos=[200, 5], endPos=[300, 300])

+ 11 - 11
module/device/screenshot.py

@@ -50,7 +50,7 @@ class Screenshot(Adb, DroidCast, Scrcpy, Window):
 
         for _ in range(2):
             method = self.screenshot_methods.get(
-                self.config.get_arg('Script', 'Device', 'ScreenshotMethod'),
+                self.config.script.device.screen_method,
                 self.screenshot_adb  # 第二个参数默认的是screenshot_adb
             )
             self.image = method()
@@ -61,7 +61,7 @@ class Screenshot(Adb, DroidCast, Scrcpy, Window):
             # self.image = self._handle_orientated_image(self.image)
 
             # if self.config.Error_SaveError:
-            if self.config.get_arg('Script', 'Error', 'SaveError'):
+            if self.config.script.error.save_error:
                 self.screenshot_deque.append({'time': datetime.now(), 'image': self.image})
 
             if self.check_screen_size() and self.check_screen_black():
@@ -100,7 +100,7 @@ class Screenshot(Adb, DroidCast, Scrcpy, Window):
     @cached_property
     def screenshot_deque(self):
         # return deque(maxlen=int(self.config.Error_ScreenshotLength))
-        return deque(maxlen=int(self.config.get_arg("Script", "Error", "ScreenshotLength")))
+        return deque(maxlen=int(self.config.script.error.screenshot_length))
 
     def save_screenshot(self, genre='items', interval=None, to_base_folder=False):
         """Save a screenshot. Use millisecond timestamp as file name.
@@ -145,17 +145,17 @@ class Screenshot(Adb, DroidCast, Scrcpy, Window):
                 Or None for Optimization_ScreenshotInterval, 'combat' for Optimization_CombatScreenshotInterval
         """
         if interval is None:
-            origin = self.config.get_arg('Script', 'Optimization', 'ScreenshotInterval')
+            origin = self.config.script.optimization.screenshot_interval
             interval = limit_in(origin, 0.1, 0.3)
             if interval != origin:
                 logger.warning(f'Optimization.ScreenshotInterval {origin} is revised to {interval}')
-                self.config.set_arg('Script', 'Optimization', 'ScreenshotInterval', interval)
+                self.config.script.optimization.screenshot_interval = interval
         elif interval == 'combat':
-            origin = self.config.get_arg('Script', 'Optimization', 'CombatScreenshotInterval')
+            origin = self.config.script.optimization.combat_screenshot_interval
             interval = limit_in(origin, 0.3, 1.0)
             if interval != origin:
                 logger.warning(f'Optimization.CombatScreenshotInterval {origin} is revised to {interval}')
-                self.config.set_arg('Script', 'Optimization', 'CombatScreenshotInterval', interval)
+                self.config.script.optimization.combat_screenshot_interval = interval
         elif isinstance(interval, (int, float)):
             # No limitation for manual set in code
             pass
@@ -165,7 +165,7 @@ class Screenshot(Adb, DroidCast, Scrcpy, Window):
         # Screenshot interval in scrcpy is meaningless,
         # video stream is received continuously no matter you use it or not.
         # if self.config.Emulator_ScreenshotMethod == 'scrcpy':
-        if self.config.get_arg('Script', 'Device', 'ScreenshotMethod') == 'scrcpy':
+        if self.config.script.device.screenshot_method == 'scrcpy':
             interval = 0.1
 
         if interval != self._screenshot_interval.limit:
@@ -234,7 +234,7 @@ class Screenshot(Adb, DroidCast, Scrcpy, Window):
             #     logger.warning('Game not running on display 0, will be restarted')
             #     self.app_stop_uiautomator2()
             #     return False
-            if self.config.get_arg('Script', 'Device', 'ScreenshotMethod') == 'uiautomator2':
+            if self.config.script.device.screenshot_method == 'uiautomator2':
                 logger.warning(f'Received pure black screenshots from emulator, color: {color}')
                 logger.warning('Uninstall minicap and retry')
                 self.uninstall_minicap()
@@ -242,10 +242,10 @@ class Screenshot(Adb, DroidCast, Scrcpy, Window):
                 return False
             else:
                 logger.warning(f'Received pure black screenshots from emulator, color: {color}')
-                logger.warning(f'Screenshot method {self.config.get_arg("Script", "Device", "ScreenshotMethod")}'
+                logger.warning(f'Screenshot method {self.config.script.device.screenshot_method}'
                                f'may not work on emulator `{self.serial}`, or the emulator is not fully started')
                 if self.is_mumu_family:
-                    if self.config.get_arg('Script', 'Device', 'ScreenshotMethod') == 'DroidCast':
+                    if self.config.script.device.screenshot_method == 'DroidCast':
                         self.droidcast_stop()
                     else:
                         logger.warning('If you are using MuMu X, please upgrade to version >= 12.1.5.0')

+ 12 - 12
script.py

@@ -29,18 +29,18 @@ class Script:
             logger.exception(e)
             exit(1)
 
-    # @cached_property
-    # def device(self) -> "Device":
-    #     try:
-    #         from module.device.device import Device
-    #         device = Device(config=self.config)
-    #         return device
-    #     except RequestHumanTakeover:
-    #         logger.critical('Request human takeover')
-    #         exit(1)
-    #     except Exception as e:
-    #         logger.exception(e)
-    #         exit(1)
+    @cached_property
+    def device(self) -> "Device":
+        try:
+            from module.device.device import Device
+            device = Device(config=self.config)
+            return device
+        except RequestHumanTakeover:
+            logger.critical('Request human takeover')
+            exit(1)
+        except Exception as e:
+            logger.exception(e)
+            exit(1)
 
     def init_server(self, port: int) -> int:
         """