kotonebot 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. kotonebot/__init__.py +40 -0
  2. kotonebot/backend/__init__.py +0 -0
  3. kotonebot/backend/bot.py +302 -0
  4. kotonebot/backend/color.py +525 -0
  5. kotonebot/backend/context/__init__.py +3 -0
  6. kotonebot/backend/context/context.py +1001 -0
  7. kotonebot/backend/context/task_action.py +176 -0
  8. kotonebot/backend/core.py +126 -0
  9. kotonebot/backend/debug/__init__.py +1 -0
  10. kotonebot/backend/debug/entry.py +89 -0
  11. kotonebot/backend/debug/mock.py +79 -0
  12. kotonebot/backend/debug/server.py +223 -0
  13. kotonebot/backend/debug/vars.py +346 -0
  14. kotonebot/backend/dispatch.py +228 -0
  15. kotonebot/backend/flow_controller.py +197 -0
  16. kotonebot/backend/image.py +748 -0
  17. kotonebot/backend/loop.py +277 -0
  18. kotonebot/backend/ocr.py +511 -0
  19. kotonebot/backend/preprocessor.py +103 -0
  20. kotonebot/client/__init__.py +10 -0
  21. kotonebot/client/device.py +500 -0
  22. kotonebot/client/fast_screenshot.py +378 -0
  23. kotonebot/client/host/__init__.py +12 -0
  24. kotonebot/client/host/adb_common.py +94 -0
  25. kotonebot/client/host/custom.py +114 -0
  26. kotonebot/client/host/leidian_host.py +202 -0
  27. kotonebot/client/host/mumu12_host.py +245 -0
  28. kotonebot/client/host/protocol.py +213 -0
  29. kotonebot/client/host/windows_common.py +55 -0
  30. kotonebot/client/implements/__init__.py +7 -0
  31. kotonebot/client/implements/adb.py +85 -0
  32. kotonebot/client/implements/adb_raw.py +159 -0
  33. kotonebot/client/implements/nemu_ipc/__init__.py +8 -0
  34. kotonebot/client/implements/nemu_ipc/external_renderer_ipc.py +280 -0
  35. kotonebot/client/implements/nemu_ipc/nemu_ipc.py +327 -0
  36. kotonebot/client/implements/remote_windows.py +193 -0
  37. kotonebot/client/implements/uiautomator2.py +82 -0
  38. kotonebot/client/implements/windows.py +168 -0
  39. kotonebot/client/protocol.py +69 -0
  40. kotonebot/client/registration.py +24 -0
  41. kotonebot/config/__init__.py +1 -0
  42. kotonebot/config/base_config.py +96 -0
  43. kotonebot/config/manager.py +36 -0
  44. kotonebot/errors.py +72 -0
  45. kotonebot/interop/win/__init__.py +0 -0
  46. kotonebot/interop/win/message_box.py +314 -0
  47. kotonebot/interop/win/reg.py +37 -0
  48. kotonebot/interop/win/shortcut.py +43 -0
  49. kotonebot/interop/win/task_dialog.py +469 -0
  50. kotonebot/logging/__init__.py +2 -0
  51. kotonebot/logging/log.py +18 -0
  52. kotonebot/primitives/__init__.py +17 -0
  53. kotonebot/primitives/geometry.py +290 -0
  54. kotonebot/primitives/visual.py +63 -0
  55. kotonebot/tools/__init__.py +0 -0
  56. kotonebot/tools/mirror.py +354 -0
  57. kotonebot/ui/__init__.py +0 -0
  58. kotonebot/ui/file_host/sensio.py +36 -0
  59. kotonebot/ui/file_host/tmp_send.py +54 -0
  60. kotonebot/ui/pushkit/__init__.py +3 -0
  61. kotonebot/ui/pushkit/image_host.py +87 -0
  62. kotonebot/ui/pushkit/protocol.py +13 -0
  63. kotonebot/ui/pushkit/wxpusher.py +53 -0
  64. kotonebot/ui/user.py +144 -0
  65. kotonebot/util.py +409 -0
  66. kotonebot-0.1.0.dist-info/METADATA +204 -0
  67. kotonebot-0.1.0.dist-info/RECORD +70 -0
  68. kotonebot-0.1.0.dist-info/WHEEL +5 -0
  69. kotonebot-0.1.0.dist-info/licenses/LICENSE +674 -0
  70. kotonebot-0.1.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,378 @@
1
+ # type: ignore
2
+ # source: https://github.com/hansalemaos/adbnativeblitz
3
+ # license: MIT
4
+ # requires: av
5
+
6
+ import base64
7
+ import ctypes
8
+ import os
9
+ import platform
10
+ import signal
11
+ import subprocess
12
+ import sys
13
+ import threading
14
+ from collections import deque
15
+ from functools import cache
16
+ import av
17
+ from time import sleep as sleep_
18
+ from math import floor
19
+
20
+
21
+ def sleep(secs):
22
+ try:
23
+ if secs == 0:
24
+ return
25
+ maxrange = 50 * secs
26
+ if isinstance(maxrange, float):
27
+ sleeplittle = floor(maxrange)
28
+ sleep_((maxrange - sleeplittle) / 50)
29
+ maxrange = int(sleeplittle)
30
+ if maxrange > 0:
31
+ for _ in range(maxrange):
32
+ sleep_(0.016)
33
+ except KeyboardInterrupt:
34
+ return
35
+
36
+ iswindows = "win" in platform.platform().lower()
37
+ if iswindows:
38
+ startupinfo = subprocess.STARTUPINFO()
39
+ startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
40
+ startupinfo.wShowWindow = subprocess.SW_HIDE
41
+ creationflags = subprocess.CREATE_NO_WINDOW
42
+ invisibledict = {
43
+ "startupinfo": startupinfo,
44
+ "creationflags": creationflags,
45
+ "start_new_session": True,
46
+ }
47
+ from ctypes import wintypes
48
+
49
+ windll = ctypes.LibraryLoader(ctypes.WinDLL)
50
+ kernel32 = windll.kernel32
51
+ _GetShortPathNameW = kernel32.GetShortPathNameW
52
+ _GetShortPathNameW.argtypes = [wintypes.LPCWSTR, wintypes.LPWSTR, wintypes.DWORD]
53
+ _GetShortPathNameW.restype = wintypes.DWORD
54
+ else:
55
+ invisibledict = {}
56
+
57
+
58
+ @cache
59
+ def get_short_path_name(long_name):
60
+ try:
61
+ if not iswindows:
62
+ return long_name
63
+ output_buf_size = 4096
64
+ output_buf = ctypes.create_unicode_buffer(output_buf_size)
65
+ _ = _GetShortPathNameW(long_name, output_buf, output_buf_size)
66
+ return output_buf.value
67
+ except Exception as e:
68
+ sys.stderr.write(f"{e}\n")
69
+ return long_name
70
+
71
+
72
+ def killthread(threadobject):
73
+ # based on https://pypi.org/project/kthread/
74
+ if not threadobject.is_alive():
75
+ return True
76
+ tid = -1
77
+ for tid1, tobj in threading._active.items():
78
+ if tobj is threadobject:
79
+ tid = tid1
80
+ break
81
+ if tid == -1:
82
+ sys.stderr.write(f"{threadobject} not found")
83
+ return False
84
+ res = ctypes.pythonapi.PyThreadState_SetAsyncExc(
85
+ ctypes.c_long(tid), ctypes.py_object(SystemExit)
86
+ )
87
+ if res == 0:
88
+ return False
89
+ elif res != 1:
90
+ ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, 0)
91
+ return False
92
+ return True
93
+
94
+
95
+ def send_ctrl_commands(pid, command=0):
96
+ if iswindows:
97
+ commandstring = r"""import ctypes, sys; CTRL_C_EVENT, CTRL_BREAK_EVENT, CTRL_CLOSE_EVENT, CTRL_LOGOFF_EVENT, CTRL_SHUTDOWN_EVENT = 0, 1, 2, 3, 4; kernel32 = ctypes.WinDLL("kernel32", use_last_error=True); (lambda pid, cmdtosend=CTRL_C_EVENT: [kernel32.FreeConsole(), kernel32.AttachConsole(pid), kernel32.SetConsoleCtrlHandler(None, 1), kernel32.GenerateConsoleCtrlEvent(cmdtosend, 0), sys.exit(0) if isinstance(pid, int) else None])(int(sys.argv[1]), int(sys.argv[2]) if len(sys.argv) > 2 else None) if __name__ == '__main__' else None"""
98
+ subprocess.Popen(
99
+ [sys.executable, "-c", commandstring, str(pid), str(command)],
100
+ **invisibledict,
101
+ )
102
+ else:
103
+ os.kill(pid, signal.SIGINT)
104
+
105
+
106
+ class StopDescriptor:
107
+ def __get__(self, instance, owner):
108
+ return instance.__dict__[self.name]
109
+
110
+ def __set__(self, instance, value):
111
+ if not value:
112
+ instance.__dict__[self.name] = False
113
+ else:
114
+ instance.__dict__[self.name] = True
115
+ instance.stop_capture()
116
+
117
+ def __delete__(self, instance):
118
+ sys.stderr.write("Cannot be deleted!")
119
+
120
+ def __set_name__(self, owner, name):
121
+ self.name = name
122
+
123
+
124
+ class AdbFastScreenshots:
125
+ stop_recording = StopDescriptor()
126
+
127
+ def __init__(
128
+ self,
129
+ adb_path,
130
+ device_serial,
131
+ time_interval=179,
132
+ width=1600,
133
+ height=900,
134
+ bitrate="20M",
135
+ use_busybox=False,
136
+ connect_to_device=True,
137
+ screenshotbuffer=10,
138
+ go_idle=0,
139
+ ):
140
+ r"""Capture Android device screen using ADB's screenrecord with high frame rate.
141
+
142
+ This class allows capturing the screen of an Android device using ADB's screenrecord
143
+ command with an improved frame rate. It continuously captures frames from the device
144
+ and provides them as NumPy arrays to the caller.
145
+
146
+ Args:
147
+ adb_path (str): The path to the ADB executable.
148
+ device_serial (str): The serial number of the target Android device.
149
+ time_interval (int): The maximum duration, in seconds, for each screen recording session (up to a maximum of 180 seconds). After reaching this time limit, a new recording session automatically starts without causing interruptions to the user experience.
150
+ width (int): The width of the captured screen.
151
+ height (int): The height of the captured screen.
152
+ bitrate (str): The bitrate for screen recording (e.g., "20M" for 20Mbps).
153
+ use_busybox (bool): Whether to use BusyBox for base64 encoding.
154
+ connect_to_device (bool): Whether to connect to the device using ADB.
155
+ screenshotbuffer (int): The size of the frame buffer to store the last captured frames.
156
+ go_idle (float): The idle time (in seconds) when no new frames are available. # higher value -> less fps, but also less CPU usage.
157
+
158
+ Attributes:
159
+ stop_recording (bool): Control attribute to stop the screen capture.
160
+
161
+ Methods:
162
+ stop_capture(): Stops the screen capture.
163
+
164
+ Usage:
165
+ import cv2
166
+ from adbnativeblitz import AdbFastScreenshots
167
+
168
+ with AdbFastScreenshots(
169
+ adb_path=r"C:\Android\android-sdk\platform-tools\adb.exe",
170
+ device_serial="127.0.0.1:5555",
171
+ time_interval=179,
172
+ width=1600,
173
+ height=900,
174
+ bitrate="20M",
175
+ use_busybox=False,
176
+ connect_to_device=True,
177
+ screenshotbuffer=10,
178
+ go_idle=0,
179
+ ) as adbscreen:
180
+ for image in adbscreen:
181
+ cv2.imshow("CV2 WINDOW", image)
182
+ if cv2.waitKey(1) & 0xFF == ord("q"):
183
+ break
184
+ cv2.destroyAllWindows()
185
+
186
+
187
+ Note:
188
+ - The `AdbFastScreenshots` class should be used in a context manager (`with` statement).
189
+ - The `stop_capture()` method can be called to stop the screen capture.
190
+ - The frames are continuously captured and provided in the form of NumPy arrays.
191
+ - The class aims to achieve a higher frame rate by avoiding slow subprocess creation
192
+ for each screen capture session.
193
+ """
194
+
195
+ self.stop_recording = False
196
+ self.size = f"{width}x{height}"
197
+ self.width = width
198
+ self.height = height
199
+ self.timelimit = time_interval
200
+ self.bitrate = bitrate
201
+ self.use_busybox = use_busybox
202
+ self.adb_path = get_short_path_name(adb_path)
203
+ self.device_serial = device_serial
204
+ if connect_to_device:
205
+ subprocess.run(
206
+ [self.adb_path, "connect", self.device_serial], **invisibledict
207
+ )
208
+ self.threadlock = threading.Lock()
209
+ self.codec = av.codec.CodecContext.create("h264", "r")
210
+ self.lastframes = deque([], screenshotbuffer)
211
+ self.command_to_execute = (
212
+ f"""#!/bin/bash
213
+ startscreenrecord() {{
214
+
215
+ screenrecord --output-format=h264 --time-limit "$1" --size "$2" --bit-rate "$3" -
216
+ }}
217
+
218
+ time_interval={self.timelimit}
219
+ size="{self.size}"
220
+ bitrate="{self.bitrate}"
221
+ #screenrecord --output-format=h264 --time-limit 1 --size "$size" --bit-rate "$bitrate" -
222
+ while true; do
223
+ startscreenrecord $time_interval "$size" "$bitrate"
224
+ done"""
225
+ + "\n"
226
+ )
227
+ self.base64cmd = self.format_adb_command(
228
+ self.command_to_execute,
229
+ su=False,
230
+ exitcommand="",
231
+ errors="strict",
232
+ )
233
+ self.p = None
234
+ self.threadstdout = None
235
+ self.framecounter = 0
236
+ self.go_idle = go_idle
237
+
238
+ def format_adb_command(
239
+ self,
240
+ cmd,
241
+ su=False,
242
+ exitcommand="DONE",
243
+ errors="strict",
244
+ ):
245
+ if su:
246
+ cmd = f"su -- {cmd}"
247
+ if exitcommand:
248
+ cmd = cmd.rstrip() + f"\necho {exitcommand}\n"
249
+ nolimitcommand = []
250
+ base64_command = base64.standard_b64encode(cmd.encode("utf-8", errors)).decode(
251
+ "utf-8", errors
252
+ )
253
+ nolimitcommand.extend(["echo", base64_command, "|"])
254
+ if self.use_busybox:
255
+ nolimitcommand.extend(["busybox"])
256
+ nolimitcommand.extend(["base64", "-d", "|", "sh"])
257
+
258
+ return " ".join(nolimitcommand) + "\n"
259
+
260
+ def _start_capturing(self):
261
+ def _execute_stdout_read():
262
+ try:
263
+ for q in iter(self.p.stdout.readline, b""):
264
+ if iswindows:
265
+ q = q.replace(b"\r\n", b"\n")
266
+ if q:
267
+ alldata.append(q)
268
+ if alldata:
269
+ joineddata = b"".join(alldata)
270
+ try:
271
+ packets = self.codec.parse(joineddata)
272
+ if packets:
273
+ for pack in packets:
274
+ frames = self.codec.decode(pack)
275
+ for frame in frames:
276
+ nparray = (
277
+ frame.to_rgb()
278
+ .reformat(
279
+ width=self.width,
280
+ height=self.height,
281
+ format="bgr24",
282
+ )
283
+ .to_ndarray()
284
+ )
285
+ try:
286
+ self.threadlock.acquire()
287
+ self.lastframes.append(nparray)
288
+ self.framecounter += 1
289
+
290
+ finally:
291
+ try:
292
+ self.threadlock.release()
293
+ except Exception as e:
294
+ sys.stderr.write(f"{e}\n")
295
+ alldata.clear()
296
+ except Exception as e:
297
+ sys.stderr.write(f"{e}\n")
298
+ except Exception as e:
299
+ sys.stderr.write(f"{e}\n")
300
+
301
+ self.p = subprocess.Popen(
302
+ [self.adb_path, "-s", self.device_serial, "shell", self.base64cmd],
303
+ stderr=subprocess.DEVNULL,
304
+ stdout=subprocess.PIPE,
305
+ stdin=subprocess.DEVNULL,
306
+ bufsize=0,
307
+ **invisibledict,
308
+ )
309
+ alldata = []
310
+ self.threadstdout = threading.Thread(target=_execute_stdout_read)
311
+ self.threadstdout.daemon = True
312
+ self.threadstdout.start()
313
+
314
+ def _stop_capture(self):
315
+ try:
316
+ if iswindows:
317
+ subprocess.Popen(f"taskkill /F /PID {self.p.pid} /T", **invisibledict)
318
+ except:
319
+ pass
320
+ try:
321
+ self.p.stdout.close()
322
+ except:
323
+ pass
324
+ try:
325
+ killthread(self.threadstdout)
326
+ except:
327
+ pass
328
+
329
+ def stop_capture(self):
330
+ send_ctrl_commands(self.p.pid, command=0)
331
+ try:
332
+ sleep(1)
333
+ except KeyboardInterrupt:
334
+ pass
335
+ self._stop_capture()
336
+
337
+ def __iter__(self):
338
+ oldframecounter = 0
339
+
340
+ self._start_capturing()
341
+ sleep(0.05)
342
+ while not self.stop_recording:
343
+ if not self.lastframes:
344
+ sleep(0.005)
345
+ continue
346
+ yield self.lastframes[-1].copy()
347
+ if oldframecounter == self.framecounter:
348
+ if self.go_idle:
349
+ sleep(self.go_idle)
350
+ oldframecounter = self.framecounter
351
+
352
+ def __enter__(self):
353
+ return self
354
+
355
+ def __exit__(self, type, value, traceback):
356
+ self.stop_recording = True
357
+
358
+
359
+ if __name__ == "__main__":
360
+ import cv2
361
+
362
+ with AdbFastScreenshots(
363
+ adb_path=r"D:\SDK\Android\platform-tools\adb.exe",
364
+ device_serial="127.0.0.1:16384",
365
+ time_interval=179,
366
+ width=720,
367
+ height=1280,
368
+ bitrate="20M",
369
+ use_busybox=False,
370
+ connect_to_device=True,
371
+ screenshotbuffer=10,
372
+ go_idle=0,
373
+ ) as adbscreen:
374
+ for image in adbscreen:
375
+ cv2.imshow("CV2 WINDOW", image)
376
+ if cv2.waitKey(1) & 0xFF == ord("q"):
377
+ break
378
+ cv2.destroyAllWindows()
@@ -0,0 +1,12 @@
1
+ from .protocol import HostProtocol, Instance, AdbHostConfig, WindowsHostConfig, RemoteWindowsHostConfig
2
+ from .custom import CustomInstance, create as create_custom
3
+ from .mumu12_host import Mumu12Host, Mumu12Instance
4
+ from .leidian_host import LeidianHost, LeidianInstance
5
+
6
+ __all__ = [
7
+ 'HostProtocol', 'Instance',
8
+ 'AdbHostConfig', 'WindowsHostConfig', 'RemoteWindowsHostConfig',
9
+ 'CustomInstance', 'create_custom',
10
+ 'Mumu12Host', 'Mumu12Instance',
11
+ 'LeidianHost', 'LeidianInstance'
12
+ ]
@@ -0,0 +1,94 @@
1
+ from abc import ABC
2
+ from typing import Any, Literal, TypeGuard, TypeVar, get_args
3
+ from typing_extensions import assert_never
4
+
5
+ from adbutils import adb
6
+ from adbutils._device import AdbDevice
7
+ from kotonebot import logging
8
+ from kotonebot.client.device import AndroidDevice
9
+ from .protocol import Instance, AdbHostConfig, Device
10
+
11
+ logger = logging.getLogger(__name__)
12
+ AdbRecipes = Literal['adb', 'adb_raw', 'uiautomator2']
13
+
14
+ def is_adb_recipe(recipe: Any) -> TypeGuard[AdbRecipes]:
15
+ return recipe in get_args(AdbRecipes)
16
+
17
+ def connect_adb(
18
+ ip: str,
19
+ port: int,
20
+ connect: bool = True,
21
+ disconnect: bool = True,
22
+ timeout: float = 180,
23
+ device_serial: str | None = None
24
+ ) -> AdbDevice:
25
+ """
26
+ 创建 ADB 连接。
27
+ """
28
+ if disconnect:
29
+ logger.debug('adb disconnect %s:%d', ip, port)
30
+ adb.disconnect(f'{ip}:{port}')
31
+ if connect:
32
+ logger.debug('adb connect %s:%d', ip, port)
33
+ result = adb.connect(f'{ip}:{port}')
34
+ if 'cannot connect to' in result:
35
+ raise ValueError(result)
36
+ serial = device_serial or f'{ip}:{port}'
37
+ logger.debug('adb wait for %s', serial)
38
+ adb.wait_for(serial, timeout=timeout)
39
+ devices = adb.device_list()
40
+ logger.debug('adb device_list: %s', devices)
41
+ d = [d for d in devices if d.serial == serial]
42
+ if len(d) == 0:
43
+ raise ValueError(f"Device {serial} not found")
44
+ d = d[0]
45
+ return d
46
+
47
+ class CommonAdbCreateDeviceMixin(ABC):
48
+ """
49
+ 通用 ADB 创建设备的 Mixin。
50
+ 该 Mixin 定义了创建 ADB 设备的通用接口。
51
+ """
52
+ def __init__(self, *args, **kwargs) -> None:
53
+ super().__init__(*args, **kwargs)
54
+ # 下面的属性只是为了让类型检查通过,无实际实现
55
+ self.adb_ip: str
56
+ self.adb_port: int
57
+ self.adb_name: str
58
+
59
+ def create_device(self, recipe: AdbRecipes, config: AdbHostConfig) -> Device:
60
+ """
61
+ 创建 ADB 设备。
62
+ """
63
+ connection = connect_adb(
64
+ self.adb_ip,
65
+ self.adb_port,
66
+ connect=True,
67
+ disconnect=True,
68
+ timeout=config.timeout,
69
+ device_serial=self.adb_name
70
+ )
71
+ d = AndroidDevice(connection)
72
+ match recipe:
73
+ case 'adb':
74
+ from kotonebot.client.implements.adb import AdbImpl
75
+ impl = AdbImpl(connection)
76
+ d._screenshot = impl
77
+ d._touch = impl
78
+ d.commands = impl
79
+ case 'adb_raw':
80
+ from kotonebot.client.implements.adb_raw import AdbRawImpl
81
+ impl = AdbRawImpl(connection)
82
+ d._screenshot = impl
83
+ d._touch = impl
84
+ d.commands = impl
85
+ case 'uiautomator2':
86
+ from kotonebot.client.implements.uiautomator2 import UiAutomator2Impl
87
+ from kotonebot.client.implements.adb import AdbImpl
88
+ impl = UiAutomator2Impl(connection)
89
+ d._screenshot = impl
90
+ d._touch = impl
91
+ d.commands = AdbImpl(connection)
92
+ case _:
93
+ assert_never(f'Unsupported ADB recipe: {recipe}')
94
+ return d
@@ -0,0 +1,114 @@
1
+ import os
2
+ import subprocess
3
+ from psutil import process_iter
4
+ from .protocol import Instance, AdbHostConfig, HostProtocol
5
+ from typing import ParamSpec, TypeVar
6
+ from typing_extensions import override
7
+
8
+ from kotonebot import logging
9
+ from kotonebot.client import Device
10
+ from .adb_common import AdbRecipes, CommonAdbCreateDeviceMixin
11
+
12
+ logger = logging.getLogger(__name__)
13
+ CustomRecipes = AdbRecipes
14
+
15
+ P = ParamSpec('P')
16
+ T = TypeVar('T')
17
+
18
+ class CustomInstance(CommonAdbCreateDeviceMixin, Instance[AdbHostConfig]):
19
+ def __init__(self, exe_path: str | None, emulator_args: str = "", *args, **kwargs):
20
+ super().__init__(*args, **kwargs)
21
+ self.exe_path: str | None = exe_path
22
+ self.exe_args: str = emulator_args
23
+ self.process: subprocess.Popen | None = None
24
+
25
+ @override
26
+ def start(self):
27
+ if self.process:
28
+ logger.warning('Process is already running.')
29
+ return
30
+
31
+ if not self.exe_path:
32
+ raise ValueError('Executable path is not set.')
33
+ if self.exe_args:
34
+ logger.info('Starting process "%s" with args "%s"...', self.exe_path, self.exe_args)
35
+ cmd = f'"{self.exe_path}" {self.exe_args}'
36
+ self.process = subprocess.Popen(cmd, shell=True)
37
+ else:
38
+ logger.info('Starting process "%s"...', self.exe_path)
39
+ self.process = subprocess.Popen(self.exe_path)
40
+
41
+ @override
42
+ def stop(self):
43
+ if not self.process:
44
+ logger.warning('Process is not running.')
45
+ return
46
+ logger.info('Stopping process "%s"...', self.process.pid)
47
+ self.process.terminate()
48
+ self.process.wait()
49
+ self.process = None
50
+
51
+ @override
52
+ def running(self) -> bool:
53
+ if self.process is not None:
54
+ return True
55
+ else:
56
+ if not self.exe_path:
57
+ logger.warning('Executable path is not set, cannot check if process is running.')
58
+ return False
59
+ process_name = os.path.basename(self.exe_path)
60
+ p = next((proc for proc in process_iter() if proc.name() == process_name), None)
61
+ if p:
62
+ return True
63
+ else:
64
+ return False
65
+
66
+ @override
67
+ def refresh(self):
68
+ pass
69
+
70
+ @override
71
+ def create_device(self, impl: CustomRecipes, host_config: AdbHostConfig) -> Device:
72
+ """为自定义实例创建 Device。"""
73
+ if self.adb_port is None:
74
+ raise ValueError("ADB port is not set and is required.")
75
+
76
+ return super().create_device(impl, host_config)
77
+
78
+ def __repr__(self) -> str:
79
+ return f'CustomInstance(#{self.id}# at "{self.exe_path}" with {self.adb_ip}:{self.adb_port})'
80
+
81
+ def _type_check(ins: Instance) -> CustomInstance:
82
+ if not isinstance(ins, CustomInstance):
83
+ raise ValueError(f'Instance {ins} is not a CustomInstance')
84
+ return ins
85
+
86
+ def create(exe_path: str | None, adb_ip: str, adb_port: int, adb_name: str | None, emulator_args: str = "") -> CustomInstance:
87
+ return CustomInstance(exe_path, emulator_args=emulator_args, id='custom', name='Custom', adb_ip=adb_ip, adb_port=adb_port, adb_name=adb_name)
88
+
89
+ class CustomHost(HostProtocol[CustomRecipes]):
90
+ @staticmethod
91
+ def installed() -> bool:
92
+ # Custom instances don't have a specific installation requirement
93
+ return True
94
+
95
+ @staticmethod
96
+ def list() -> list[Instance]:
97
+ # Custom instances are created manually, not discovered
98
+ return []
99
+
100
+ @staticmethod
101
+ def query(*, id: str) -> Instance | None:
102
+ # Custom instances are created manually, not discovered
103
+ return None
104
+
105
+ @staticmethod
106
+ def recipes() -> 'list[CustomRecipes]':
107
+ return ['adb', 'adb_raw', 'uiautomator2']
108
+
109
+ if __name__ == '__main__':
110
+ ins = create(r'C:\Program Files\BlueStacks_nxt\HD-Player.exe', '127.0.0.1', 5555, '**emulator-name**')
111
+ ins.start()
112
+ ins.wait_available()
113
+ input('Press Enter to stop...')
114
+ ins.stop()