kotonebot 0.5.0__py3-none-any.whl → 0.6.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.
- kotonebot/__init__.py +39 -39
- kotonebot/backend/bot.py +312 -312
- kotonebot/backend/color.py +525 -525
- kotonebot/backend/context/__init__.py +3 -3
- kotonebot/backend/context/context.py +1002 -1002
- kotonebot/backend/context/task_action.py +183 -183
- kotonebot/backend/core.py +86 -129
- kotonebot/backend/debug/entry.py +89 -89
- kotonebot/backend/debug/mock.py +78 -78
- kotonebot/backend/debug/server.py +222 -222
- kotonebot/backend/debug/vars.py +351 -351
- kotonebot/backend/dispatch.py +227 -227
- kotonebot/backend/flow_controller.py +196 -196
- kotonebot/backend/image.py +36 -5
- kotonebot/backend/loop.py +222 -208
- kotonebot/backend/ocr.py +535 -535
- kotonebot/backend/preprocessor.py +103 -103
- kotonebot/client/__init__.py +9 -9
- kotonebot/client/device.py +369 -529
- kotonebot/client/fast_screenshot.py +377 -377
- kotonebot/client/host/__init__.py +43 -43
- kotonebot/client/host/adb_common.py +101 -107
- kotonebot/client/host/custom.py +118 -118
- kotonebot/client/host/leidian_host.py +196 -196
- kotonebot/client/host/mumu12_host.py +353 -353
- kotonebot/client/host/protocol.py +214 -214
- kotonebot/client/host/windows_common.py +58 -58
- kotonebot/client/implements/__init__.py +65 -70
- kotonebot/client/implements/adb.py +89 -89
- kotonebot/client/implements/nemu_ipc/__init__.py +11 -11
- kotonebot/client/implements/nemu_ipc/external_renderer_ipc.py +284 -284
- kotonebot/client/implements/nemu_ipc/nemu_ipc.py +327 -327
- kotonebot/client/implements/remote_windows.py +188 -188
- kotonebot/client/implements/uiautomator2.py +85 -85
- kotonebot/client/implements/windows.py +176 -176
- kotonebot/client/protocol.py +69 -69
- kotonebot/client/registration.py +24 -24
- kotonebot/client/scaler.py +467 -0
- kotonebot/config/base_config.py +96 -96
- kotonebot/config/config.py +61 -0
- kotonebot/config/manager.py +36 -36
- kotonebot/core/__init__.py +13 -0
- kotonebot/core/entities/base.py +182 -0
- kotonebot/core/entities/compound.py +75 -0
- kotonebot/core/entities/ocr.py +117 -0
- kotonebot/core/entities/template_match.py +198 -0
- kotonebot/devtools/__init__.py +42 -0
- kotonebot/devtools/cli/__init__.py +6 -0
- kotonebot/devtools/cli/main.py +53 -0
- kotonebot/{tools → devtools}/mirror.py +354 -354
- kotonebot/devtools/project/project.py +41 -0
- kotonebot/devtools/project/scanner.py +202 -0
- kotonebot/devtools/project/schema.py +99 -0
- kotonebot/devtools/resgen/__init__.py +42 -0
- kotonebot/devtools/resgen/codegen.py +331 -0
- kotonebot/devtools/resgen/core.py +94 -0
- kotonebot/devtools/resgen/parsers.py +360 -0
- kotonebot/devtools/resgen/utils.py +158 -0
- kotonebot/devtools/resgen/validation.py +115 -0
- kotonebot/devtools/web/dist/assets/bootstrap-icons-BOrJxbIo.woff +0 -0
- kotonebot/devtools/web/dist/assets/bootstrap-icons-BtvjY1KL.woff2 +0 -0
- kotonebot/devtools/web/dist/assets/ext-language_tools-CD021WJ2.js +2577 -0
- kotonebot/devtools/web/dist/assets/index-B_m5f2LF.js +2836 -0
- kotonebot/devtools/web/dist/assets/index-BlEDyGGa.css +9 -0
- kotonebot/devtools/web/dist/assets/language-client-C9muzqaq.js +128 -0
- kotonebot/devtools/web/dist/assets/mode-python-CtHp76XS.js +476 -0
- kotonebot/devtools/web/dist/icons/symbol-class.svg +3 -0
- kotonebot/devtools/web/dist/icons/symbol-file.svg +3 -0
- kotonebot/devtools/web/dist/icons/symbol-method.svg +3 -0
- kotonebot/devtools/web/dist/index.html +25 -0
- kotonebot/devtools/web/server/__init__.py +0 -0
- kotonebot/devtools/web/server/rest_api.py +217 -0
- kotonebot/devtools/web/server/server.py +85 -0
- kotonebot/errors.py +76 -76
- kotonebot/interop/win/__init__.py +11 -9
- kotonebot/interop/win/_mouse.py +310 -310
- kotonebot/interop/win/message_box.py +313 -313
- kotonebot/interop/win/reg.py +37 -37
- kotonebot/interop/win/shake_mouse.py +224 -0
- kotonebot/interop/win/shortcut.py +43 -43
- kotonebot/interop/win/task_dialog.py +513 -513
- kotonebot/logging/__init__.py +2 -2
- kotonebot/logging/log.py +17 -17
- kotonebot/primitives/__init__.py +19 -17
- kotonebot/primitives/geometry.py +1067 -862
- kotonebot/primitives/visual.py +143 -63
- kotonebot/ui/file_host/sensio.py +36 -36
- kotonebot/ui/file_host/tmp_send.py +54 -54
- kotonebot/ui/pushkit/__init__.py +3 -3
- kotonebot/ui/pushkit/image_host.py +88 -88
- kotonebot/ui/pushkit/protocol.py +13 -13
- kotonebot/ui/pushkit/wxpusher.py +54 -54
- kotonebot/ui/user.py +148 -148
- kotonebot/util.py +436 -436
- {kotonebot-0.5.0.dist-info → kotonebot-0.6.0.dist-info}/METADATA +84 -82
- kotonebot-0.6.0.dist-info/RECORD +105 -0
- kotonebot-0.6.0.dist-info/entry_points.txt +2 -0
- {kotonebot-0.5.0.dist-info → kotonebot-0.6.0.dist-info}/licenses/LICENSE +673 -673
- kotonebot/client/implements/adb_raw.py +0 -163
- kotonebot-0.5.0.dist-info/RECORD +0 -71
- /kotonebot/{tools → devtools/project}/__init__.py +0 -0
- {kotonebot-0.5.0.dist-info → kotonebot-0.6.0.dist-info}/WHEEL +0 -0
- {kotonebot-0.5.0.dist-info → kotonebot-0.6.0.dist-info}/top_level.txt +0 -0
|
@@ -1,327 +1,327 @@
|
|
|
1
|
-
import os
|
|
2
|
-
import ctypes
|
|
3
|
-
import logging
|
|
4
|
-
import time
|
|
5
|
-
from dataclasses import dataclass
|
|
6
|
-
from time import sleep
|
|
7
|
-
from typing import Literal
|
|
8
|
-
from typing_extensions import override
|
|
9
|
-
|
|
10
|
-
import cv2
|
|
11
|
-
import numpy as np
|
|
12
|
-
from cv2.typing import MatLike
|
|
13
|
-
|
|
14
|
-
from ...device import AndroidDevice, Device
|
|
15
|
-
from ...protocol import Touchable, Screenshotable
|
|
16
|
-
from ...registration import ImplConfig
|
|
17
|
-
from .external_renderer_ipc import ExternalRendererIpc
|
|
18
|
-
from kotonebot.errors import KotonebotError
|
|
19
|
-
|
|
20
|
-
logger = logging.getLogger(__name__)
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
class NemuIpcIncompatible(Exception):
|
|
24
|
-
"""MuMu12 版本过低或 dll 不兼容"""
|
|
25
|
-
pass
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
class NemuIpcError(KotonebotError):
|
|
29
|
-
"""调用 IPC 过程中发生错误"""
|
|
30
|
-
pass
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
@dataclass
|
|
34
|
-
class NemuIpcImplConfig(ImplConfig):
|
|
35
|
-
"""nemu_ipc 能力的配置模型。"""
|
|
36
|
-
nemu_folder: str
|
|
37
|
-
r"""MuMu12 根目录(如 F:\Apps\Netease\MuMuPlayer-12.0)。"""
|
|
38
|
-
instance_id: int
|
|
39
|
-
"""模拟器实例 ID。"""
|
|
40
|
-
display_id: int | None = 0
|
|
41
|
-
"""目标显示器 ID,默认为 0(主显示器)。若为 None 且设置了 target_package_name,则自动获取对应的 display_id。"""
|
|
42
|
-
target_package_name: str | None = None
|
|
43
|
-
"""目标应用包名,用于自动获取 display_id。"""
|
|
44
|
-
app_index: int = 0
|
|
45
|
-
"""多开应用索引,传给 get_display_id 方法。"""
|
|
46
|
-
wait_package_timeout: float = 60 # 单位秒,-1 表示永远等待,0 表示不等待,立即抛出异常
|
|
47
|
-
wait_package_interval: float = 0.1 # 单位秒
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
class NemuIpcImpl(Touchable, Screenshotable):
|
|
51
|
-
"""
|
|
52
|
-
利用 MuMu12 提供的 external_renderer_ipc.dll 进行截图与触摸控制。
|
|
53
|
-
"""
|
|
54
|
-
|
|
55
|
-
def __init__(self, config: NemuIpcImplConfig):
|
|
56
|
-
self.config = config
|
|
57
|
-
self.__width: int = 0
|
|
58
|
-
self.__height: int = 0
|
|
59
|
-
self.__connected: bool = False
|
|
60
|
-
self._connect_id: int = 0
|
|
61
|
-
self.nemu_folder = config.nemu_folder
|
|
62
|
-
|
|
63
|
-
# --------------------------- DLL 封装 ---------------------------
|
|
64
|
-
self._ipc = ExternalRendererIpc(config.nemu_folder)
|
|
65
|
-
logger.info("ExternalRendererIpc initialized and DLL loaded")
|
|
66
|
-
|
|
67
|
-
@property
|
|
68
|
-
def width(self) -> int:
|
|
69
|
-
"""
|
|
70
|
-
屏幕宽度。
|
|
71
|
-
|
|
72
|
-
若为 0,表示未连接或未获取到分辨率。
|
|
73
|
-
"""
|
|
74
|
-
return self.__width
|
|
75
|
-
|
|
76
|
-
@property
|
|
77
|
-
def height(self) -> int:
|
|
78
|
-
"""
|
|
79
|
-
屏幕高度。
|
|
80
|
-
|
|
81
|
-
若为 0,表示未连接或未获取到分辨率。
|
|
82
|
-
"""
|
|
83
|
-
return self.__height
|
|
84
|
-
|
|
85
|
-
@property
|
|
86
|
-
def connected(self) -> bool:
|
|
87
|
-
"""是否已连接。"""
|
|
88
|
-
return self.__connected
|
|
89
|
-
|
|
90
|
-
# ------------------------------------------------------------------
|
|
91
|
-
# 基础控制
|
|
92
|
-
# ------------------------------------------------------------------
|
|
93
|
-
|
|
94
|
-
def _ensure_connected(self) -> None:
|
|
95
|
-
if not self.__connected:
|
|
96
|
-
self.connect()
|
|
97
|
-
|
|
98
|
-
def _get_display_id(self) -> int:
|
|
99
|
-
"""获取有效的 display_id。"""
|
|
100
|
-
# 如果配置中直接指定了 display_id,直接返回
|
|
101
|
-
if self.config.display_id is not None:
|
|
102
|
-
return self.config.display_id
|
|
103
|
-
|
|
104
|
-
# 如果设置了 target_package_name,实时获取 display_id
|
|
105
|
-
if self.config.target_package_name:
|
|
106
|
-
self._ensure_connected()
|
|
107
|
-
|
|
108
|
-
timeout = self.config.wait_package_timeout
|
|
109
|
-
interval = self.config.wait_package_interval
|
|
110
|
-
if timeout == -1:
|
|
111
|
-
timeout = float('inf')
|
|
112
|
-
start_time = time.time()
|
|
113
|
-
while True:
|
|
114
|
-
display_id = self._ipc.get_display_id(
|
|
115
|
-
self._connect_id,
|
|
116
|
-
self.config.target_package_name,
|
|
117
|
-
self.config.app_index
|
|
118
|
-
)
|
|
119
|
-
if display_id >= 0:
|
|
120
|
-
return display_id
|
|
121
|
-
elif display_id == -1:
|
|
122
|
-
# 可以继续等
|
|
123
|
-
pass
|
|
124
|
-
else:
|
|
125
|
-
# 未知错误
|
|
126
|
-
raise NemuIpcError(f"Failed to get display_id for package '{self.config.target_package_name}', error code={display_id}")
|
|
127
|
-
if time.time() - start_time > timeout:
|
|
128
|
-
break
|
|
129
|
-
sleep(interval)
|
|
130
|
-
|
|
131
|
-
raise NemuIpcError(f"Failed to get display_id for package '{self.config.target_package_name}' within {timeout}s")
|
|
132
|
-
|
|
133
|
-
# 如果都没有设置,抛出错误
|
|
134
|
-
raise NemuIpcError("display_id is None and target_package_name is not set. Please set display_id or target_package_name in config.")
|
|
135
|
-
|
|
136
|
-
def connect(self) -> None:
|
|
137
|
-
"""连接模拟器。"""
|
|
138
|
-
if self.__connected:
|
|
139
|
-
return
|
|
140
|
-
|
|
141
|
-
connect_id = self._ipc.connect(self.nemu_folder, self.config.instance_id)
|
|
142
|
-
if connect_id == 0:
|
|
143
|
-
raise NemuIpcError("nemu_connect failed, please check if the emulator is running and the instance ID is correct.")
|
|
144
|
-
|
|
145
|
-
self._connect_id = connect_id
|
|
146
|
-
self.__connected = True
|
|
147
|
-
logger.debug("NemuIpc connected, connect_id=%d", connect_id)
|
|
148
|
-
|
|
149
|
-
def disconnect(self) -> None:
|
|
150
|
-
"""断开连接。"""
|
|
151
|
-
if not self.__connected:
|
|
152
|
-
return
|
|
153
|
-
self._ipc.disconnect(self._connect_id)
|
|
154
|
-
self.__connected = False
|
|
155
|
-
self._connect_id = 0
|
|
156
|
-
logger.debug("NemuIpc disconnected.")
|
|
157
|
-
|
|
158
|
-
# ------------------------------------------------------------------
|
|
159
|
-
# Screenshotable 接口实现
|
|
160
|
-
# ------------------------------------------------------------------
|
|
161
|
-
@property
|
|
162
|
-
def screen_size(self) -> tuple[int, int]:
|
|
163
|
-
"""获取屏幕分辨率。"""
|
|
164
|
-
if self.__width == 0 or self.__height == 0:
|
|
165
|
-
self._refresh_resolution()
|
|
166
|
-
if self.__width == 0 or self.__height == 0:
|
|
167
|
-
raise NemuIpcError("Screen resolution not obtained, please connect to the emulator first.")
|
|
168
|
-
return self.__width, self.__height
|
|
169
|
-
|
|
170
|
-
@override
|
|
171
|
-
def detect_orientation(self):
|
|
172
|
-
return self.get_display_orientation(self._get_display_id())
|
|
173
|
-
|
|
174
|
-
def get_display_orientation(self, display_id: int = 0) -> Literal['portrait', 'landscape'] | None:
|
|
175
|
-
"""获取指定显示屏的方向。"""
|
|
176
|
-
width, height = self.query_resolution(display_id)
|
|
177
|
-
if width > height:
|
|
178
|
-
return "landscape"
|
|
179
|
-
if height > width:
|
|
180
|
-
return "portrait"
|
|
181
|
-
return None
|
|
182
|
-
|
|
183
|
-
@override
|
|
184
|
-
def screenshot(self) -> MatLike:
|
|
185
|
-
self._ensure_connected()
|
|
186
|
-
|
|
187
|
-
# 必须每次都更新分辨率,因为屏幕可能会旋转
|
|
188
|
-
self._refresh_resolution()
|
|
189
|
-
|
|
190
|
-
length = self.__width * self.__height * 4 # RGBA
|
|
191
|
-
buf_type = ctypes.c_ubyte * length
|
|
192
|
-
buffer = buf_type()
|
|
193
|
-
|
|
194
|
-
w_ptr = ctypes.pointer(ctypes.c_int(self.__width))
|
|
195
|
-
h_ptr = ctypes.pointer(ctypes.c_int(self.__height))
|
|
196
|
-
|
|
197
|
-
ret = self._ipc.capture_display(
|
|
198
|
-
self._connect_id,
|
|
199
|
-
self._get_display_id(),
|
|
200
|
-
length,
|
|
201
|
-
ctypes.cast(w_ptr, ctypes.c_void_p),
|
|
202
|
-
ctypes.cast(h_ptr, ctypes.c_void_p),
|
|
203
|
-
ctypes.cast(buffer, ctypes.c_void_p),
|
|
204
|
-
)
|
|
205
|
-
if ret != 0:
|
|
206
|
-
raise NemuIpcError(f"nemu_capture_display screenshot failed, error code={ret}")
|
|
207
|
-
|
|
208
|
-
# 读入并转换数据
|
|
209
|
-
img = np.ctypeslib.as_array(buffer).reshape((self.__height, self.__width, 4))
|
|
210
|
-
# RGBA -> BGR
|
|
211
|
-
img = cv2.cvtColor(img, cv2.COLOR_RGBA2BGR)
|
|
212
|
-
cv2.flip(img, 0, dst=img)
|
|
213
|
-
return img
|
|
214
|
-
|
|
215
|
-
# --------------------------- 内部工具 -----------------------------
|
|
216
|
-
|
|
217
|
-
def _refresh_resolution(self) -> None:
|
|
218
|
-
"""刷新分辨率信息。"""
|
|
219
|
-
display_id = self._get_display_id()
|
|
220
|
-
self.__width, self.__height = self.query_resolution(display_id)
|
|
221
|
-
|
|
222
|
-
def query_resolution(self, display_id: int = 0) -> tuple[int, int]:
|
|
223
|
-
"""
|
|
224
|
-
查询指定显示屏的分辨率。
|
|
225
|
-
|
|
226
|
-
:param display_id: 显示屏 ID。
|
|
227
|
-
:return: 分辨率 (width, height)。
|
|
228
|
-
:raise NemuIpcError: 查询失败。
|
|
229
|
-
"""
|
|
230
|
-
self._ensure_connected()
|
|
231
|
-
|
|
232
|
-
w_ptr = ctypes.pointer(ctypes.c_int(0))
|
|
233
|
-
h_ptr = ctypes.pointer(ctypes.c_int(0))
|
|
234
|
-
ret = self._ipc.capture_display(
|
|
235
|
-
self._connect_id,
|
|
236
|
-
display_id,
|
|
237
|
-
0,
|
|
238
|
-
ctypes.cast(w_ptr, ctypes.c_void_p),
|
|
239
|
-
ctypes.cast(h_ptr, ctypes.c_void_p),
|
|
240
|
-
ctypes.c_void_p(),
|
|
241
|
-
)
|
|
242
|
-
if ret != 0:
|
|
243
|
-
raise NemuIpcError(f"Call nemu_capture_display failed. Return value={ret}")
|
|
244
|
-
|
|
245
|
-
return w_ptr.contents.value, h_ptr.contents.value
|
|
246
|
-
|
|
247
|
-
# ------------------------------------------------------------------
|
|
248
|
-
# Touchable 接口实现
|
|
249
|
-
# ------------------------------------------------------------------
|
|
250
|
-
def __convert_pos(self, x: int, y: int) -> tuple[int, int]:
|
|
251
|
-
# Android 显示屏有两套坐标:逻辑坐标与物理坐标。
|
|
252
|
-
# 逻辑坐标原点始终是画面左上角,而物理坐标原点则始终是显示屏的左上角。
|
|
253
|
-
# 如果屏幕画面旋转,会导致两个坐标的原点不同,坐标也不同。
|
|
254
|
-
# ========
|
|
255
|
-
# 这里传给 MuMu 的是逻辑坐标,ExternalRendererIpc DLL 内部会
|
|
256
|
-
# 自动判断旋转,并转换为物理坐标。但是这部分有个 bug:
|
|
257
|
-
# 旋转没有考虑到多显示器,只是以主显示器为准,若两个显示器旋转不一致,
|
|
258
|
-
# 会导致错误地转换坐标。因此需要在 Python 层面 workaround 这个问题。
|
|
259
|
-
# 通过判断主显示器与当前显示器的旋转,将坐标进行预转换,抵消 DLL 层的错误转换。
|
|
260
|
-
display_id = self._get_display_id()
|
|
261
|
-
if display_id == 0:
|
|
262
|
-
return x, y
|
|
263
|
-
else:
|
|
264
|
-
primary = self.get_display_orientation(0)
|
|
265
|
-
primary_size = self.query_resolution(0)
|
|
266
|
-
current = self.get_display_orientation(display_id)
|
|
267
|
-
if primary == current:
|
|
268
|
-
return x, y
|
|
269
|
-
else:
|
|
270
|
-
# 如果旋转不一致,视为顺时针旋转了 90°
|
|
271
|
-
# 因此我们要提前逆时针旋转 90°
|
|
272
|
-
self._refresh_resolution()
|
|
273
|
-
x, y = y, primary_size[1] - x
|
|
274
|
-
return x, y
|
|
275
|
-
|
|
276
|
-
@override
|
|
277
|
-
def click(self, x: int, y: int) -> None:
|
|
278
|
-
self._ensure_connected()
|
|
279
|
-
display_id = self._get_display_id()
|
|
280
|
-
x, y = self.__convert_pos(x, y)
|
|
281
|
-
self._ipc.input_touch_down(self._connect_id, display_id, x, y)
|
|
282
|
-
sleep(0.01)
|
|
283
|
-
self._ipc.input_touch_up(self._connect_id, display_id)
|
|
284
|
-
|
|
285
|
-
@override
|
|
286
|
-
def swipe(
|
|
287
|
-
self,
|
|
288
|
-
x1: int,
|
|
289
|
-
y1: int,
|
|
290
|
-
x2: int,
|
|
291
|
-
y2: int,
|
|
292
|
-
duration: float | None = None,
|
|
293
|
-
) -> None:
|
|
294
|
-
self._ensure_connected()
|
|
295
|
-
|
|
296
|
-
duration = duration or 0.3
|
|
297
|
-
steps = max(int(duration / 0.01), 2)
|
|
298
|
-
display_id = self._get_display_id()
|
|
299
|
-
x1, y1 = self.__convert_pos(x1, y1)
|
|
300
|
-
x2, y2 = self.__convert_pos(x2, y2)
|
|
301
|
-
|
|
302
|
-
xs = np.linspace(x1, x2, steps, dtype=int)
|
|
303
|
-
ys = np.linspace(y1, y2, steps, dtype=int)
|
|
304
|
-
|
|
305
|
-
# 按下第一点
|
|
306
|
-
self._ipc.input_touch_down(self._connect_id, display_id, xs[0], ys[0])
|
|
307
|
-
sleep(0.01)
|
|
308
|
-
# 中间移动
|
|
309
|
-
for px, py in zip(xs[1:-1], ys[1:-1]):
|
|
310
|
-
self._ipc.input_touch_down(self._connect_id, display_id, px, py)
|
|
311
|
-
sleep(0.01)
|
|
312
|
-
|
|
313
|
-
# 最终抬起
|
|
314
|
-
self._ipc.input_touch_up(self._connect_id, display_id)
|
|
315
|
-
sleep(0.01)
|
|
316
|
-
|
|
317
|
-
if __name__ == '__main__':
|
|
318
|
-
nemu = NemuIpcImpl(NemuIpcImplConfig(
|
|
319
|
-
r'F:\Apps\Netease\MuMuPlayer-12.0', 0, None,
|
|
320
|
-
target_package_name='com.android.chrome',
|
|
321
|
-
))
|
|
322
|
-
nemu.connect()
|
|
323
|
-
# while True:
|
|
324
|
-
# nemu.click(0, 0)
|
|
325
|
-
nemu.click(100, 100)
|
|
326
|
-
nemu.click(100*3, 100)
|
|
327
|
-
nemu.click(100*3, 100*3)
|
|
1
|
+
import os
|
|
2
|
+
import ctypes
|
|
3
|
+
import logging
|
|
4
|
+
import time
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from time import sleep
|
|
7
|
+
from typing import Literal
|
|
8
|
+
from typing_extensions import override
|
|
9
|
+
|
|
10
|
+
import cv2
|
|
11
|
+
import numpy as np
|
|
12
|
+
from cv2.typing import MatLike
|
|
13
|
+
|
|
14
|
+
from ...device import AndroidDevice, Device
|
|
15
|
+
from ...protocol import Touchable, Screenshotable
|
|
16
|
+
from ...registration import ImplConfig
|
|
17
|
+
from .external_renderer_ipc import ExternalRendererIpc
|
|
18
|
+
from kotonebot.errors import KotonebotError
|
|
19
|
+
|
|
20
|
+
logger = logging.getLogger(__name__)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class NemuIpcIncompatible(Exception):
|
|
24
|
+
"""MuMu12 版本过低或 dll 不兼容"""
|
|
25
|
+
pass
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class NemuIpcError(KotonebotError):
|
|
29
|
+
"""调用 IPC 过程中发生错误"""
|
|
30
|
+
pass
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@dataclass
|
|
34
|
+
class NemuIpcImplConfig(ImplConfig):
|
|
35
|
+
"""nemu_ipc 能力的配置模型。"""
|
|
36
|
+
nemu_folder: str
|
|
37
|
+
r"""MuMu12 根目录(如 F:\Apps\Netease\MuMuPlayer-12.0)。"""
|
|
38
|
+
instance_id: int
|
|
39
|
+
"""模拟器实例 ID。"""
|
|
40
|
+
display_id: int | None = 0
|
|
41
|
+
"""目标显示器 ID,默认为 0(主显示器)。若为 None 且设置了 target_package_name,则自动获取对应的 display_id。"""
|
|
42
|
+
target_package_name: str | None = None
|
|
43
|
+
"""目标应用包名,用于自动获取 display_id。"""
|
|
44
|
+
app_index: int = 0
|
|
45
|
+
"""多开应用索引,传给 get_display_id 方法。"""
|
|
46
|
+
wait_package_timeout: float = 60 # 单位秒,-1 表示永远等待,0 表示不等待,立即抛出异常
|
|
47
|
+
wait_package_interval: float = 0.1 # 单位秒
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class NemuIpcImpl(Touchable, Screenshotable):
|
|
51
|
+
"""
|
|
52
|
+
利用 MuMu12 提供的 external_renderer_ipc.dll 进行截图与触摸控制。
|
|
53
|
+
"""
|
|
54
|
+
|
|
55
|
+
def __init__(self, config: NemuIpcImplConfig):
|
|
56
|
+
self.config = config
|
|
57
|
+
self.__width: int = 0
|
|
58
|
+
self.__height: int = 0
|
|
59
|
+
self.__connected: bool = False
|
|
60
|
+
self._connect_id: int = 0
|
|
61
|
+
self.nemu_folder = config.nemu_folder
|
|
62
|
+
|
|
63
|
+
# --------------------------- DLL 封装 ---------------------------
|
|
64
|
+
self._ipc = ExternalRendererIpc(config.nemu_folder)
|
|
65
|
+
logger.info("ExternalRendererIpc initialized and DLL loaded")
|
|
66
|
+
|
|
67
|
+
@property
|
|
68
|
+
def width(self) -> int:
|
|
69
|
+
"""
|
|
70
|
+
屏幕宽度。
|
|
71
|
+
|
|
72
|
+
若为 0,表示未连接或未获取到分辨率。
|
|
73
|
+
"""
|
|
74
|
+
return self.__width
|
|
75
|
+
|
|
76
|
+
@property
|
|
77
|
+
def height(self) -> int:
|
|
78
|
+
"""
|
|
79
|
+
屏幕高度。
|
|
80
|
+
|
|
81
|
+
若为 0,表示未连接或未获取到分辨率。
|
|
82
|
+
"""
|
|
83
|
+
return self.__height
|
|
84
|
+
|
|
85
|
+
@property
|
|
86
|
+
def connected(self) -> bool:
|
|
87
|
+
"""是否已连接。"""
|
|
88
|
+
return self.__connected
|
|
89
|
+
|
|
90
|
+
# ------------------------------------------------------------------
|
|
91
|
+
# 基础控制
|
|
92
|
+
# ------------------------------------------------------------------
|
|
93
|
+
|
|
94
|
+
def _ensure_connected(self) -> None:
|
|
95
|
+
if not self.__connected:
|
|
96
|
+
self.connect()
|
|
97
|
+
|
|
98
|
+
def _get_display_id(self) -> int:
|
|
99
|
+
"""获取有效的 display_id。"""
|
|
100
|
+
# 如果配置中直接指定了 display_id,直接返回
|
|
101
|
+
if self.config.display_id is not None:
|
|
102
|
+
return self.config.display_id
|
|
103
|
+
|
|
104
|
+
# 如果设置了 target_package_name,实时获取 display_id
|
|
105
|
+
if self.config.target_package_name:
|
|
106
|
+
self._ensure_connected()
|
|
107
|
+
|
|
108
|
+
timeout = self.config.wait_package_timeout
|
|
109
|
+
interval = self.config.wait_package_interval
|
|
110
|
+
if timeout == -1:
|
|
111
|
+
timeout = float('inf')
|
|
112
|
+
start_time = time.time()
|
|
113
|
+
while True:
|
|
114
|
+
display_id = self._ipc.get_display_id(
|
|
115
|
+
self._connect_id,
|
|
116
|
+
self.config.target_package_name,
|
|
117
|
+
self.config.app_index
|
|
118
|
+
)
|
|
119
|
+
if display_id >= 0:
|
|
120
|
+
return display_id
|
|
121
|
+
elif display_id == -1:
|
|
122
|
+
# 可以继续等
|
|
123
|
+
pass
|
|
124
|
+
else:
|
|
125
|
+
# 未知错误
|
|
126
|
+
raise NemuIpcError(f"Failed to get display_id for package '{self.config.target_package_name}', error code={display_id}")
|
|
127
|
+
if time.time() - start_time > timeout:
|
|
128
|
+
break
|
|
129
|
+
sleep(interval)
|
|
130
|
+
|
|
131
|
+
raise NemuIpcError(f"Failed to get display_id for package '{self.config.target_package_name}' within {timeout}s")
|
|
132
|
+
|
|
133
|
+
# 如果都没有设置,抛出错误
|
|
134
|
+
raise NemuIpcError("display_id is None and target_package_name is not set. Please set display_id or target_package_name in config.")
|
|
135
|
+
|
|
136
|
+
def connect(self) -> None:
|
|
137
|
+
"""连接模拟器。"""
|
|
138
|
+
if self.__connected:
|
|
139
|
+
return
|
|
140
|
+
|
|
141
|
+
connect_id = self._ipc.connect(self.nemu_folder, self.config.instance_id)
|
|
142
|
+
if connect_id == 0:
|
|
143
|
+
raise NemuIpcError("nemu_connect failed, please check if the emulator is running and the instance ID is correct.")
|
|
144
|
+
|
|
145
|
+
self._connect_id = connect_id
|
|
146
|
+
self.__connected = True
|
|
147
|
+
logger.debug("NemuIpc connected, connect_id=%d", connect_id)
|
|
148
|
+
|
|
149
|
+
def disconnect(self) -> None:
|
|
150
|
+
"""断开连接。"""
|
|
151
|
+
if not self.__connected:
|
|
152
|
+
return
|
|
153
|
+
self._ipc.disconnect(self._connect_id)
|
|
154
|
+
self.__connected = False
|
|
155
|
+
self._connect_id = 0
|
|
156
|
+
logger.debug("NemuIpc disconnected.")
|
|
157
|
+
|
|
158
|
+
# ------------------------------------------------------------------
|
|
159
|
+
# Screenshotable 接口实现
|
|
160
|
+
# ------------------------------------------------------------------
|
|
161
|
+
@property
|
|
162
|
+
def screen_size(self) -> tuple[int, int]:
|
|
163
|
+
"""获取屏幕分辨率。"""
|
|
164
|
+
if self.__width == 0 or self.__height == 0:
|
|
165
|
+
self._refresh_resolution()
|
|
166
|
+
if self.__width == 0 or self.__height == 0:
|
|
167
|
+
raise NemuIpcError("Screen resolution not obtained, please connect to the emulator first.")
|
|
168
|
+
return self.__width, self.__height
|
|
169
|
+
|
|
170
|
+
@override
|
|
171
|
+
def detect_orientation(self):
|
|
172
|
+
return self.get_display_orientation(self._get_display_id())
|
|
173
|
+
|
|
174
|
+
def get_display_orientation(self, display_id: int = 0) -> Literal['portrait', 'landscape'] | None:
|
|
175
|
+
"""获取指定显示屏的方向。"""
|
|
176
|
+
width, height = self.query_resolution(display_id)
|
|
177
|
+
if width > height:
|
|
178
|
+
return "landscape"
|
|
179
|
+
if height > width:
|
|
180
|
+
return "portrait"
|
|
181
|
+
return None
|
|
182
|
+
|
|
183
|
+
@override
|
|
184
|
+
def screenshot(self) -> MatLike:
|
|
185
|
+
self._ensure_connected()
|
|
186
|
+
|
|
187
|
+
# 必须每次都更新分辨率,因为屏幕可能会旋转
|
|
188
|
+
self._refresh_resolution()
|
|
189
|
+
|
|
190
|
+
length = self.__width * self.__height * 4 # RGBA
|
|
191
|
+
buf_type = ctypes.c_ubyte * length
|
|
192
|
+
buffer = buf_type()
|
|
193
|
+
|
|
194
|
+
w_ptr = ctypes.pointer(ctypes.c_int(self.__width))
|
|
195
|
+
h_ptr = ctypes.pointer(ctypes.c_int(self.__height))
|
|
196
|
+
|
|
197
|
+
ret = self._ipc.capture_display(
|
|
198
|
+
self._connect_id,
|
|
199
|
+
self._get_display_id(),
|
|
200
|
+
length,
|
|
201
|
+
ctypes.cast(w_ptr, ctypes.c_void_p),
|
|
202
|
+
ctypes.cast(h_ptr, ctypes.c_void_p),
|
|
203
|
+
ctypes.cast(buffer, ctypes.c_void_p),
|
|
204
|
+
)
|
|
205
|
+
if ret != 0:
|
|
206
|
+
raise NemuIpcError(f"nemu_capture_display screenshot failed, error code={ret}")
|
|
207
|
+
|
|
208
|
+
# 读入并转换数据
|
|
209
|
+
img = np.ctypeslib.as_array(buffer).reshape((self.__height, self.__width, 4))
|
|
210
|
+
# RGBA -> BGR
|
|
211
|
+
img = cv2.cvtColor(img, cv2.COLOR_RGBA2BGR)
|
|
212
|
+
cv2.flip(img, 0, dst=img)
|
|
213
|
+
return img
|
|
214
|
+
|
|
215
|
+
# --------------------------- 内部工具 -----------------------------
|
|
216
|
+
|
|
217
|
+
def _refresh_resolution(self) -> None:
|
|
218
|
+
"""刷新分辨率信息。"""
|
|
219
|
+
display_id = self._get_display_id()
|
|
220
|
+
self.__width, self.__height = self.query_resolution(display_id)
|
|
221
|
+
|
|
222
|
+
def query_resolution(self, display_id: int = 0) -> tuple[int, int]:
|
|
223
|
+
"""
|
|
224
|
+
查询指定显示屏的分辨率。
|
|
225
|
+
|
|
226
|
+
:param display_id: 显示屏 ID。
|
|
227
|
+
:return: 分辨率 (width, height)。
|
|
228
|
+
:raise NemuIpcError: 查询失败。
|
|
229
|
+
"""
|
|
230
|
+
self._ensure_connected()
|
|
231
|
+
|
|
232
|
+
w_ptr = ctypes.pointer(ctypes.c_int(0))
|
|
233
|
+
h_ptr = ctypes.pointer(ctypes.c_int(0))
|
|
234
|
+
ret = self._ipc.capture_display(
|
|
235
|
+
self._connect_id,
|
|
236
|
+
display_id,
|
|
237
|
+
0,
|
|
238
|
+
ctypes.cast(w_ptr, ctypes.c_void_p),
|
|
239
|
+
ctypes.cast(h_ptr, ctypes.c_void_p),
|
|
240
|
+
ctypes.c_void_p(),
|
|
241
|
+
)
|
|
242
|
+
if ret != 0:
|
|
243
|
+
raise NemuIpcError(f"Call nemu_capture_display failed. Return value={ret}")
|
|
244
|
+
|
|
245
|
+
return w_ptr.contents.value, h_ptr.contents.value
|
|
246
|
+
|
|
247
|
+
# ------------------------------------------------------------------
|
|
248
|
+
# Touchable 接口实现
|
|
249
|
+
# ------------------------------------------------------------------
|
|
250
|
+
def __convert_pos(self, x: int, y: int) -> tuple[int, int]:
|
|
251
|
+
# Android 显示屏有两套坐标:逻辑坐标与物理坐标。
|
|
252
|
+
# 逻辑坐标原点始终是画面左上角,而物理坐标原点则始终是显示屏的左上角。
|
|
253
|
+
# 如果屏幕画面旋转,会导致两个坐标的原点不同,坐标也不同。
|
|
254
|
+
# ========
|
|
255
|
+
# 这里传给 MuMu 的是逻辑坐标,ExternalRendererIpc DLL 内部会
|
|
256
|
+
# 自动判断旋转,并转换为物理坐标。但是这部分有个 bug:
|
|
257
|
+
# 旋转没有考虑到多显示器,只是以主显示器为准,若两个显示器旋转不一致,
|
|
258
|
+
# 会导致错误地转换坐标。因此需要在 Python 层面 workaround 这个问题。
|
|
259
|
+
# 通过判断主显示器与当前显示器的旋转,将坐标进行预转换,抵消 DLL 层的错误转换。
|
|
260
|
+
display_id = self._get_display_id()
|
|
261
|
+
if display_id == 0:
|
|
262
|
+
return x, y
|
|
263
|
+
else:
|
|
264
|
+
primary = self.get_display_orientation(0)
|
|
265
|
+
primary_size = self.query_resolution(0)
|
|
266
|
+
current = self.get_display_orientation(display_id)
|
|
267
|
+
if primary == current:
|
|
268
|
+
return x, y
|
|
269
|
+
else:
|
|
270
|
+
# 如果旋转不一致,视为顺时针旋转了 90°
|
|
271
|
+
# 因此我们要提前逆时针旋转 90°
|
|
272
|
+
self._refresh_resolution()
|
|
273
|
+
x, y = y, primary_size[1] - x
|
|
274
|
+
return x, y
|
|
275
|
+
|
|
276
|
+
@override
|
|
277
|
+
def click(self, x: int, y: int) -> None:
|
|
278
|
+
self._ensure_connected()
|
|
279
|
+
display_id = self._get_display_id()
|
|
280
|
+
x, y = self.__convert_pos(x, y)
|
|
281
|
+
self._ipc.input_touch_down(self._connect_id, display_id, x, y)
|
|
282
|
+
sleep(0.01)
|
|
283
|
+
self._ipc.input_touch_up(self._connect_id, display_id)
|
|
284
|
+
|
|
285
|
+
@override
|
|
286
|
+
def swipe(
|
|
287
|
+
self,
|
|
288
|
+
x1: int,
|
|
289
|
+
y1: int,
|
|
290
|
+
x2: int,
|
|
291
|
+
y2: int,
|
|
292
|
+
duration: float | None = None,
|
|
293
|
+
) -> None:
|
|
294
|
+
self._ensure_connected()
|
|
295
|
+
|
|
296
|
+
duration = duration or 0.3
|
|
297
|
+
steps = max(int(duration / 0.01), 2)
|
|
298
|
+
display_id = self._get_display_id()
|
|
299
|
+
x1, y1 = self.__convert_pos(x1, y1)
|
|
300
|
+
x2, y2 = self.__convert_pos(x2, y2)
|
|
301
|
+
|
|
302
|
+
xs = np.linspace(x1, x2, steps, dtype=int)
|
|
303
|
+
ys = np.linspace(y1, y2, steps, dtype=int)
|
|
304
|
+
|
|
305
|
+
# 按下第一点
|
|
306
|
+
self._ipc.input_touch_down(self._connect_id, display_id, xs[0], ys[0])
|
|
307
|
+
sleep(0.01)
|
|
308
|
+
# 中间移动
|
|
309
|
+
for px, py in zip(xs[1:-1], ys[1:-1]):
|
|
310
|
+
self._ipc.input_touch_down(self._connect_id, display_id, px, py)
|
|
311
|
+
sleep(0.01)
|
|
312
|
+
|
|
313
|
+
# 最终抬起
|
|
314
|
+
self._ipc.input_touch_up(self._connect_id, display_id)
|
|
315
|
+
sleep(0.01)
|
|
316
|
+
|
|
317
|
+
if __name__ == '__main__':
|
|
318
|
+
nemu = NemuIpcImpl(NemuIpcImplConfig(
|
|
319
|
+
r'F:\Apps\Netease\MuMuPlayer-12.0', 0, None,
|
|
320
|
+
target_package_name='com.android.chrome',
|
|
321
|
+
))
|
|
322
|
+
nemu.connect()
|
|
323
|
+
# while True:
|
|
324
|
+
# nemu.click(0, 0)
|
|
325
|
+
nemu.click(100, 100)
|
|
326
|
+
nemu.click(100*3, 100)
|
|
327
|
+
nemu.click(100*3, 100*3)
|