ohos-devloop-pc 0.4.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.
Binary file
@@ -0,0 +1,58 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """ohos-devloop-pc —— Windows PC 操作代理(独立发行版,强烈建议而非服务器必需)。
4
+
5
+ 本包承载 PC 侧运行时:pc_service(HTTP 操作服务)、pc_ops(操作注册表)、
6
+ device_locks(设备占用登记)、rkflash(RK3568 upgrade_tool 刷机)、
7
+ dayu600_flash_setup / dayu600_skip_setup(DAYU600 设置向导)、mount_ws(W: 应急挂载)、
8
+ DeviceTest.hap(测试应用资产)。
9
+
10
+ 与服务器发行版 ohos-devloop 的关系(关键取舍 1/2,见 261127-d0m-PLAN.md):
11
+ - 本包依赖 `ohos-devloop>=0.3.1`(同 tag 同版本,`pipx install ohos-devloop-pc` 自动拉取);
12
+ - 共享模块(apply/wsroot/ui_probe/pc_mcp/flash/codespace 等)留在服务器包;
13
+ - 跨发行版互引走 sys.path 机制:本模块把 `Path(__file__).parent`(PC 兄弟目录)与已安装
14
+ ohos-devloop 的 `scripts/` 目录插入 sys.path,让 PC 模块与服务器脚本互相以扁平兄弟模块
15
+ 直 import(`import apply` / `import pc_mcp` 语义与拆分前一致);
16
+ - 未安装 ohos-devloop 时 import 本包立即抛带说明的 ImportError(绝不静默半可用)。
17
+
18
+ 每个可直接执行的 PC 模块顶部另有同一段 8 行引导(先入本目录与 pc/,再 import 本包),
19
+ 使脚本直跑(`python pc/ohos_devloop_pc/pc_service.py ...`)与包导入
20
+ (`from ohos_devloop_pc import pc_service`)两种形态都能解析 PC 兄弟与服务器 scripts 兄弟。
21
+ """
22
+ import sys
23
+ from pathlib import Path
24
+
25
+ _PC_DIR = Path(__file__).resolve().parent
26
+ if str(_PC_DIR) not in sys.path:
27
+ sys.path.insert(0, str(_PC_DIR))
28
+ try:
29
+ import ohos_devloop
30
+ except ImportError as exc:
31
+ # 源树直跑形态(python pc/ohos_devloop_pc/<script>.py):仓库根不在 sys.path 内,
32
+ # 且服务器包未以 editable 安装——经 pc/ 的仓根签名判定后补一次源树路径再试。
33
+ _repo_root = _PC_DIR.parent.parent
34
+ if (_repo_root / "ohos_devloop").is_dir() and str(_repo_root) not in sys.path:
35
+ sys.path.insert(0, str(_repo_root))
36
+ try:
37
+ import ohos_devloop
38
+ except ImportError as exc2:
39
+ raise ImportError(
40
+ "ohos-devloop-pc 需要同版本 ohos-devloop(服务器发行版)提供共享脚本模块——"
41
+ "先 `pipx install ohos-devloop`,或直接 `pipx install ohos-devloop-pc`(自动拉取)"
42
+ ) from exc2
43
+ else:
44
+ raise ImportError(
45
+ "ohos-devloop-pc 需要同版本 ohos-devloop(服务器发行版)提供共享脚本模块——"
46
+ "先 `pipx install ohos-devloop`,或直接 `pipx install ohos-devloop-pc`(自动拉取)"
47
+ ) from exc
48
+ _SCRIPTS_DIR = Path(ohos_devloop.__file__).resolve().parent / "scripts"
49
+ if str(_SCRIPTS_DIR) not in sys.path:
50
+ sys.path.insert(0, str(_SCRIPTS_DIR))
51
+
52
+ __version__ = "unknown"
53
+ try:
54
+ from importlib.metadata import version as _version
55
+
56
+ __version__ = _version("ohos-devloop-pc")
57
+ except Exception:
58
+ pass
@@ -0,0 +1,24 @@
1
+ # file generated by vcs-versioning
2
+ # don't change, don't track in version control
3
+ from __future__ import annotations
4
+
5
+ __all__ = [
6
+ "__version__",
7
+ "__version_tuple__",
8
+ "version",
9
+ "version_tuple",
10
+ "__commit_id__",
11
+ "commit_id",
12
+ ]
13
+
14
+ version: str
15
+ __version__: str
16
+ __version_tuple__: tuple[int | str, ...]
17
+ version_tuple: tuple[int | str, ...]
18
+ commit_id: str | None
19
+ __commit_id__: str | None
20
+
21
+ __version__ = version = '0.4.0'
22
+ __version_tuple__ = version_tuple = (0, 4, 0)
23
+
24
+ __commit_id__ = commit_id = 'g27f4a4537'
@@ -0,0 +1,165 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """DAYU600 自动下载、解压、烧录并跳过开机向导(本模块属独立发行版 ohos-devloop-pc)。
4
+
5
+ 用法:
6
+ ohos-devloop-pc dayu600-flash-setup --target <序列号> # 推荐(服务器 CLI 入口自动转发)
7
+ ohos-devloop dayu600-flash-setup --target <序列号> # 服务器兼容入口(安装 PC 包后转发到本模块)
8
+ ohos-devloop-pc dayu600-flash-setup --archive <tar.gz> --target <序列号>
9
+ ohos-devloop-pc dayu600-flash-setup --pac <pac> --target <序列号>
10
+ ohos-devloop-pc dayu600-flash-setup --dry-run
11
+
12
+ 流程:
13
+ 1. 未指定 --archive/--pac 时,从 CI 下载 dayu600 最新成功构建
14
+ 2. 未指定 --pac 时,解压镜像包
15
+ 3. 使用 CmdDloader 烧录 PAC,并等待 HDC 与系统 buildtime 可读
16
+ 4. 安装 Provision HAP、写入 OOBE 设置并停止开机向导
17
+ """
18
+ from __future__ import annotations
19
+
20
+ import argparse
21
+ import subprocess
22
+ import sys
23
+ import time
24
+ from pathlib import Path
25
+
26
+ # PC 发行版引导(ohos-devloop-pc):本目录与 pc/ 入 sys.path,再经 ohos_devloop_pc 注入
27
+ # 服务器 scripts 兄弟目录——脚本直跑与包导入两种形态都能解析扁平兄弟模块(见 pc/README.md)。
28
+ import sys
29
+ from pathlib import Path
30
+
31
+ _PC_DIR = Path(__file__).resolve().parent
32
+ for _cand in (str(_PC_DIR), str(_PC_DIR.parent)):
33
+ if _cand not in sys.path:
34
+ sys.path.insert(0, _cand)
35
+ import ohos_devloop_pc # noqa: E402,F401
36
+ import ohos_devloop # noqa: E402 —— 引导已保证可导入(失败即 __init__ 抛安装说明)
37
+
38
+ SCRIPT_DIR = Path(__file__).resolve().parent
39
+ # flash.py 是服务器发行版共享脚本(关键取舍 1):经 ohos_devloop 包定位,不复制进 PC 包。
40
+ FLASH_SCRIPT = Path(ohos_devloop.__file__).resolve().parent / "scripts" / "flash.py"
41
+ SKIP_SCRIPT = SCRIPT_DIR / "dayu600_skip_setup.py"
42
+
43
+
44
+ class FlowError(RuntimeError):
45
+ pass
46
+
47
+
48
+ def run_step(title: str, script: Path, args: list[str], dry_run: bool = False) -> None:
49
+ command = [sys.executable, str(script), *args]
50
+ print(f"\n== {title} ==")
51
+ print("命令: " + subprocess.list2cmdline(command))
52
+ if dry_run:
53
+ return
54
+ proc = subprocess.run(command)
55
+ if proc.returncode != 0:
56
+ raise FlowError(f"{title} 失败,退出码 {proc.returncode}")
57
+
58
+
59
+ def flash_args(args: argparse.Namespace) -> list[str]:
60
+ out = ["dayu600"]
61
+ if args.pac:
62
+ out.append(args.pac)
63
+ for flag, value in (
64
+ ("--tools-dir", args.tools_dir),
65
+ ("--port", args.port),
66
+ ("--hdc", args.hdc),
67
+ ("--hdc-target", args.target),
68
+ ):
69
+ if value:
70
+ out.extend([flag, value])
71
+ if args.manual_download:
72
+ out.append("--manual-download")
73
+ if args.no_verify:
74
+ out.append("--no-verify")
75
+ if args.no_progress:
76
+ out.append("--no-progress")
77
+ out.extend([
78
+ "--wait-sec", str(args.wait_sec),
79
+ "--flash-timeout-sec", str(args.flash_timeout_sec),
80
+ "--boot-timeout-sec", str(args.boot_timeout_sec),
81
+ ])
82
+ return out
83
+
84
+
85
+ def setup_args(args: argparse.Namespace) -> list[str]:
86
+ out = []
87
+ if args.target:
88
+ out.extend(["--target", args.target])
89
+ if args.hdc:
90
+ out.extend(["--hdc", args.hdc])
91
+ return out
92
+
93
+
94
+ def planned_steps(args: argparse.Namespace) -> list[tuple[str, Path, list[str]]]:
95
+ steps: list[tuple[str, Path, list[str]]] = []
96
+ if not args.pac:
97
+ if not args.archive:
98
+ steps.append(("下载 DAYU600 最新镜像", FLASH_SCRIPT, ["fetch", args.device]))
99
+ extract_args = ["extract"]
100
+ if args.archive:
101
+ extract_args.append(args.archive)
102
+ steps.append(("解压镜像包", FLASH_SCRIPT, extract_args))
103
+ steps.append(("烧录 PAC 并验证启动", FLASH_SCRIPT, flash_args(args)))
104
+ if args.settle_sec > 0:
105
+ steps.append(("等待系统设置服务就绪", Path("__sleep__"), [str(args.settle_sec)]))
106
+ steps.append(("写入 provision 并跳过开机向导", SKIP_SCRIPT, setup_args(args)))
107
+ return steps
108
+
109
+
110
+ def parse_args() -> argparse.Namespace:
111
+ ap = argparse.ArgumentParser(description="DAYU600 一键刷机并跳过开机向导")
112
+ ap.add_argument("--device", default="dayu600", help="CI 设备名/别名(默认 dayu600)")
113
+ ap.add_argument("--archive", default="", help="已有 tar.gz;指定后跳过下载")
114
+ ap.add_argument("--pac", default="", help="已有 .pac;指定后跳过下载和解压")
115
+ ap.add_argument("--tools-dir", default="", help="CmdDloader 工具目录")
116
+ ap.add_argument("--port", default="auto", help="auto 或 COMx")
117
+ ap.add_argument("--hdc", default="", help="hdc.exe 路径")
118
+ ap.add_argument("--target", default="", help="hdc 序列号;多设备或烧录后固定目标时使用")
119
+ ap.add_argument("--wait-sec", type=int, default=1800, help="等待 SPD 下载口秒数")
120
+ ap.add_argument("--flash-timeout-sec", type=int, default=900, help="CmdDloader 超时秒数")
121
+ ap.add_argument("--boot-timeout-sec", type=int, default=180, help="等待 HDC 启动秒数")
122
+ ap.add_argument("--settle-sec", type=int, default=10, help="烧录后等待设置服务秒数")
123
+ ap.add_argument("--manual-download", action="store_true", help="不自动 reboot autodloader")
124
+ ap.add_argument("--no-verify", action="store_true", help="跳过烧录后 buildtime 校验")
125
+ ap.add_argument("--no-progress", action="store_true", help="关闭 CmdDloader 进度条")
126
+ ap.add_argument("--dry-run", action="store_true", help="只打印完整流程")
127
+ ap.add_argument("--yes", action="store_true", help=argparse.SUPPRESS)
128
+ return ap.parse_args()
129
+
130
+
131
+ def main() -> int:
132
+ args = parse_args()
133
+ if args.settle_sec < 0:
134
+ raise FlowError("--settle-sec 不能小于 0")
135
+ if not FLASH_SCRIPT.is_file() or not SKIP_SCRIPT.is_file():
136
+ raise FlowError("仓库脚本不完整,缺少 flash.py 或 dayu600_skip_setup.py")
137
+ steps = planned_steps(args)
138
+ for title, script, step_args in steps:
139
+ if script == Path("__sleep__"):
140
+ seconds = int(step_args[0])
141
+ print(f"\n== {title} ==")
142
+ print(f"等待 {seconds}s")
143
+ if not args.dry_run:
144
+ time.sleep(seconds)
145
+ continue
146
+ run_step(title, script, step_args, args.dry_run)
147
+
148
+ if args.dry_run:
149
+ print("\nDRY-RUN 完成: 未下载、未解压、未烧录、未修改设备")
150
+ else:
151
+ print("\n完成: 镜像已烧录,设备已启动并完成开机向导跳过")
152
+ return 0
153
+
154
+
155
+ if __name__ == "__main__":
156
+ try:
157
+ sys.stdout.reconfigure(encoding="utf-8", errors="replace", line_buffering=True)
158
+ sys.stderr.reconfigure(encoding="utf-8", errors="replace", line_buffering=True)
159
+ except Exception:
160
+ pass
161
+ try:
162
+ sys.exit(main())
163
+ except FlowError as e:
164
+ print(f"ERROR: {e}", file=sys.stderr)
165
+ sys.exit(1)
@@ -0,0 +1,314 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """DAYU600 跳过开机向导。
4
+
5
+ 安装 DevLoop Provision HAP,启动 ProvisionService 写入 OOBE 完成设置,
6
+ 然后 force-stop com.ohos.startup_guide 并复核其不会立即重启。兼容文件名仍为
7
+ DeviceTest.hap。
8
+
9
+ 用法:
10
+ ohos-devloop dayu600-skip-setup --dry-run
11
+ ohos-devloop dayu600-skip-setup
12
+
13
+ 设备选择:
14
+ - 默认自动选择唯一的 Connected/Ready hdc 设备。
15
+ - 多设备时使用 --target <序列号>。
16
+ """
17
+ from __future__ import annotations
18
+
19
+ import argparse
20
+ import os
21
+ import shutil
22
+ import subprocess
23
+ import sys
24
+ import time
25
+ from pathlib import Path
26
+
27
+ # PC 发行版引导(ohos-devloop-pc):本目录与 pc/ 入 sys.path,再经 ohos_devloop_pc 注入
28
+ # 服务器 scripts 兄弟目录——脚本直跑与包导入两种形态都能解析扁平兄弟模块(见 pc/README.md)。
29
+ import sys
30
+ from pathlib import Path
31
+
32
+ _PC_DIR = Path(__file__).resolve().parent
33
+ for _cand in (str(_PC_DIR), str(_PC_DIR.parent)):
34
+ if _cand not in sys.path:
35
+ sys.path.insert(0, _cand)
36
+ import ohos_devloop_pc # noqa: E402,F401
37
+
38
+ import wsroot
39
+
40
+ PROVISION_BUNDLE = "com.example.devloopprovision"
41
+ PROVISION_ABILITY = "ProvisionService"
42
+ PROVISION_LOG_TAG = "DevLoopProvision"
43
+ PROVISION_OK = "DEVLOOP_PROVISION_OK"
44
+ PROVISION_FAILED = "DEVLOOP_PROVISION_FAILED"
45
+ DEFAULT_GUIDE_BUNDLE = "com.ohos.startup_guide"
46
+ GUIDE_STOP_SETTLE_SEC = 3.0
47
+ SCRIPT_DIR = Path(__file__).resolve().parent
48
+ BUNDLED_PROVISION_HAP = SCRIPT_DIR / "DeviceTest.hap"
49
+
50
+
51
+ class SetupError(RuntimeError):
52
+ pass
53
+
54
+
55
+ def die(msg: str) -> None:
56
+ print(f"ERROR: {msg}", file=sys.stderr)
57
+ raise SystemExit(2)
58
+
59
+
60
+ def inventory_local_value(key: str) -> str:
61
+ try:
62
+ import yaml
63
+ inv = yaml.safe_load(wsroot.inventory_path().read_text(encoding="utf-8")) or {}
64
+ value = str((inv.get("local") or {}).get(key) or "").strip()
65
+ return "" if value.startswith("<") else value
66
+ except (OSError, ImportError, ValueError):
67
+ return ""
68
+
69
+
70
+ def resolve_hdc(raw: str = "") -> str:
71
+ for value in (raw, os.environ.get("HDC", ""), inventory_local_value("hdc")):
72
+ if value:
73
+ p = Path(value).expanduser()
74
+ if p.is_file():
75
+ return str(p)
76
+ found = shutil.which("hdc") or shutil.which("hdc_std")
77
+ if found:
78
+ return found
79
+ die("未找到 hdc;用 --hdc 指定,或在 inventory local.hdc 配置")
80
+
81
+
82
+ def run_hdc(hdc: str, *args: str, timeout: int = 60) -> tuple[int, str]:
83
+ try:
84
+ p = subprocess.run(
85
+ [hdc, *args], capture_output=True, text=True, encoding="utf-8",
86
+ errors="replace", timeout=timeout)
87
+ except (OSError, subprocess.TimeoutExpired) as e:
88
+ raise SetupError(f"hdc 执行失败: {e}") from e
89
+ return p.returncode, (p.stdout or "") + (p.stderr or "")
90
+
91
+
92
+ def ready_targets(hdc: str) -> list[str]:
93
+ _, out = run_hdc(hdc, "list", "targets", "-v", timeout=20)
94
+ targets = []
95
+ for line in out.splitlines():
96
+ cols = line.split()
97
+ if not cols or cols[0].upper().startswith("COM"):
98
+ continue
99
+ if any(x in ("Connected", "Ready", "Online") for x in cols):
100
+ targets.append(cols[0])
101
+ return targets
102
+
103
+
104
+ def select_target(hdc: str, requested: str) -> str:
105
+ targets = ready_targets(hdc)
106
+ if requested:
107
+ if requested not in targets:
108
+ die(f"目标 {requested!r} 不在线;当前: {targets or '(无)'}")
109
+ return requested
110
+ if len(targets) == 1:
111
+ return targets[0]
112
+ if not targets:
113
+ die("没有在线 hdc 设备")
114
+ die(f"检测到多个 hdc 设备 {targets};请用 --target 指定")
115
+
116
+
117
+ def _resolve_hap_value(value: str, *bases: Path) -> Path | None:
118
+ p = Path(value).expanduser()
119
+ candidates = (p,) if p.is_absolute() else tuple(base / p for base in bases)
120
+ for candidate in candidates:
121
+ if candidate.is_file():
122
+ return candidate.resolve()
123
+ return None
124
+
125
+
126
+ def resolve_provision_hap(raw: str = "") -> Path | None:
127
+ """按命令行/env/inventory/包内资产查找 Provision HAP。"""
128
+ raw = raw.strip()
129
+ if raw:
130
+ found = _resolve_hap_value(raw, Path.cwd())
131
+ if found:
132
+ return found
133
+
134
+ for env_name in ("DAYU600_PROVISION_HAP", "DAYU600_DEVICE_TEST_HAP"):
135
+ env_value = os.environ.get(env_name, "").strip()
136
+ if env_value:
137
+ found = _resolve_hap_value(env_value, Path.cwd())
138
+ if found:
139
+ return found
140
+
141
+ inventory_value = inventory_local_value("device_test_hap")
142
+ if inventory_value:
143
+ found = _resolve_hap_value(inventory_value, SCRIPT_DIR, Path.cwd())
144
+ if found:
145
+ return found
146
+
147
+ if BUNDLED_PROVISION_HAP.is_file():
148
+ return BUNDLED_PROVISION_HAP
149
+ return None
150
+
151
+
152
+ # 兼容既有测试和调用方。
153
+ resolve_agent_hap = resolve_provision_hap
154
+
155
+
156
+ class Hdc:
157
+ def __init__(self, exe: str, target: str):
158
+ self.exe = exe
159
+ self.target = target
160
+
161
+ def cmd(self, *args: str, timeout: int = 60) -> str:
162
+ _, out = run_hdc(self.exe, "-t", self.target, *args, timeout=timeout)
163
+ return out.strip()
164
+
165
+ def shell(self, cmd: str, timeout: int = 60) -> str:
166
+ return self.cmd("shell", cmd, timeout=timeout)
167
+
168
+
169
+ def installed_bundles(hdc: Hdc) -> set[str]:
170
+ return {line.strip() for line in hdc.shell("bm dump -a").splitlines() if line.strip()}
171
+
172
+
173
+ def sync_device_time(hdc: Hdc) -> None:
174
+ epoch = int(time.time())
175
+ hdc.shell(f"date -s @{epoch}")
176
+ print(f"校时: @{epoch}")
177
+
178
+
179
+ def stop_bundle_process(hdc: Hdc, bundle: str) -> None:
180
+ pid = hdc.shell(f"pidof {bundle}").strip()
181
+ if pid.isdigit():
182
+ hdc.shell(f"kill {pid}")
183
+
184
+
185
+ def install_provision_hap(hdc: Hdc, hap: Path) -> None:
186
+ print(f"安装 Provision HAP: {hap}")
187
+ out = hdc.cmd("install", "-r", str(hap), timeout=180)
188
+ if PROVISION_BUNDLE not in installed_bundles(hdc):
189
+ raise SetupError(f"Provision HAP 安装失败: {out[-800:]}")
190
+
191
+ info = hdc.shell(f"bm dump -n {PROVISION_BUNDLE}")
192
+ if '"isSystemApp": true' not in info:
193
+ raise SetupError("Provision HAP 未获得 isSystemApp=true")
194
+ if '"appPrivilegeLevel": "system_basic"' not in info:
195
+ raise SetupError("Provision HAP 未获得 system_basic APL")
196
+
197
+
198
+ def wait_for_provision(hdc: Hdc, before_ok: int, before_failed: int,
199
+ timeout: int = 20) -> None:
200
+ deadline = time.time() + timeout
201
+ last_logs = ""
202
+ while time.time() < deadline:
203
+ last_logs = hdc.shell(
204
+ f"hilog -z 300 -T {PROVISION_LOG_TAG}", timeout=20)
205
+ if last_logs.count(PROVISION_FAILED) > before_failed:
206
+ raise SetupError(f"ProvisionService 写入失败:\n{last_logs[-1200:]}")
207
+ if last_logs.count(PROVISION_OK) > before_ok:
208
+ print("校验: ProvisionService 已返回 DEVLOOP_PROVISION_OK")
209
+ return
210
+ time.sleep(0.5)
211
+ raise SetupError(f"等待 ProvisionService 完成超时:\n{last_logs[-1200:]}")
212
+
213
+
214
+ def run_provision(hdc: Hdc, dry_run: bool = False) -> None:
215
+ if dry_run:
216
+ print("DRY-RUN: date -s @<host_epoch>")
217
+ print(f"DRY-RUN: install -r {BUNDLED_PROVISION_HAP.name}")
218
+ print(f"DRY-RUN: aa start -a {PROVISION_ABILITY} -b {PROVISION_BUNDLE}")
219
+ print(f"DRY-RUN: 等待 {PROVISION_OK}")
220
+ return
221
+
222
+ sync_device_time(hdc)
223
+ stop_bundle_process(hdc, PROVISION_BUNDLE)
224
+
225
+ before = hdc.shell(
226
+ f"hilog -z 300 -T {PROVISION_LOG_TAG}", timeout=20)
227
+ before_ok = before.count(PROVISION_OK)
228
+ before_failed = before.count(PROVISION_FAILED)
229
+
230
+ out = hdc.shell(
231
+ f"aa start -a {PROVISION_ABILITY} -b {PROVISION_BUNDLE}", timeout=30)
232
+ if "success" not in out.lower():
233
+ raise SetupError(f"ProvisionService 启动失败: {out[-500:]}")
234
+ wait_for_provision(hdc, before_ok, before_failed)
235
+
236
+
237
+ def stop_guide_process(hdc: Hdc, guide_bundle: str, dry_run: bool = False) -> None:
238
+ if dry_run:
239
+ print(f"DRY-RUN: aa force-stop {guide_bundle}")
240
+ print(f"DRY-RUN: 等待 {GUIDE_STOP_SETTLE_SEC:g}s,复核向导未重启")
241
+ return
242
+
243
+ # 普通 kill 后系统可能立即重新拉起向导;aa force-stop 会同时清理任务栈并
244
+ # 标记该 bundle 已停止。等待稳定期后再回读,避免把瞬时退出误判为成功。
245
+ hdc.shell(f"aa force-stop {guide_bundle}", timeout=30)
246
+ time.sleep(GUIDE_STOP_SETTLE_SEC)
247
+ pid = hdc.shell(f"pidof {guide_bundle}").strip()
248
+ if pid.isdigit():
249
+ # 兼容不支持 force-stop 的旧系统;kill 后仍以稳定期回读为准。
250
+ hdc.shell(f"kill {pid}")
251
+ time.sleep(GUIDE_STOP_SETTLE_SEC)
252
+
253
+ pid = hdc.shell(f"pidof {guide_bundle}").strip()
254
+ if pid.isdigit():
255
+ raise SetupError(f"无法停止开机向导进程: {guide_bundle} pid={pid}")
256
+
257
+
258
+ def parse_args() -> argparse.Namespace:
259
+ ap = argparse.ArgumentParser(description="DAYU600 跳过开机向导(Provision HAP)")
260
+ ap.add_argument("--target", default="", help="hdc 序列号;多设备时必填")
261
+ ap.add_argument("--hdc", default="", help="hdc.exe 路径")
262
+ ap.add_argument("--agent-hap", default="",
263
+ help="兼容参数:Provision HAP 路径;默认使用 scripts/DeviceTest.hap")
264
+ ap.add_argument("--guide-bundle", default=DEFAULT_GUIDE_BUNDLE,
265
+ help=f"开机向导包名(默认 {DEFAULT_GUIDE_BUNDLE})")
266
+ ap.add_argument("--dry-run", action="store_true", help="只打印计划,不安装或修改设备")
267
+ return ap.parse_args()
268
+
269
+
270
+ def main() -> int:
271
+ args = parse_args()
272
+ hdc_exe = resolve_hdc(args.hdc)
273
+ target = select_target(hdc_exe, args.target)
274
+ hdc = Hdc(hdc_exe, target)
275
+ guide_bundle = args.guide_bundle.strip()
276
+ if not guide_bundle or any(c not in "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789._-"
277
+ for c in guide_bundle):
278
+ die(f"非法 guide bundle: {guide_bundle!r}")
279
+
280
+ hap = resolve_provision_hap(args.agent_hap)
281
+ if hap is None:
282
+ die("未找到 Provision HAP;用 --agent-hap 指定,"
283
+ "或设置 DAYU600_PROVISION_HAP / inventory local.device_test_hap")
284
+
285
+ print(f"设备: {target}")
286
+ print(f"hdc: {hdc_exe}")
287
+ print(f"向导: {guide_bundle}")
288
+ print(f"HAP: {hap}")
289
+
290
+ if args.dry_run:
291
+ run_provision(hdc, True)
292
+ stop_guide_process(hdc, guide_bundle, True)
293
+ print("DRY-RUN 完成: 未安装 HAP、未修改设置、未停止向导")
294
+ return 0
295
+
296
+ install_provision_hap(hdc, hap)
297
+ run_provision(hdc)
298
+ stop_guide_process(hdc, guide_bundle)
299
+ hdc.shell("uinput -K -d 1 -u 1")
300
+ print("完成: DAYU600 provision 已写入,开机向导已 force-stop 且未重启")
301
+ return 0
302
+
303
+
304
+ if __name__ == "__main__":
305
+ try:
306
+ sys.stdout.reconfigure(encoding="utf-8", errors="replace", line_buffering=True)
307
+ sys.stderr.reconfigure(encoding="utf-8", errors="replace", line_buffering=True)
308
+ except Exception:
309
+ pass
310
+ try:
311
+ sys.exit(main())
312
+ except SetupError as e:
313
+ print(f"ERROR: {e}", file=sys.stderr)
314
+ sys.exit(1)