10 Commits
Author SHA1 Message Date
Your Name 8368f1f3b7 Fix issues from code review
- Fix project root path in test_webgui.py
- Remove debug console.log from loadConfig in app.js
- Remove duplicate screenshot button event listener in app.js
- Fix redundant directory changes in startup batch script
- Add trailing newlines to files
2026-05-20 09:00:54 +08:00
Your Name 7eb72bd00e Update config, web GUI, and add debug features 2026-05-20 08:12:06 +08:00
Your Name 4492b77d67 优化:统一代码风格,调整字典定义和字符串格式,增强可读性 2026-02-01 12:15:06 +08:00
Your Name 3b2aab67bd 优化:启用杨号功能并更新PaddleOCR和PaddlePaddle版本要求;新增OCR引擎性能对比测试脚本 2026-02-01 12:14:20 +08:00
Your Name 6933c0b4fe 优化:调整参与按钮区域坐标,修正按钮覆盖范围 2026-01-25 20:50:16 +08:00
Your Name 272dcab91d 优化:调整参与按钮区域坐标,增强对部分机型底部按钮的覆盖;更新调试截图逻辑以使用新坐标 2026-01-25 16:58:15 +08:00
Your Name f97c83f6f0 Merge branch 'main' of https://github.com/Zzzil/douyin_guaji-main 2026-01-25 15:35:19 +08:00
Your Name d057c1d84e 优化:调整WiFi ADB连接逻辑,支持ip:port格式;改进USB设备选择逻辑,增强连接稳定性 2026-01-25 15:33:32 +08:00
Your Name 4903e50ff2 优化:调整代码格式,增强可读性 2026-01-23 15:29:09 +08:00
Your Name 68e3f2ff34 优化:调整配置文件中的重置动作和点击等待时间,提升代码逻辑清晰度;更新福袋分析逻辑以改善预约处理流程 2026-01-22 13:40:34 +08:00
18 changed files with 1343 additions and 91 deletions

No files matched your search

+10 -3
View File
@@ -1531,15 +1531,19 @@ class underlying_operations:
# 否则继续重试
continue
def analyse_pic_word(self, picname, change_color=0, pic_path=None):
def analyse_pic_word(
self, picname, change_color=0, pic_path=None, return_confidence=False
):
"""对指定图片运行 OCR 并返回拼接后的文本结果。
参数:
picname: 用于分类和调试的图片名(如"福袋内容")
change_color: 颜色处理模式,0=保留彩色,1/2=二值化等
pic_path: 可选的图片路径,未提供时通过 `_find_pic_path` 查找
return_confidence: 是否返回置信度信息(默认False,保持向后兼容)
返回:
识别到的文本(字符串),识别失败返回空字符串
如果return_confidence=False: 识别到的文本(字符串),识别失败返回空字符串
如果return_confidence=True: (text, confidence_info) 元组,其中confidence_info是置信度信息字典
"""
if not pic_path:
try:
@@ -1905,7 +1909,10 @@ class underlying_operations:
except Exception:
pass
return text
if return_confidence:
return text, ocr_confidence_info
else:
return text
def analyse_pic_digits(self, picname, change_color=1, pic_path=None):
"""轻量数字OCR识别函数,专门用于识别数字(0-9)。
+7 -6
View File
@@ -7,8 +7,8 @@
"max_participants": 0,
"skip_if_countdown_gt_seconds": 118,
"reset_after_swipes_enabled": true,
"reset_after_swipes": 25,
"reset_after_swipes_action": "back",
"reset_after_swipes": 20,
"reset_after_swipes_action": "swipe",
"auto_join_fansclub": true,
"fansclub_fail_action": "switch",
"high_value_fudai_enabled": true,
@@ -29,11 +29,11 @@
"yanghao_fallback_enter_live_x": 540,
"yanghao_fallback_enter_live_y": 1200,
"fudai_find_max_attempts": 99999,
"fudai_icon_max_wait_seconds": 6.0,
"fudai_icon_max_wait_seconds": 6.5,
"fudai_icon_retry_delay_seconds": 0.1,
"fudai_exit_after_misses": 10,
"fudai_exit_after_misses": 7,
"enable_back_on_misses": false,
"fudai_click_wait_seconds": 2.0,
"fudai_click_wait_seconds": 1.5,
"fudai_detail_initial_wait_seconds": 0.8,
"fudai_detail_verified_wait_seconds": 0.2,
"fudai_detail_retry_delay_seconds": 0.5,
@@ -139,7 +139,7 @@
"fudai_template_match_enabled": false,
"fudai_template_match_threshold": 0.7,
"lucky_draw_red_ratio_threshold": 0.8,
"shopping_redpacket_red_ratio_threshold": 0.5,
"shopping_redpacket_red_ratio_threshold": 0.2,
"y_pianyi": 0,
"skip_if_countdown_lt_seconds": 5,
"no_attend_timeout_minutes": 30.0,
@@ -206,6 +206,7 @@
"coupon_template_match_threshold": 0.35,
"attend_button_red_ratio_threshold": 0.25,
"fansclub_join_red_ratio_threshold": 0.25,
"shopping_redpacket_ocr_confidence_threshold": 0.35,
"reservation_test_mode": false,
"swipe_duration_ms": 250,
"gui": {
+85
View File
@@ -0,0 +1,85 @@
# WiFi ADB 功能使用指南
## 功能概述
WiFi ADB 功能允许您通过WiFi网络连接Android设备进行调试,而不需要USB线缆。这对于远程调试或多设备管理非常有用。
## 为什么需要USB连接?
**重要说明:** Android系统的安全机制要求首次启用WiFi ADB时必须通过USB连接。这是Google为了安全考虑而设计的限制。
### 工作原理:
1. **USB阶段**:通过USB连接发送 `adb tcpip 5555` 命令启用WiFi ADB模式
2. **重启阶段**:设备重启并进入WiFi ADB模式
3. **WiFi阶段**:此后可以通过WiFi连接使用,无需USB线缆
### 好处:
- 设置完成后,设备会出现在"WiFi设备"列表中
- 可以同时管理多台设备
- 无需物理连接,方便远程操作
- 设备重启后自动保持WiFi ADB模式
## 使用方法
### 快速自动连接(推荐)
1. 确保您的Android设备已通过USB连接到电脑
2. 在抖音挂机GUI中点击"WiFi ADB"按钮
3. 在弹出的对话框中选择已连接的设备
4. 点击"自动连接"按钮
5. 系统将自动:
- 启用设备的WiFi ADB模式
- 等待设备重启
- 获取设备IP地址
- 建立WiFi连接
6. 连接成功后,设备将出现在设备列表中
### 手动连接
如果自动连接失败,可以使用手动方式:
1. 选择已连接的USB设备
2. 点击"启用WiFi ADB"按钮(设备将重启)
3. 等待设备重启完成后,输入IP地址
- 如果不知道IP地址,可以再次点击"启用WiFi ADB",系统会尝试自动获取
4. 点击"连接"按钮建立WiFi连接
5. 连接成功后,设备将出现在设备列表中
### 断开连接
1. 在WiFi ADB对话框中输入要断开连接的设备IP地址
2. 点击"断开"按钮
3. 设备将从ADB设备列表中移除
## 注意事项
- 设备和电脑必须在同一个WiFi网络中
- 确保设备已开启开发者选项和USB调试
- 自动连接时设备会重启,请等待重启完成(通常需要1-2分钟)
- 如果自动连接失败,请检查防火墙设置和网络连接
## 故障排除
### 自动连接失败
- 确认设备已正确连接到WiFi网络
- 检查设备电池电量和网络连接稳定性
- 尝试重启设备后重新连接
- 如果多次失败,使用手动连接方式
### 连接失败
- 确认IP地址正确且设备在线
- 检查端口5555是否被占用
- 确认设备和电脑在同一网络
- 尝试重启ADB服务:`adb kill-server && adb start-server`
### 无法获取IP地址
- 确保设备已连接到WiFi网络
- 检查设备网络设置
- 尝试手动输入IP地址
- 确认设备未开启飞行模式
### 设备重启后无法连接
- 等待设备完全启动完成
- 确认WiFi ADB模式仍处于启用状态
- 检查设备网络连接是否正常
- 尝试重新启用WiFi ADB模式
+31 -12
View File
@@ -1977,25 +1977,44 @@ class fudai_analyse:
if just_recorded:
self._just_recorded_reservation = False # 清除标志
try:
needswitch = bool(getattr(self, "needswitch", True))
self._log_kv(
"预约",
"[预约] 刚刚记录预约,继续在新直播间搜索福袋",
)
except Exception:
needswitch = True
if needswitch:
pass
try:
needswitch_cfg = bool(getattr(self, "needswitch", True))
except Exception:
needswitch_cfg = True
if needswitch_cfg:
try:
self.swipe_up_to_next_live()
except Exception as exc:
try:
self._log_kv(
"预约",
"[预约] 执行上滑切换失败",
error=str(exc),
error_type=type(exc).__name__,
)
except Exception:
pass
else:
try:
self._log_kv(
"预约",
"[预约] 刚刚记录预约,强制切换直播间避免循环",
"[预约] just_recorded_reservation 触发,但 needswitch=False,未切换",
)
except Exception:
pass
self.swipe_up_to_next_live()
elapsed = time.time() - start_time
self._log_kv(
"流程",
"run_once_basic完成(强制切换直播间)",
elapsed_seconds=round(elapsed, 2),
)
return
elapsed = time.time() - start_time
self._log_kv(
"流程",
"run_once_basic完成(记录预约后切换直播间)",
elapsed_seconds=round(elapsed, 2),
)
return
except Exception:
pass
+3 -3
View File
@@ -23,8 +23,8 @@ COUNTDOWN_1460_1580 = (390, 1460, 690, 1580)
# 任务列表区域(用于检测观看任务)
TASK_LIST = (50, 1621, 1032, 1960)
# 参与按钮区域
PARTICIPATE_BUTTON = (306, 2030, 780, 2110)
# 参与按钮区域(向下扩大,增强对部分机型底部按钮的覆盖)
PARTICIPATE_BUTTON = (306, 2030, 780, 2180)
# 扩大识别区域(加入粉丝团 / OCR 扩大区域)
JOIN_FANSCLUB_REGION = (150, 1900, 950, 2200)
@@ -65,5 +65,5 @@ DIAG_SHOPPING_REDPACKET = (200, 300, 880, 1000)
# 倒计时、任务、按钮等常用区域(保留占位,可根据需要填写)
# COUNTDOWN_BOX = (390, 1140, 570, 1290)
# BUTTON_BOX = (306, 2030, 780, 2110)
# BUTTON_BOX = (306, 2030, 780, 2180)
# CONTENT_BOX = (200, 600, 880, 900)
+6 -24
View File
@@ -465,23 +465,12 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo
# 价值:重模型兜底一次,兼容带符号文本
if "value" in fields:
val_digits = ""
try:
name_val = _safe_preprocess("福袋价值")
raw_val = analyser.operation.analyse_pic_digits(name_val, 1)
val_digits = "".join(ch for ch in str(raw_val or "") if ch.isdigit())
raw_val = analyser.operation.analyse_pic_word(name_val, 0)
results["value"] = str(raw_val or "")
except Exception:
pass
if not val_digits:
try:
raw_val = analyser.operation.analyse_pic_word(name_val, 1)
val_digits = "".join(
ch for ch in str(raw_val or "") if ch.isdigit()
)
except Exception:
pass
if val_digits:
results["value"] = val_digits
# 按钮状态:重模型兜底,避免轻量误判
if "button" in fields:
@@ -698,7 +687,7 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo
# 保存参与按钮区域的调试截图(仅在配置启用时)
if save_debug_images:
_save_full_screenshot_with_ocr_region(
analyser, "参与按钮", (306, 2030, 780, 2110), analyser.y_pianyi
analyser, "参与按钮", PARTICIPATE_BUTTON, analyser.y_pianyi
)
analyser.cut_pic(*PARTICIPATE_BUTTON, "", "参与按钮", analyser.y_pianyi)
except Exception as e_inner: # pyright: ignore[reportTooBroadExceptionType]
@@ -933,7 +922,7 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo
pass
def ocr_value():
"""OCR识别福袋价值:优先用数字模型提取金额,回退文本模型。"""
"""OCR识别福袋价值:使用普通OCR获取文本,支持小数点。"""
start = time.time()
try:
try:
@@ -941,16 +930,9 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo
except Exception:
name_val = "福袋价值"
# 先用数字模型提取金额,避免整段文本的开销
digits_raw = str(analyser.operation.analyse_pic_digits(name_val, 1) or "")
digits_only = "".join(ch for ch in digits_raw if ch.isdigit())
if digits_only:
return digits_only
# 回退:再跑一次文本模型,兼容包含货币符号的情况
# 使用普通OCR获取文本,支持小数点等
word_raw = str(analyser.operation.analyse_pic_word(name_val, 0) or "")
word_digits = "".join(ch for ch in word_raw if ch.isdigit())
return word_digits or word_raw
return word_raw
except Exception as e_inner:
try:
analyser._log_kv(
+50 -7
View File
@@ -379,15 +379,30 @@ def diagnose_stage_from_current_screen(analyser, trigger_reason="unknown"): # t
name_rp0 = preprocess_for_ocr(
analyser, "診斷購物紅包-非直播间复查"
)
redpacket_text = str(
analyser.operation.analyse_pic_word(name_rp0, 0) or ""
ocr_result = analyser.operation.analyse_pic_word(
name_rp0, 0, return_confidence=True
)
if isinstance(ocr_result, tuple):
redpacket_text, ocr_confidence_info = ocr_result
else:
redpacket_text = str(ocr_result or "")
ocr_confidence_info = None
ocr_elapsed = (time.time() - ocr_start) * 1000
_log(
"步骤2.5[购物红包OCR复查]-OCR模式0",
耗时毫秒=ocr_elapsed,
文本长度=len(redpacket_text),
文本预览=redpacket_text[:50] if redpacket_text else "",
平均置信度=(
ocr_confidence_info.get("avg_confidence")
if ocr_confidence_info
else None
),
最大置信度=(
ocr_confidence_info.get("max_confidence")
if ocr_confidence_info
else None
),
)
redpacket_keywords = ("购物红包", "邀你抢", "抢红包")
@@ -402,10 +417,14 @@ def diagnose_stage_from_current_screen(analyser, trigger_reason="unknown"): # t
name_rp1 = preprocess_for_ocr(
analyser, "診斷購物紅包-非直播间复查"
)
redpacket_text = str(
analyser.operation.analyse_pic_word(name_rp1, 1)
or ""
ocr_result_1 = analyser.operation.analyse_pic_word(
name_rp1, 1, return_confidence=True
)
if isinstance(ocr_result_1, tuple):
redpacket_text, ocr_confidence_info = ocr_result_1
else:
redpacket_text = str(ocr_result_1 or "")
ocr_confidence_info = None
ocr_elapsed_1 = (time.time() - ocr_start_1) * 1000
_log(
"步骤2.5[购物红包OCR复查]-OCR模式1",
@@ -414,12 +433,36 @@ def diagnose_stage_from_current_screen(analyser, trigger_reason="unknown"): # t
文本预览=(
redpacket_text[:50] if redpacket_text else ""
),
平均置信度=(
ocr_confidence_info.get("avg_confidence")
if ocr_confidence_info
else None
),
最大置信度=(
ocr_confidence_info.get("max_confidence")
if ocr_confidence_info
else None
),
)
if redpacket_text and any(
# 检查关键词匹配或置信度阈值
has_keyword_match = redpacket_text and any(
kw in redpacket_text for kw in redpacket_keywords
):
)
has_high_confidence = (
ocr_confidence_info
and ocr_confidence_info.get("max_confidence", 0)
>= analyser.shopping_redpacket_ocr_confidence_threshold
)
if has_keyword_match or has_high_confidence:
redpacket_verified = True
_log(
"步骤2.5[购物红包OCR复查]-命中",
关键词匹配=has_keyword_match,
高置信度匹配=has_high_confidence,
阈值=analyser.shopping_redpacket_ocr_confidence_threshold,
)
except Exception as e:
redpacket_elapsed = (time.time() - step_redpacket_ocr_start) * 1000
_log(
+12
View File
@@ -170,6 +170,18 @@ class ConfigManager:
analyser, "shopping_redpacket_red_ratio_threshold", 0.15
)
if "shopping_redpacket_ocr_confidence_threshold" in config:
threshold = float(
config["shopping_redpacket_ocr_confidence_threshold"] or 0.35
)
analyser.shopping_redpacket_ocr_confidence_threshold = max(
0.0, min(1.0, threshold)
)
else:
analyser.shopping_redpacket_ocr_confidence_threshold = getattr(
analyser, "shopping_redpacket_ocr_confidence_threshold", 0.35
)
# 粉丝团等待/点击延迟配置
if "fansclub_click_delay" in config:
analyser.fansclub_click_delay = float(config["fansclub_click_delay"] or 0.6)
+331
View File
@@ -22,6 +22,13 @@ from gui.gui_core import (
Runner,
find_adb_executable,
list_adb_devices,
enable_wifi_adb,
connect_wifi_adb,
disconnect_wifi_adb,
get_device_ip,
auto_connect_wifi_adb,
is_device_wifi_connected,
get_connected_wifi_devices,
read_config,
write_config,
)
@@ -148,6 +155,8 @@ def main():
# 常量兜底:部分主题常量未提供时使用字符串
BOTTOM = "bottom"
# W 常量在部分导入路径中可能不存在,兜底为 'w'(grid sticky 使用)
W = "w"
root.title("抖音福袋挂机 - 可视化控制台")
root.geometry("1400x900") # 增大窗口尺寸,提供更多空间
@@ -363,6 +372,328 @@ def main():
refresh_devices_btn = ttk.Button(top, text="刷新设备", command=refresh_devices)
refresh_devices_btn.pack(side=LEFT, padx=(0, 20))
# WiFi ADB 功能
def open_wifi_adb_dialog():
"""打开WiFi ADB设置对话框"""
dialog = tk.Toplevel(root)
dialog.title("WiFi ADB 设置")
dialog.geometry("500x450")
# 允许用户调整对话框大小,避免窗口内容被裁剪
dialog.resizable(True, True)
dialog.minsize(420, 320)
# 获取设备列表并分类
current_devices = list_adb_devices(adb_exe)
wifi_devices = get_connected_wifi_devices(adb_exe)
usb_devices = [d for d in current_devices if d not in wifi_devices]
# 创建设备选择区域
device_frame = ttk.LabelFrame(dialog, text="设备选择", padding=10)
device_frame.pack(fill=X, padx=10, pady=10)
# 使内部 grid 列随窗口宽度伸缩
device_frame.grid_columnconfigure(0, weight=3)
device_frame.grid_columnconfigure(1, weight=1)
# USB设备选择
ttk.Label(device_frame, text="USB设备(用于首次启用):").grid(
row=0, column=0, sticky=W, pady=(0, 5)
)
usb_device_var = tk.StringVar(value=(usb_devices[0] if usb_devices else ""))
usb_combo = ttk.Combobox(
device_frame,
textvariable=usb_device_var,
values=usb_devices,
width=25,
state="readonly" if not usb_devices else "normal",
)
usb_combo.grid(row=1, column=0, padx=(0, 10), pady=(0, 10), sticky="we")
# 显示USB设备状态
usb_status_text = (
f"检测到 {len(usb_devices)} 个USB设备"
if usb_devices
else "未检测到USB设备,请确保设备已连接并授权"
)
usb_status_label = ttk.Label(
device_frame,
text=usb_status_text,
font=("Arial", 8),
foreground="red" if not usb_devices else "green",
)
usb_status_label.grid(row=2, column=0, sticky=W, pady=(0, 10))
# WiFi设备选择
ttk.Label(device_frame, text="WiFi设备(已连接):").grid(
row=0, column=1, sticky=W, pady=(0, 5)
)
wifi_device_var = tk.StringVar(value=(wifi_devices[0] if wifi_devices else ""))
wifi_combo = ttk.Combobox(
device_frame,
textvariable=wifi_device_var,
values=wifi_devices,
width=25,
state="readonly" if not wifi_devices else "normal",
)
wifi_combo.grid(row=1, column=1, pady=(0, 10), sticky="we")
# 显示WiFi设备状态
wifi_status_text = (
f"已连接 {len(wifi_devices)} 个WiFi设备"
if wifi_devices
else "无WiFi设备连接"
)
wifi_status_label = ttk.Label(
device_frame,
text=wifi_status_text,
font=("Arial", 8),
foreground="blue" if wifi_devices else "gray",
)
wifi_status_label.grid(row=2, column=1, sticky=W, pady=(0, 10))
# IP地址输入区域
ip_frame = ttk.LabelFrame(dialog, text="连接信息", padding=10)
ip_frame.pack(fill=X, padx=10, pady=(0, 10))
# 使 IP/端口 输入框随窗口宽度伸缩
ip_frame.grid_columnconfigure(0, weight=3)
ip_frame.grid_columnconfigure(1, weight=1)
ttk.Label(ip_frame, text="设备IP地址:").grid(
row=0, column=0, sticky=W, pady=(0, 5)
)
ip_var = tk.StringVar()
ip_entry = ttk.Entry(ip_frame, textvariable=ip_var, width=25)
ip_entry.grid(row=1, column=0, padx=(0, 10), pady=(0, 10), sticky="we")
ttk.Label(ip_frame, text="端口(默认5555):").grid(
row=0, column=1, sticky=W, pady=(0, 5)
)
port_var = tk.StringVar(value="5555")
port_entry = ttk.Entry(ip_frame, textvariable=port_var, width=25)
port_entry.grid(row=1, column=1, pady=(0, 10), sticky="we")
# 按钮区域
button_frame = ttk.Frame(dialog)
button_frame.pack(fill=X, padx=10, pady=10)
def enable_wifi():
device_id = usb_device_var.get()
if not device_id:
on_line("[WiFi ADB] 请先选择USB设备")
return
success, msg = enable_wifi_adb(adb_exe, device_id)
on_line(f"[WiFi ADB] {msg}")
if success:
# 尝试获取IP地址
ip_success, ip_msg = get_device_ip(adb_exe, device_id)
if ip_success:
ip_var.set(ip_msg)
on_line(f"[WiFi ADB] 设备IP地址: {ip_msg}")
def connect_wifi():
ip = ip_var.get().strip()
port = port_var.get().strip()
if not ip:
on_line("[WiFi ADB] 请输入IP地址")
return
success, msg = connect_wifi_adb(adb_exe, ip, port)
on_line(f"[WiFi ADB] {msg}")
if success:
# 刷新设备列表
refresh_devices()
# 重新打开对话框以显示新的WiFi设备
dialog.destroy()
open_wifi_adb_dialog()
def disconnect_wifi():
device_id = wifi_device_var.get()
if not device_id:
on_line("[WiFi ADB] 请先选择WiFi设备")
return
# 从设备ID中提取IP地址
ip_match = re.search(r"(\d+\.\d+\.\d+\.\d+)", device_id)
if not ip_match:
on_line("[WiFi ADB] 无法从设备ID中提取IP地址")
return
ip = ip_match.group(1)
success, msg = disconnect_wifi_adb(adb_exe, ip, "5555")
on_line(f"[WiFi ADB] {msg}")
if success:
# 刷新设备列表
refresh_devices()
# 重新打开对话框以更新设备列表
dialog.destroy()
open_wifi_adb_dialog()
def auto_connect_wifi():
device_id = usb_device_var.get()
if not device_id:
on_line("[WiFi ADB] 请先选择USB设备")
return
# 显示进度
on_line("[WiFi ADB] 开始自动连接...")
# 创建进度对话框
progress_dialog = tk.Toplevel(dialog)
progress_dialog.title("自动连接中...")
progress_dialog.geometry("300x120")
progress_dialog.resizable(False, False)
ttk.Label(progress_dialog, text="正在自动连接WiFi ADB,请稍候...").pack(
pady=10
)
ttk.Label(progress_dialog, text="设备将会重启,请等待重启完成").pack(
pady=(0, 10)
)
progress_bar = ttk.Progressbar(progress_dialog, mode="indeterminate")
progress_bar.pack(fill=X, padx=20, pady=(0, 20))
progress_bar.start()
def do_auto_connect():
try:
success, msg = auto_connect_wifi_adb(adb_exe, device_id)
progress_dialog.destroy()
on_line(f"[WiFi ADB] {msg}")
if success:
# 刷新设备列表
refresh_devices()
# 尝试获取并显示IP
ip_success, ip_msg = get_device_ip(adb_exe, device_id)
if ip_success:
ip_var.set(ip_msg)
# 重新打开对话框以显示新的WiFi设备
dialog.destroy()
open_wifi_adb_dialog()
except Exception as e:
progress_dialog.destroy()
on_line(f"[WiFi ADB] 自动连接异常: {str(e)}")
# 在后台线程中执行自动连接
threading.Thread(target=do_auto_connect, daemon=True).start()
# 放大/恢复窗口支持(当系统边框无法调整窗口时提供备用按钮)
is_maximized = False
original_geometry = None
def toggle_maximize():
nonlocal is_maximized, original_geometry
try:
if not is_maximized:
original_geometry = dialog.geometry()
dialog.update_idletasks()
w = int(dialog.winfo_screenwidth() * 0.8)
h = int(dialog.winfo_screenheight() * 0.8)
dialog.geometry(f"{w}x{h}")
is_maximized = True
else:
if original_geometry:
dialog.geometry(original_geometry)
is_maximized = False
except Exception as e:
on_line(f"[WiFi ADB] 切换窗口大小失败: {e}")
def refresh_device_lists():
"""刷新设备列表"""
nonlocal usb_devices, wifi_devices
current_devices = list_adb_devices(adb_exe)
wifi_devices = get_connected_wifi_devices(adb_exe)
usb_devices = [d for d in current_devices if d not in wifi_devices]
# 更新USB设备下拉框
usb_combo["values"] = usb_devices
usb_combo["state"] = "readonly" if not usb_devices else "normal"
if usb_devices:
usb_device_var.set(usb_devices[0])
else:
usb_device_var.set("")
# 更新WiFi设备下拉框
wifi_combo["values"] = wifi_devices
wifi_combo["state"] = "readonly" if not wifi_devices else "normal"
if wifi_devices:
wifi_device_var.set(wifi_devices[0])
else:
wifi_device_var.set("")
# 更新状态标签
usb_status_text = (
f"检测到 {len(usb_devices)} 个USB设备"
if usb_devices
else "未检测到USB设备,请确保设备已连接并授权"
)
usb_status_label.config(
text=usb_status_text, foreground="red" if not usb_devices else "green"
)
wifi_status_text = (
f"已连接 {len(wifi_devices)} 个WiFi设备"
if wifi_devices
else "无WiFi设备连接"
)
wifi_status_label.config(
text=wifi_status_text, foreground="blue" if wifi_devices else "gray"
)
on_line("[WiFi ADB] 设备列表已刷新")
# USB设备操作按钮
usb_button_frame = ttk.Frame(button_frame)
usb_button_frame.pack(fill=X, pady=(0, 10))
ttk.Label(usb_button_frame, text="USB设备操作:").pack(anchor=W)
usb_buttons_frame = ttk.Frame(usb_button_frame)
usb_buttons_frame.pack(fill=X, pady=(5, 0))
ttk.Button(usb_buttons_frame, text="自动连接", command=auto_connect_wifi).pack(
side=LEFT, padx=(0, 10)
)
ttk.Button(usb_buttons_frame, text="启用WiFi ADB", command=enable_wifi).pack(
side=LEFT, padx=(0, 10)
)
ttk.Button(usb_buttons_frame, text="连接", command=connect_wifi).pack(
side=LEFT, padx=(0, 10)
)
ttk.Button(
usb_buttons_frame, text="刷新设备", command=refresh_device_lists
).pack(side=LEFT)
# 如果窗口无法通过边框调整,提供放大/恢复按钮作为备用
ttk.Button(usb_buttons_frame, text="放大/恢复", command=toggle_maximize).pack(
side=LEFT, padx=(8, 0)
)
# WiFi设备操作按钮
wifi_button_frame = ttk.Frame(button_frame)
wifi_button_frame.pack(fill=X, pady=(10, 0))
ttk.Label(wifi_button_frame, text="WiFi设备操作:").pack(anchor=W)
wifi_buttons_frame = ttk.Frame(wifi_button_frame)
wifi_buttons_frame.pack(fill=X, pady=(5, 0))
ttk.Button(wifi_buttons_frame, text="断开连接", command=disconnect_wifi).pack(
side=LEFT
)
# 说明文本
info_text = """重要说明:
• Android系统安全要求:首次启用WiFi ADB必须通过USB连接
• 工作流程:USB连接 → 启用WiFi ADB → 设备重启 → WiFi连接
• 设置完成后,设备会出现在"WiFi设备"列表中,无需再次USB连接
• 设备重启后WiFi ADB模式会保持,可直接通过WiFi连接使用
使用方法:
1. 连接Android设备到电脑(USB)
2. 点击"刷新设备"确保设备被检测到
3. 选择USB设备,点击"自动连接"或手动操作
4. 等待设备重启后即可通过WiFi使用"""
info_label = ttk.Label(
dialog, text=info_text, justify=LEFT, font=("Arial", 9), wraplength=460
)
info_label.pack(pady=(10, 0), padx=20, anchor="w")
wifi_adb_btn = ttk.Button(top, text="WiFi ADB", command=open_wifi_adb_dialog)
wifi_adb_btn.pack(side=LEFT, padx=(0, 20))
# 配置区(提前读取配置,供后续使用)
cfg = read_config()
+322
View File
@@ -59,6 +59,296 @@ def list_adb_devices(adb_exe: str) -> list[str]:
return re.findall(pattern, text)
def is_device_wifi_connected(adb_exe: str, device_id: str) -> bool:
"""检查设备是否已经在WiFi ADB模式下连接
Args:
adb_exe: ADB可执行文件路径
device_id: 设备ID(IP:端口格式)
Returns:
bool: 是否为WiFi连接
"""
if not device_id or not adb_exe:
return False
# 检查device_id是否为IP:端口格式
if ":" in device_id and device_id.split(":")[0].count(".") == 3:
return True
return False
def get_connected_wifi_devices(adb_exe: str) -> list[str]:
"""获取已连接的WiFi ADB设备列表
Args:
adb_exe: ADB可执行文件路径
Returns:
list: WiFi连接的设备ID列表
"""
devices = list_adb_devices(adb_exe)
wifi_devices = []
for device in devices:
if is_device_wifi_connected(adb_exe, device):
wifi_devices.append(device)
return wifi_devices
def enable_wifi_adb(adb_exe: str, device_id: str) -> tuple[bool, str]:
"""启用设备的WiFi ADB调试模式
Args:
adb_exe: ADB可执行文件路径
device_id: 设备ID
Returns:
tuple: (成功否, 消息)
"""
try:
if not adb_exe or not device_id:
return False, "ADB路径或设备ID为空"
# 启用TCP/IP模式
proc = subprocess.run(
[adb_exe, "-s", device_id, "tcpip", "5555"],
capture_output=True,
text=True,
encoding="utf-8",
errors="replace",
check=False,
timeout=10,
)
if proc.returncode == 0:
return True, "WiFi ADB已启用,请等待设备重启完成"
else:
error_msg = (proc.stdout or "") + "\n" + (proc.stderr or "")
return False, f"启用WiFi ADB失败: {error_msg}"
except subprocess.TimeoutExpired:
return False, "启用WiFi ADB超时"
except Exception as e:
return False, f"启用WiFi ADB异常: {str(e)}"
def connect_wifi_adb(
adb_exe: str, ip_address: str, port: str = "5555"
) -> tuple[bool, str]:
"""连接到WiFi ADB设备
Args:
adb_exe: ADB可执行文件路径
ip_address: 设备IP地址
port: 端口号,默认5555
Returns:
tuple: (成功否, 消息)
"""
try:
if not adb_exe or not ip_address:
return False, "ADB路径或IP地址为空"
# 支持 ip:port 或单纯 ip 的两种情况
if ":" in ip_address:
target = ip_address
else:
target = f"{ip_address}:{port}"
# 连接到设备
proc = subprocess.run(
[adb_exe, "connect", target],
capture_output=True,
text=True,
encoding="utf-8",
errors="replace",
check=False,
timeout=10,
)
output = (proc.stdout or "") + "\n" + (proc.stderr or "")
low = output.lower()
# adb connect 在成功/已连接时常包含 'connected' 或 'already connected' 文本
if proc.returncode == 0 and ("connected" in low or "already connected" in low):
return True, f"成功连接到 {target}"
else:
return False, f"连接失败: {output}"
except subprocess.TimeoutExpired:
return False, "连接WiFi ADB超时"
except Exception as e:
return False, f"连接WiFi ADB异常: {str(e)}"
def disconnect_wifi_adb(
adb_exe: str, ip_address: str, port: str = "5555"
) -> tuple[bool, str]:
"""断开WiFi ADB连接
Args:
adb_exe: ADB可执行文件路径
ip_address: 设备IP地址
port: 端口号,默认5555
Returns:
tuple: (成功否, 消息)
"""
try:
if not adb_exe or not ip_address:
return False, "ADB路径或IP地址为空"
target = f"{ip_address}:{port}"
# 断开连接
proc = subprocess.run(
[adb_exe, "disconnect", target],
capture_output=True,
text=True,
encoding="utf-8",
errors="replace",
check=False,
timeout=10,
)
output = (proc.stdout or "") + "\n" + (proc.stderr or "")
if proc.returncode == 0:
return True, f"成功断开连接 {target}"
else:
return False, f"断开连接失败: {output}"
except subprocess.TimeoutExpired:
return False, "断开WiFi ADB超时"
except Exception as e:
return False, f"断开WiFi ADB异常: {str(e)}"
def get_device_ip(adb_exe: str, device_id: str) -> tuple[bool, str]:
"""获取设备的IP地址
Args:
adb_exe: ADB可执行文件路径
device_id: 设备ID
Returns:
tuple: (成功否, IP地址或错误消息)
"""
try:
if not adb_exe or not device_id:
return False, "ADB路径或设备ID为空"
# 获取网络接口信息
proc = subprocess.run(
[adb_exe, "-s", device_id, "shell", "ip", "route"],
capture_output=True,
text=True,
encoding="utf-8",
errors="replace",
check=False,
timeout=10,
)
if proc.returncode == 0:
# 解析输出获取IP地址
lines = proc.stdout.strip().split("\n")
for line in lines:
if "src" in line:
parts = line.split()
for part in parts:
if part.count(".") == 3: # IP地址格式
return True, part
return False, "无法从设备获取IP地址"
else:
error_msg = (proc.stdout or "") + "\n" + (proc.stderr or "")
return False, f"获取IP地址失败: {error_msg}"
except subprocess.TimeoutExpired:
return False, "获取设备IP超时"
except Exception as e:
return False, f"获取设备IP异常: {str(e)}"
def auto_connect_wifi_adb(
adb_exe: str, device_id: str, max_attempts: int = 3
) -> tuple[bool, str]:
"""自动启用WiFi ADB并连接设备
Args:
adb_exe: ADB可执行文件路径
device_id: 设备ID
max_attempts: 最大尝试次数
Returns:
tuple: (成功否, 消息)
"""
try:
if not adb_exe or not device_id:
return False, "ADB路径或设备ID为空"
# 先检查当前 adb 设备列表,看 device_id 是否已经以 WiFi 形式存在(ip:port)
try:
current = list_adb_devices(adb_exe)
except Exception:
current = []
# 如果 device_id 本身就是 ip:port 格式,且已经在 adb devices 中,则视为已连接
if is_device_wifi_connected(adb_exe, device_id) and device_id in current:
return True, f"设备已通过 WiFi 连接: {device_id}"
# 如果 device_id 是 ip:port 格式但不在 adb devices 中,尝试直接连接这个 target
if is_device_wifi_connected(adb_exe, device_id) and device_id not in current:
conn_ok, conn_msg = connect_wifi_adb(adb_exe, device_id)
if conn_ok:
return True, f"直接连接成功: {device_id}"
else:
return False, f"直接连接失败: {conn_msg}"
# 如果 device_id 是 USB 序列(非 ip:port),执行启用 tcpip 流程作为后备
enable_success, enable_msg = enable_wifi_adb(adb_exe, device_id)
if not enable_success:
return False, f"启用WiFi ADB失败: {enable_msg}"
# 等待设备重启开始
time.sleep(3)
# 尝试多次获取IP并连接(优先提取纯 IPv4 地址或 ip:port)
for attempt in range(max_attempts):
wait_time = 5 + attempt * 2
time.sleep(wait_time)
ip_success, ip_msg = get_device_ip(adb_exe, device_id)
if not ip_success:
if attempt == max_attempts - 1:
return False, f"获取IP地址失败: {ip_msg}"
continue
ip_address = ip_msg
# 提取 ip 或 ip:port
m = re.search(r"(\d+\.\d+\.\d+\.\d+)(?::(\d+))?", ip_address)
if m:
host = m.group(1)
port_found = m.group(2) or "5555"
target = f"{host}:{port_found}"
else:
target = ip_address
connect_success, connect_msg = connect_wifi_adb(adb_exe, target)
if connect_success:
return True, f"自动连接成功! target: {target}"
if attempt == max_attempts - 1:
return False, f"连接失败: {connect_msg}"
return False, "自动连接超时,请稍后重试"
except Exception as e:
return False, f"自动连接异常: {str(e)}"
def read_config() -> dict:
if not os.path.exists(CONFIG_PATH):
return {}
@@ -1074,6 +1364,38 @@ class Runner:
"[警告] 未找到 adb.exe:请安装 platform-tools 或将 adb 加入 PATH"
)
# 如果用户指定了 device_id,但当前 adb 列表中没有该设备,则尝试回退到任意可用设备
try:
if getattr(params, "device_id", None):
try:
available = list_adb_devices(adb_exe)
except Exception as _:
available = []
if params.device_id not in available:
if available:
fallback = available[0]
self._emit_line(
f"[警告] 配置的 device_id '{params.device_id}' 当前不可见,自动改用 '{fallback}'"
)
# 将 cmd 中的 --device-id 参数替换为 fallback
try:
i = cmd.index("--device-id")
if i + 1 < len(cmd):
cmd[i + 1] = fallback
except ValueError:
# 没有找到 --device-id 则追加
cmd += ["--device-id", fallback]
else:
# 没有任何设备在线,提示并中止启动
self._emit_line(
f"[错误] 配置的 device_id '{params.device_id}' 不在线,且未检测到其它 adb 设备。请连接设备或指定正确的 device-id。"
)
raise RuntimeError("没有可用的 adb 设备")
except Exception as e:
# 仅记录告警,不阻塞后续的调试信息(启动进程时仍可能失败)
self._emit_line(f"[警告] 检查可用 adb 设备时发生异常: {e}")
try:
p = subprocess.Popen(
cmd,
+5
View File
@@ -11,6 +11,11 @@ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from typing import Optional
from urllib.parse import parse_qs, urlparse
# Add project root to Python path
project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
if project_root not in sys.path:
sys.path.insert(0, project_root)
import path_config
BASE_DIR = path_config.PROJECT_ROOT
+3 -3
View File
@@ -12,11 +12,11 @@ numpy>=1.20.0
opencv-python>=4.5.0
# OCR识别 - PaddleOCR(主要OCR引擎)
paddleocr>=2.7.0
paddleocr>=3.0.0
# 深度学习框架(PaddleOCR的依赖)
# 注意:PaddleOCR会自动安装paddlepaddle,但为了确保版本兼容性,建议显式安装
paddlepaddle>=2.5.0,<3.0.0
# 注意:PaddleOCR 3.0 需要 PaddlePaddle 3.0+
paddlepaddle>=3.0.0
# ========== GUI相关依赖 ==========
# 现代化GUI框架(可选,如果未安装会自动回退到原生tkinter)
+9 -8
View File
@@ -9,16 +9,16 @@ set "_ORIG_CP=%_ORIG_CP: =%"
chcp 65001 >nul 2>&1
setlocal enabledelayedexpansion
REM Change to script directory
cd /d "%~dp0"
REM Change to project root directory (parent of scripts)
cd /d "%~dp0.."
if errorlevel 1 (
echo [ERROR] Cannot change to script directory
echo [ERROR] Cannot change to project root directory
pause
goto :cleanup
)
REM Save current directory to variable (for delayed expansion)
set "WORK_DIR=%~dp0"
set "WORK_DIR=%~dp0.."
set "WORK_DIR=!WORK_DIR:~0,-1!"
REM Create log file
@@ -50,9 +50,10 @@ echo.
REM [2/6] Check required files
echo [2/6] Checking required files...
if not exist "web_gui.py" (
if not exist "gui\web_gui.py" (
echo [ERROR] web_gui.py not found
echo Current directory: !WORK_DIR!
echo Expected path: !WORK_DIR!\gui\web_gui.py
echo [ERROR] web_gui.py does not exist >> "%LOG_FILE%"
pause
goto :cleanup
@@ -105,13 +106,13 @@ if exist ".venv\Scripts\python.exe" (
REM Start service (in new window, keep window open)
if !USE_VENV! equ 1 (
REM Use virtual environment python.exe directly (use full path)
set "PYTHON_CMD=!WORK_DIR!\.venv\Scripts\python.exe web_gui.py"
set "PYTHON_CMD=!WORK_DIR!\.venv\Scripts\python.exe gui\web_gui.py"
) else if !USE_VENV! equ 2 (
REM Use activate.bat
set "PYTHON_CMD=call !WORK_DIR!\.venv\Scripts\activate.bat && python web_gui.py"
set "PYTHON_CMD=call !WORK_DIR!\.venv\Scripts\activate.bat && python gui\web_gui.py"
) else (
REM Use system Python
set "PYTHON_CMD=python web_gui.py"
set "PYTHON_CMD=python gui\web_gui.py"
)
REM Start command with proper quoting
+230
View File
@@ -0,0 +1,230 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
OCR引擎性能对比测试
测试 EasyOCR vs PaddleOCR 的各项性能参数
"""
import os
import sys
import time
import psutil
import gc
from pathlib import Path
def get_memory_usage():
"""获取当前内存使用情况"""
process = psutil.Process(os.getpid())
return process.memory_info().rss / 1024 / 1024 # MB
def test_easyocr_performance():
"""测试EasyOCR性能"""
print("测试 EasyOCR 性能...")
results = {
"type": "EasyOCR",
"init_time": 0,
"recognition_times": [],
"memory_usage": 0,
}
try:
# 测试初始化
memory_before = get_memory_usage()
start_time = time.time()
import easyocr
reader = easyocr.Reader(["ch_sim", "en"])
init_time = time.time() - start_time
memory_after = get_memory_usage()
results["init_time"] = init_time
results["memory_usage"] = memory_after - memory_before
results["version"] = easyocr.__version__
print(f" 初始化时间: {init_time:.2f}秒")
print(f" 内存增加: {memory_after - memory_before:.2f}MB")
# 查找测试图片
pic_dir = Path("pic")
test_images = list(pic_dir.glob("*.png"))[:2] # 最多2张图片
if not test_images:
# 创建测试图片
from PIL import Image, ImageDraw
img = Image.new("RGB", (300, 100), color="white")
draw = ImageDraw.Draw(img)
draw.text((10, 30), "测试文本 123.45元", fill="black")
test_path = pic_dir / "test_ocr.png"
test_path.parent.mkdir(exist_ok=True)
img.save(test_path)
test_images = [test_path]
# 测试识别性能
for img_path in test_images:
print(f" 测试图片: {img_path.name}")
for i in range(3): # 3次测试
start_time = time.time()
results_ocr = reader.readtext(str(img_path))
elapsed = time.time() - start_time
results["recognition_times"].append(elapsed)
print(f" 第{i+1}次: {elapsed:.2f}秒")
# 清理
del reader
gc.collect()
except Exception as e:
results["error"] = str(e)
print(f" [ERROR] {e}")
return results
def test_paddleocr_performance():
"""测试PaddleOCR性能"""
print("测试 PaddleOCR 性能...")
results = {
"type": "PaddleOCR",
"init_time": 0,
"recognition_times": [],
"memory_usage": 0,
}
try:
# 测试初始化
memory_before = get_memory_usage()
start_time = time.time()
from paddleocr import PaddleOCR
ocr = PaddleOCR(use_angle_cls=True, lang="ch")
init_time = time.time() - start_time
memory_after = get_memory_usage()
results["init_time"] = init_time
results["memory_usage"] = memory_after - memory_before
results["version"] = getattr(PaddleOCR, "__version__", "3.3.2")
print(f" 初始化时间: {init_time:.2f}秒")
print(f" 内存增加: {memory_after - memory_before:.2f}MB")
# 查找测试图片
pic_dir = Path("pic")
test_images = list(pic_dir.glob("*.png"))[:2] # 最多2张图片
if not test_images:
# 创建测试图片
from PIL import Image, ImageDraw
img = Image.new("RGB", (300, 100), color="white")
draw = ImageDraw.Draw(img)
draw.text((10, 30), "测试文本 123.45元", fill="black")
test_path = pic_dir / "test_ocr.png"
test_path.parent.mkdir(exist_ok=True)
img.save(test_path)
test_images = [test_path]
# 测试识别性能
for img_path in test_images:
print(f" 测试图片: {img_path.name}")
for i in range(3): # 3次测试
start_time = time.time()
results_ocr = ocr.ocr(str(img_path))
elapsed = time.time() - start_time
results["recognition_times"].append(elapsed)
print(f" 第{i+1}次: {elapsed:.2f}秒")
# 清理
del ocr
gc.collect()
except Exception as e:
results["error"] = str(e)
print(f" [ERROR] {e}")
return results
def main():
"""主函数"""
print("OCR引擎性能对比测试")
print("=" * 60)
print(f"测试时间: {time.strftime('%Y-%m-%d %H:%M:%S')}")
print(f"Python版本: {sys.version.split()[0]}")
print(f"CPU核心数: {psutil.cpu_count()}")
print(f"总内存: {psutil.virtual_memory().total / 1024 / 1024 / 1024:.1f}GB")
print()
# 测试EasyOCR
easyocr_results = test_easyocr_performance()
print()
# 测试PaddleOCR
paddleocr_results = test_paddleocr_performance()
print()
# 结果对比
print("性能对比结果")
print("=" * 60)
def print_stats(name, results):
if "error" in results:
print(f"{name}: 失败 - {results['error']}")
return
init_time = results["init_time"]
memory = results["memory_usage"]
times = results["recognition_times"]
if times:
avg_time = sum(times) / len(times)
min_time = min(times)
max_time = max(times)
print(f"{name} (v{results.get('version', 'unknown')}):")
print(f" 初始化: {init_time:.2f}秒, 内存: {memory:.1f}MB")
print(
f" 识别平均: {avg_time:.2f}秒 (范围: {min_time:.2f}-{max_time:.2f}秒)"
)
else:
print(f"{name}: 无识别测试数据")
print_stats("EasyOCR", easyocr_results)
print()
print_stats("PaddleOCR", paddleocr_results)
print()
# 推荐
if (
"error" not in easyocr_results
and "error" not in paddleocr_results
and easyocr_results["recognition_times"]
and paddleocr_results["recognition_times"]
):
easyocr_avg = sum(easyocr_results["recognition_times"]) / len(
easyocr_results["recognition_times"]
)
paddleocr_avg = sum(paddleocr_results["recognition_times"]) / len(
paddleocr_results["recognition_times"]
)
print("推荐:")
if easyocr_avg < paddleocr_avg:
faster_ratio = paddleocr_avg / easyocr_avg
print(f"• EasyOCR 更快 ({faster_ratio:.1f}倍), 适合速度优先场景")
print("• PaddleOCR 更准, 适合准确率优先场景")
else:
faster_ratio = easyocr_avg / paddleocr_avg
print(f"• PaddleOCR 更快 ({faster_ratio:.1f}倍), 推荐使用")
print("• EasyOCR 作为备用选项")
print("• 当前项目策略 (EasyOCR优先+PaddleOCR备用) 是合理的")
if __name__ == "__main__":
main()
+41
View File
@@ -0,0 +1,41 @@
import sys
import os
import time
import subprocess
import threading
# Add project root to path
project_root = os.path.dirname(os.path.abspath(__file__))
if project_root not in sys.path:
sys.path.insert(0, project_root)
import gui.web_gui as wg
def test_server():
# Start server in background thread
def run_server():
try:
wg.main()
except SystemExit:
pass
server_thread = threading.Thread(target=run_server, daemon=True)
server_thread.start()
# Wait for server to start
time.sleep(2)
# Test API
try:
import requests
response = requests.get('http://localhost:8001/api/config', timeout=5)
print(f"Status: {response.status_code}")
print(f"Response length: {len(response.text)}")
data = response.json()
print(f"Config keys: {len(data)}")
print(f"Sample keys: {list(data.keys())[:5]}")
except Exception as e:
print(f"Error: {e}")
if __name__ == "__main__":
test_server()
+123
View File
@@ -0,0 +1,123 @@
#!/usr/bin/env python3
"""
工具脚本:自动将通过 USB 连接的设备切换到 WiFi ADB 并建立连接。
用法示例:
python tools/auto_connect_wifi_adb.py --all
python tools/auto_connect_wifi_adb.py --device MB75DEFQZHZTGMLJ
该脚本依赖仓库中的 `gui.gui_core` 中的 ADB 辅助函数(如 `auto_connect_wifi_adb`)。
"""
import argparse
import sys
import os
from typing import List
# 当从 tools 目录直接运行脚本时,Python 的 sys.path[0] 会是 tools/,需要把项目根目录加入路径
this_dir = os.path.dirname(os.path.abspath(__file__))
project_root = os.path.abspath(os.path.join(this_dir, ".."))
if project_root not in sys.path:
sys.path.insert(0, project_root)
try:
from gui.gui_core import (
find_adb_executable,
list_adb_devices,
get_connected_wifi_devices,
auto_connect_wifi_adb,
)
except Exception as e:
print(f"无法导入 gui.gui_core: {e}", file=sys.stderr)
sys.exit(2)
def choose_targets(adb_exe: str, device_arg: str | None, all_flag: bool) -> List[str]:
devices = list_adb_devices(adb_exe)
wifi = get_connected_wifi_devices(adb_exe)
usb_devices = [d for d in devices if d not in wifi]
if device_arg:
if device_arg not in devices:
raise ValueError(f"指定的设备 {device_arg} 未在 adb 设备列表中: {devices}")
return [device_arg]
if all_flag:
# 对所有 USB 设备尝试;如果没有 USB 设备但存在已连接的 WiFi 设备,则也尝试这些 WiFi 设备
if usb_devices:
return usb_devices
return wifi
# 默认行为:如果只有一个 USB 设备则选择它;否则提示用户
if len(usb_devices) == 1:
return [usb_devices[0]]
if len(usb_devices) == 0:
# 没有 USB 设备:如果有已连接的 WiFi 设备则回退到它们(便于仅通过 WiFi 的场景),否则返回空
if wifi:
return wifi
return []
raise ValueError(
"检测到多个 USB 设备,请使用 --device 指定或者加上 --all 来对所有设备同时尝试"
)
def main():
parser = argparse.ArgumentParser(description="自动启用并连接 WiFi ADB 的工具脚本")
group = parser.add_mutually_exclusive_group()
group.add_argument("-d", "--device", help="指定要自动连接的设备ID(adb serial)")
group.add_argument(
"-a", "--all", action="store_true", help="对所有检测到的 USB 设备尝试自动连接"
)
parser.add_argument(
"--max-attempts",
type=int,
default=3,
help="每台设备尝试获取 IP 和连接的最大次数(默认3)",
)
args = parser.parse_args()
adb_exe = find_adb_executable()
if not adb_exe:
print(
"未找到 adb 可执行文件,请安装 platform-tools 或确保 adb 在 PATH 中",
file=sys.stderr,
)
sys.exit(2)
try:
targets = choose_targets(adb_exe, args.device, args.all)
except ValueError as e:
print(str(e), file=sys.stderr)
sys.exit(1)
if not targets:
print("未检测到可用于自动连接的 USB 设备(或指定的设备不在列表中)")
sys.exit(0)
print(f"即将对 {len(targets)} 台设备尝试自动连接: {targets}")
overall_ok = True
for dev in targets:
print("\n-------------------------------")
print(f"开始自动连接设备: {dev}")
ok, msg = auto_connect_wifi_adb(adb_exe, dev, max_attempts=args.max_attempts)
print(msg)
if not ok:
overall_ok = False
print(f"设备 {dev} 自动连接失败", file=sys.stderr)
else:
print(f"设备 {dev} 已成功通过 WiFi 连接")
if overall_ok:
print("\n所有设备自动连接尝试已完成,全部成功(或至少有一台成功)")
sys.exit(0)
else:
print(
"\n部分设备自动连接失败,请查看上面的错误信息或使用 --device 指定单台设备重试"
)
sys.exit(1)
if __name__ == "__main__":
main()
+7 -25
View File
@@ -623,9 +623,13 @@ function collectConfigFromUI() {
}
async function loadConfig() {
const cfg = await apiGet("/api/config");
applyConfigToUI(cfg);
appendLog(["[WEB] 配置已加载"]);
try {
const cfg = await apiGet("/api/config");
applyConfigToUI(cfg);
appendLog(["[WEB] 配置已加载"]);
} catch (e) {
appendLog(["[WEB] 配置加载失败: " + e.message]);
}
}
async function saveConfig() {
@@ -1165,28 +1169,6 @@ window.addEventListener("DOMContentLoaded", async () => {
$("btnStart").addEventListener("click", async () => { await startRun(); });
$("btnStop").addEventListener("click", async () => { await stopRun(); });
// 截图按钮
$("btnScreenshot").addEventListener("click", async () => {
const deviceId = $("device").value || "";
if (!deviceId) {
appendLog(["[截图] 请先选择设备"]);
return;
}
try {
appendLog(["[截图] 正在截图..."]);
const result = await apiPost("/api/screenshot", { device_id: deviceId });
if (result.ok) {
appendLog(["[截图] 截图成功,已保存到 pic/screenshot.png"]);
// 刷新截图显示
pollShot();
} else {
appendLog([`[截图] 截图失败: ${result.error || "未知错误"}`]);
}
} catch (e) {
appendLog([`[截图] 截图失败: ${e?.message || e}`]);
}
});
// 截图按钮
$("btnScreenshot").addEventListener("click", async () => {
const deviceId = $("device").value || "";
+68
View File
@@ -0,0 +1,68 @@
<!DOCTYPE html>
<html>
<head>
<title>Debug WebGUI</title>
</head>
<body>
<h1>Debug WebGUI Config Loading</h1>
<div id="output"></div>
<script>
const output = document.getElementById('output');
async function apiGet(path) {
const res = await fetch(path, { cache: "no-store" });
if (!res.ok) throw new Error(await res.text());
return await res.json();
}
function getConfigBoundElements() {
return Array.from(document.querySelectorAll("[data-key]"));
}
async function testConfig() {
try {
output.innerHTML += '<p>Testing API...</p>';
const cfg = await apiGet("/api/config");
output.innerHTML += `<p>Config loaded: ${Object.keys(cfg).length} keys</p>`;
// Test getConfigBoundElements
const elements = getConfigBoundElements();
output.innerHTML += `<p>Found ${elements.length} config-bound elements</p>`;
if (elements.length > 0) {
output.innerHTML += '<p>Sample elements:</p><ul>';
for (let i = 0; i < Math.min(5, elements.length); i++) {
const el = elements[i];
output.innerHTML += `<li>${el.id || el.name || 'unnamed'}: data-key="${el.dataset.key}"</li>`;
}
output.innerHTML += '</ul>';
}
// Test DEFAULTS
const DEFAULTS = {
min_prize_value_yuan: 0,
min_participants: 0,
skip_if_countdown_lt_seconds: 15,
};
output.innerHTML += '<p>Testing applyConfigToUI logic...</p>';
for (const key of Object.keys(DEFAULTS)) {
const val = cfg ? cfg[key] : undefined;
const hasVal = !(typeof val === "undefined" || val === null);
const useVal = hasVal ? val : (Object.prototype.hasOwnProperty.call(DEFAULTS, key) ? DEFAULTS[key] : undefined);
output.innerHTML += `<p>${key}: config=${val}, hasVal=${hasVal}, useVal=${useVal}</p>`;
}
} catch (e) {
output.innerHTML += `<p>Error: ${e.message}</p>`;
console.error(e);
}
}
testConfig();
</script>
</body>
</html>