feat(rtos): 首次发布手机真机调试桥与S2探针

这个提交包含在:
sydxky 于 2026-11-14 13:25:37 +08:00 提交
当前提交 2f0f4b9702
59 个文件已更改
+4303

没有与搜索条件相匹配的文件

+4
查看文件
@@ -0,0 +1,4 @@
* text=auto eol=lf
*.png binary
*.jpg binary
*.jar binary
+16
查看文件
@@ -0,0 +1,16 @@
**/.gradle/
**/build/
**/.glyphix-work/
**/__pycache__/
**/*.local.json
**/local.properties
**/artifacts/
**/*.jks
**/*.keystore
**/*.p12
**/*.pem
**/connection.local.json
temp/
work/
downloads/
!phone-debug-bridge/gradle/wrapper/gradle-wrapper.jar
+5
查看文件
@@ -0,0 +1,5 @@
# 0.2.0(探针 1.0.4)
首次独立源码发布,PolyForm Noncommercial 1.0.0。包含手机回环认证桥、Binder 262/263 适配、PC 查询/安装/日志/作业工具、官方健康截屏、图片导入预览与校验导出、明确目标的 UI 工具及圆/方探针。
1.0.4 增加前台 wakeScreenOn 续期,修复 1.0.3 在本台 S2 的常亮失败。至少 159 秒无触摸静置及用户实体亮屏观察通过,手动计数 0→1 已截图。未取得通用真机遥控、Inspector 隧道、稳定远程前台启动或 JS console 标记。软件及设备证据见 docs/VALIDATION.md。
+131
查看文件
@@ -0,0 +1,131 @@
# PolyForm Noncommercial License 1.0.0
<https://polyformproject.org/licenses/noncommercial/1.0.0>
## Acceptance
In order to get any license under these terms, you must agree
to them as both strict obligations and conditions to all
your licenses.
## Copyright License
The licensor grants you a copyright license for the
software to do everything you might do with the software
that would otherwise infringe the licensor's copyright
in it for any permitted purpose. However, you may
only distribute the software according to [Distribution
License](#distribution-license) and make changes or new works
based on the software according to [Changes and New Works
License](#changes-and-new-works-license).
## Distribution License
The licensor grants you an additional copyright license
to distribute copies of the software. Your license
to distribute covers distributing the software with
changes and new works permitted by [Changes and New Works
License](#changes-and-new-works-license).
## Notices
You must ensure that anyone who gets a copy of any part of
the software from you also gets a copy of these terms or the
URL for them above, as well as copies of any plain-text lines
beginning with `Required Notice:` that the licensor provided
with the software. For example:
> Required Notice: Copyright Yoyodyne, Inc. (http://example.com)
## Changes and New Works License
The licensor grants you an additional copyright license to
make changes and new works based on the software for any
permitted purpose.
## Patent License
The licensor grants you a patent license for the software that
covers patent claims the licensor can license, or becomes able
to license, that you would infringe by using the software.
## Noncommercial Purposes
Any noncommercial purpose is a permitted purpose.
## Personal Uses
Personal use for research, experiment, and testing for
the benefit of public knowledge, personal study, private
entertainment, hobby projects, amateur pursuits, or religious
observance, without any anticipated commercial application,
is use for a permitted purpose.
## Noncommercial Organizations
Use by any charitable organization, educational institution,
public research organization, public safety or health
organization, environmental protection organization,
or government institution is use for a permitted purpose
regardless of the source of funding or obligations resulting
from the funding.
## Fair Use
You may have "fair use" rights for the software under the
law. These terms do not limit them.
## No Other Rights
These terms do not allow you to sublicense or transfer any of
your licenses to anyone else, or prevent the licensor from
granting licenses to anyone else. These terms do not imply
any other licenses.
## Patent Defense
If you make any written claim that the software infringes or
contributes to infringement of any patent, your patent license
for the software granted under these terms ends immediately. If
your company makes such a claim, your patent license ends
immediately for work on behalf of your company.
## Violations
The first time you are notified in writing that you have
violated any of these terms, or done anything with the software
not covered by your licenses, your licenses can nonetheless
continue if you come into full compliance with these terms,
and take practical steps to correct past violations, within
32 days of receiving notice. Otherwise, all your licenses
end immediately.
## No Liability
***As far as the law allows, the software comes as is, without
any warranty or condition, and the licensor will not be liable
to you for any damages arising out of these terms or the use
or nature of the software, under any kind of legal claim.***
## Definitions
The **licensor** is the individual or entity offering these
terms, and the **software** is the software the licensor makes
available under these terms.
**You** refers to the individual or entity agreeing to these
terms.
**Your company** is any legal entity, sole proprietorship,
or other kind of organization that you work for, plus all
organizations that have control over, are under the control of,
or are under common control with that organization. **Control**
means ownership of substantially all the assets of an entity,
or the power to direct its management and policies by vote,
contract, or otherwise. Control can be direct or indirect.
**Your licenses** are all the licenses granted to you for the
software under these terms.
**Use** means anything you do with the software requiring one
of your licenses.
+11
查看文件
@@ -0,0 +1,11 @@
# 版权、许可与参考
Required Notice: Copyright 2026 herry / sydxky (https://git2.sydxky.cn/sydxky/rtos-watch-debug-bridge)
本项目自研手机桥、PC 工具、配套探针及文档以 [PolyForm Noncommercial 1.0.0](LICENSE) 提供。允许许可条款覆盖的非商业用途、修改及分发;商业用途须另获许可。分发时保留许可全文与 Required Notice。准确权限和例外以英文许可全文为准,不将第三方原有许可改为本许可。
参考 [chengchengking/oppo-watch-s-sideload](https://github.com/chengchengking/oppo-watch-s-sideload),本地参考版本 `162fca4aa51302e18ee9802dc5269e54814c02e8`。Binder 协议和工具为本工程实现;前台亮屏续期参考其公开用法。保留上游 Copyright (c) 2026 chengchengking 及完整 [MIT 许可](third_party/oppo-watch-s-sideload-MIT.txt)。不分发其助手 APK 或反编译结果。
Gradle Wrapper 是第三方构建工具,按其原有 Apache-2.0 及随附第三方条款提供,见 [Gradle 许可全文](third_party/Gradle-LICENSE.txt)。Gradle、Android Gradle Plugin、Android SDK/JDK、Glyphix SDK/运行时各自适用其许可;除 Wrapper 外,本项目不打包这些工具。
开发图标沿用作者工作区的贪吃蛇应用资源,作为本项目探针开发资源提供。Glyphix 文档、OPPO 运动健康、设备及相关商标属于各自权利人。本项目为独立调试工具,不表示设备厂商或上游作者背书;不包含厂商 SDK、运动健康 APK、配对资料、令牌、私有签名密钥或内部 Git 历史。
+68
查看文件
@@ -0,0 +1,68 @@
{
"project": "RTOS Watch Debug Bridge",
"version": "0.2.0",
"probe": "1.0.4",
"license": "PolyForm-Noncommercial-1.0.0",
"independent_history": true,
"sensitive_findings": [],
"files": {
".gitignore": "4cbafe661a8261c06b3a7bc95405c574f07c0090697176ec04f8fb0d7bb14e7f",
"CHANGELOG.md": "de8109c1530dd0ccf1a014ee9048ae259e72f9cf04255019a1c638365374a2f9",
"LICENSE": "ffcca38841adb694b6f380647e15f17c446a4d1656fed51a1e2041d064c94cc8",
"NOTICE.md": "0eaa82a4eb8e84b7d89e1e0279815c98dc232565a914ed2f29bab6fc424bbf54",
"README.md": "a458838ca35d3a30363c1da620e9fbf5a81f5ad90a9df2b5a15a4971a8033199",
"build-rtos-game.ps1": "207ff9875af96221559f314364c932fe37bfc22c698ad1afabb9aeec40a8679e",
"com.sydxky.rtos.deviceprobe/.gitignore": "3fc9fbb6fa7795f07ed0f60fe5e3f900e17ea77a793493ef2a3ef582de5fe572",
"com.sydxky.rtos.deviceprobe/LICENSE": "ffcca38841adb694b6f380647e15f17c446a4d1656fed51a1e2041d064c94cc8",
"com.sydxky.rtos.deviceprobe/README.md": "be00b351472bdbb3566508b1c189a0e400dc3313ef16a6fe3ae4eb3eaf3230f7",
"com.sydxky.rtos.deviceprobe/build.ps1": "4a9e503fb14e0de09fa5297c37d0b68850de9463adaadfb46e9332d6625d124d",
"com.sydxky.rtos.deviceprobe/glyphix.config.js": "c7e2b3af659b18c9dc82377fd31dbb1d0f49c232bed2508e7f8ad82e7b3d216e",
"com.sydxky.rtos.deviceprobe/src/app.js": "b892392748f9b4ee66f146364676baa1bb443502b1beaeaaa9b952798c70b2e6",
"com.sydxky.rtos.deviceprobe/src/assets/icon.png": "503c979d3a45ceb0643c279e2e8d67bea67bd17b38bc4f3007094f570113967b",
"com.sydxky.rtos.deviceprobe/src/main/index.ux": "282c7ea96fb9a58ec695bd70e57f2c519218b53057611e3ecb342a86da027bc7",
"com.sydxky.rtos.deviceprobe/src/manifest.json": "338ea23d4271f1e67a8469d9f2df2343d87bbd26df648722da911a16e95bf3cc",
"com.sydxky.rtos.deviceprobe/tests/screen-lifecycle.cjs": "823c6bf1c7e7b514648bb9e2b6c2124f13ef62efcb3e7210e9fd7ce1deecc715",
"docs/ARCHITECTURE.md": "49214e342482b870fa69da4457295904d0abe199dd8f961e4d465dd9b2274904",
"docs/BUILD.md": "3f1b7050a51ab2fe129922d5ff659b4e3e05a54649b3cc59ce879b9e6fcc309c",
"docs/PRIVACY.md": "180601f2f4925dc9bfd2508d12786e0a2bf2d23ea364a7fe58791bc4d6cfc1bb",
"docs/VALIDATION.md": "f915064457ce5680ceec773100931c94a7366602d0e95864206b43c2b026c6e2",
"docs/images/S2-1.0.4-idle-baseline.jpg": "b46fd339dcee4d6ba5406c98847867a6f50f89a64f605cada383125ee6c1c13a",
"docs/images/S2-1.0.4-idle-recheck.jpg": "b46fd339dcee4d6ba5406c98847867a6f50f89a64f605cada383125ee6c1c13a",
"docs/images/S2-1.0.4-manual-tap.jpg": "4e0eacffaefef868382d8d92db2f07864090306f9b3d61114d3cbc9630783aab",
"docs/validation.json": "e57b88b1fed602f4f4e7db9fe52f61ad5c209d53ec7c9646f2356b9d557cd819",
"phone-debug-bridge/.gitignore": "0a8d360b9b497252e065ab7e2fdceb94d2735549d264a3edf112897542b5fddd",
"phone-debug-bridge/LICENSE": "ffcca38841adb694b6f380647e15f17c446a4d1656fed51a1e2041d064c94cc8",
"phone-debug-bridge/NOTICE.md": "0eaa82a4eb8e84b7d89e1e0279815c98dc232565a914ed2f29bab6fc424bbf54",
"phone-debug-bridge/README.md": "9371b82f67abbf474e14fe713367f747bbce27073258f7f9685adec169932825",
"phone-debug-bridge/app/build.gradle": "668cfef7d332c5f428ba2ff56a6dc4a1b0d0c3950bddc7b22411d5d4579364a0",
"phone-debug-bridge/app/src/main/AndroidManifest.xml": "c49aa75bd964369eb56d680cd9430a4cbc43e32cc96030276aabc352cbed130a",
"phone-debug-bridge/app/src/main/java/com/sydxky/rtos/bridge/BridgeService.java": "dd7e5246630bed70cd390219b87780298691da46b369fd4d55629d82acd46bcd",
"phone-debug-bridge/app/src/main/java/com/sydxky/rtos/bridge/Journal.java": "6e47206f897d6f9f43a174cb3b0dfd90dbc5539b81dd3213494b88446606e991",
"phone-debug-bridge/app/src/main/java/com/sydxky/rtos/bridge/LocalApi.java": "af731a7cdc91536ec78e1eeb3ddf50f0b8d5a090d2ff5323d18f14422fa7d5c7",
"phone-debug-bridge/app/src/main/java/com/sydxky/rtos/bridge/MainActivity.java": "7a3888d57a09c719cdd4316135d4c3da1ff47a273e321ac55be87b1ec086fb1a",
"phone-debug-bridge/app/src/main/java/com/sydxky/rtos/bridge/UiToolsActivity.java": "9146e1dd1d51a4af0f5ae85af57e72c255514311d4313e5fce8c22d01869f75f",
"phone-debug-bridge/app/src/main/java/com/sydxky/rtos/bridge/WearEngine.java": "36910c95e310c3e6b7e4ab27a6d0216ddeabeee3d9a351614c67668da08e4c1e",
"phone-debug-bridge/app/src/main/res/drawable/ic_bridge.xml": "f09152b6b4da93220829473cbce6bb5a8364e585d1ea899a0b16f5e28ea2bb5d",
"phone-debug-bridge/app/src/main/res/xml/data_extraction_rules.xml": "ec0f1c6431c2434ac85c7933dd0fe21c430e9601ec4db70d0112557cbebf9993",
"phone-debug-bridge/bridge.py": "b940cf000dc9619f50ac59a44fc3fa60aedee6127b25288c05114a5f1c9a599c",
"phone-debug-bridge/build.gradle": "de886547be160389c21b4d01d6584abd662e751da42d6bc10b5e7e1d12f64d0e",
"phone-debug-bridge/build.ps1": "a00ddde57bc932146f62fd307204c6babde7a5847eae0690135214f26a913471",
"phone-debug-bridge/examples/probe-inspector.json": "8385a334b15d0cbbb45b1507318ca82bc7cdaeee569abd19e1b68fb826136fb0",
"phone-debug-bridge/gradle.properties": "29602ce1e53b5477d1746258b44e370a09735415abdab1d92de86d0201456f45",
"phone-debug-bridge/gradle/wrapper/gradle-wrapper.jar": "e996d452d2645e70c01c11143ca2d3742734a28da2bf61f25c82bdc288c9e637",
"phone-debug-bridge/gradle/wrapper/gradle-wrapper.properties": "e9cedbd5a065eb2c1319cbf50f9eb38871ff957598dffa0d9cf822825a4e6287",
"phone-debug-bridge/gradlew.bat": "0e82fa239f8f4dca4efc83863c16c3b143cb6faab6f50cbefab4ee0bd03e5b5f",
"phone-debug-bridge/settings.gradle": "739bd191eff46009c1ac5b9ab73d523c544d90e36d333f3e222dcc75471efb92",
"phone-debug-bridge/tests/native_ui.py": "3f65b708a1da0a405afa2a0cb767f4af3ad2fc753e6a7cbd793eb93630cd7763",
"phone-debug-bridge/tests/test_client.py": "70ab60e2efa727f7ce351f77c0eae191a29c9bfd7946b90d5a29e3249a74adc7",
"phone-debug-bridge/tests/test_ui.py": "ec9f01413a06eb5bbd3564e9737f18d8f4c936c8a8bf73e24395a013f2e63449",
"phone-debug-bridge/tests/test_verify.py": "29facb49689a41790dad1e31284f2d8b91369cf97d6a3395ff56dc0bb6e4ed16",
"phone-debug-bridge/third_party/Gradle-LICENSE.txt": "9536d88ea948603d18e232a13f5958d67807cd80828036b082bff171d2cf0703",
"phone-debug-bridge/third_party/oppo-watch-s-sideload-MIT.txt": "be0683b824ae7ed6444427c322f6b77ee42e113ef2e88e6240e1557442fac519",
"phone-debug-bridge/ui.py": "556d108aa3ebc88debc7ac5f72d432ccc4c7f9f36a5dce6b67199516a98f26eb",
"phone-debug-bridge/verify.py": "00f172339e389c4529ca2f6a901cb5b636348d534a472e00c5e782eca3bb5ce2",
"third_party/Gradle-LICENSE.txt": "9536d88ea948603d18e232a13f5958d67807cd80828036b082bff171d2cf0703",
"third_party/oppo-watch-s-sideload-MIT.txt": "be0683b824ae7ed6444427c322f6b77ee42e113ef2e88e6240e1557442fac519",
".gitattributes": "b417160239022500ff4070f251d4701b745c5c545996c82dfdfc2b46d001df5b"
}
}
+171
查看文件
@@ -0,0 +1,171 @@
# RTOS 手表真机调试桥
通过 Android 手机上已配对的 Wear Engine 服务,让电脑安装 Glyphix 手表应用、查询设备、采集官方截图,并开展有证据的 UI 验证。适合已经拥有合法配对设备、希望反复安装和验收自己手表应用的开发者。
**源码公开 · PolyForm Noncommercial 1.0.0 · 仅限许可允许的非商业用途。** 商业用途须另获许可。完整条款见 [LICENSE](LICENSE),版权及第三方条款见 [NOTICE.md](NOTICE.md)。
当前发布:**手机桥 0.2.0 / versionCode 3**,配套探针 **1.0.4 / 10004**。这是开发测试版,APK 安装到手机;手表安装 `bundle.pkg`。已测组合为 P30PRO + OPPO Watch S2 / OWW265,其他型号和固件需自行验收。
![S2 实体手动点击后的官方截图](docs/images/S2-1.0.4-manual-tap.jpg)
上图是 S2 官方截屏导出,用户手动触摸后计数变为 1;画面中的“待实测”是每次运行的请求状态文案。本次另外完成了实体观察:无触摸静置至少 159 秒后仍亮屏。两者均不能替代通用远程输入验证。
## 下载和反馈
- [发布页:APK、探针包、源码与完整工具包](https://git2.sydxky.cn/sydxky/rtos-watch-debug-bridge/releases)
- [已有问题与建议](https://git2.sydxky.cn/sydxky/rtos-watch-debug-bridge/issues)
- [免注册提交问题与建议](https://git2.sydxky.cn/feedback/sydxky/rtos-watch-debug-bridge)
- [完整操作说明](phone-debug-bridge/README.md) · [真机验收记录](docs/VALIDATION.md) · [隐私与安全](docs/PRIVACY.md)
Git2 允许免登录浏览、克隆和下载,当前关闭注册,由所有者维护代码与发行版。
```powershell
git clone https://git2.sydxky.cn/sydxky/rtos-watch-debug-bridge.git
cd rtos-watch-debug-bridge
```
## 工作方式
```mermaid
flowchart TD
PC[电脑 bridge.py / ui.py] -->|已授权 ADB forward| APK[手机调试桥:回环认证 API]
APK -->|bindService + Binder.transact| WE[手机运动健康 Wear Engine]
WE -->|厂商配对传输| WATCH[S2 / Glyphix 应用]
PC -->|正常导航手机健康 UI| SHOT[官方手表截屏并导出]
```
RTOS 手表不需要 Android ADB。手机必须先在受支持的官方配套应用中正常配对,桥接工具不会替你完成配对,也不会绕过系统安装确认或厂商消息授权。
## 能力与实测范围
| 能力 | 当前结果 |
| --- | --- |
| 手机 APK 安装、回读 hash、Binder 绑定 | P30PRO 已通过 |
| 等待手表上线、查询型号及运行时版本 | S2 已通过;OWW265 / runtime 0.8.0-5 |
| Glyphix 应用检查、安装 | S2 探针 1.0.4 已实装,回调成功并显示实际页面 |
| 官方手表截屏 | 电脑导航健康界面并导出 480×464 JPEG,已通过 |
| 图片导入、原比例预览、安全区辅助线、PNG 导出校验 | 手机已通过 |
| 手表探针手动触摸 | 官方截图确认计数 0→1,已通过 |
| 探针内前台调试常亮 | 1.0.4 静置至少 159 秒后,截图及用户实体观察通过 |
| 手机控件树、点击、滑动和步骤报告 | 支持,作用于 Android 手机 |
| Inspector 控件检查、点击和截图 | 圆/方原生模拟器通过;真机隧道尚未打通 |
| S2 通用远程点击/滑动 | 尚未打通 |
| 远程打开手表应用到前台 | 回调 200 仍可能停在表盘,目前需手动从图标进入 |
| READY/TAP JS console、自动测试 RPC | 未通过;部分 RPC 返回 3000 |
| 消息和文件互联 | 需要匹配 appId/license,默认 test/test 不构成授权 |
`phone`、`watch-health`、`watch-import`、`inspector` 必须显式选择,避免把手机或模拟器结果误认为 S2 真机证据。
## 开始使用
准备 Windows PowerShell 7、Python 3(标准库即可)、Android platform-tools,并将 `adb` 放入 PATH。先把 P30PRO 与 S2 在运动健康中正常配对,解锁手机并让手表唤醒。
1. 从发布页下载 APK,安装到 **Android 手机**;华为手机可能需要本机点击“继续安装”。
2. 在手机开启并授权 USB 调试,运行 `adb devices -l`,确认手机序列号。也可使用自己已授权的网络 ADB;地址会变化。
3. 打开运动健康,等待手表连接。多设备环境始终指定手机 `--serial`。
4. 在仓库的 `phone-debug-bridge` 目录运行:
```powershell
$phone = 'YOUR_PHONE_SERIAL'
adb -s $phone install -r '..\downloads\RTOS-Phone-Bridge-0.2.0-debug.apk'
python bridge.py --serial $phone connect
python bridge.py --serial $phone wait-link --seconds 45
python bridge.py --serial $phone info
python ui.py --target watch-health --serial $phone screenshot --output artifacts/s2.jpg
```
将示例 APK 路径改为自己的实际下载位置。也可用 `bridge.py setup --apk <文件>` 安装并启动桥。手机上仅监听 `127.0.0.1:18765`,PC 经 `adb forward` 访问,令牌由工具通过已授权 ADB 读取,不需要手动复制。
### 安装并验证探针
解压发行版 `S2-DeviceProbe-1.0.4-dist.zip`,保留每种屏幕完整的 `bundle.pkg`、`manifest.json`、`icon.png`。S2 本轮使用圆屏配置:
```powershell
python bridge.py --serial $phone install '..\downloads\dist\generic-watch-466x466-quickapp\com.sydxky.rtos.deviceprobe\bundle.pkg'
python bridge.py --serial $phone check com.sydxky.rtos.deviceprobe
python bridge.py --serial $phone launch com.sydxky.rtos.deviceprobe
```
启动返回成功后仍需检查实际画面。若仍是表盘,请在手表图标列表打开“真机链路验证”。页面显示版本、常亮请求状态、点击次数和按钮;手动点一下再截图,核对计数变化。
1.0.4 使用 `setKeepScreenOn(true)` 配合 `wakeScreenOn({screenOn:true})` 前台 15 秒续期;隐藏/销毁停止续期并释放。它没有永久改写系统设置,不保证所有固件或系统覆盖界面下都常亮。退出探针即可结束应用内调试常亮。
### 截图和 UI 检查
`watch-health` 正常进入运动健康“设备 → 更多功能 → 手表截屏”,读取本次生成的官方公开图片;不会在失败时拿手机截图冒充手表图。手机图片检查页可通过系统文件选择器导入截图、显示圆屏安全区、导出 PNG。
```powershell
python ui.py --target phone --serial $phone tree --output artifacts/phone.tree.json
python ui.py --target phone --serial $phone screenshot --output artifacts/phone.png
python ui.py --target watch-import --serial $phone screenshot --output artifacts/imported.png
```
后两种图必须按来源解释:手机截图属于手机;任意导入图片本身不构成手表身份背书。JPEG 转 PNG 会改变字节和 SHA-256。步骤 JSON 的 `click`、`scroll`、`assert-visible`、`screenshot` 示例见 [examples](phone-debug-bridge/examples)。
## 从源码构建
仓库包含手机工程、PC 工具、探针及测试,不含厂商 SDK、Android SDK、JDK 或健康 APK。
### 手机 APK
需要 JDK 17、Android SDK Platform 35 及对应 Build Tools。工程使用 Gradle 8.13、AGP 8.13.1,minSdk 27 / targetSdk 34 / compileSdk 35。
```powershell
cd phone-debug-bridge
.\build.ps1 -JavaHome 'C:\path\to\jdk17' -AndroidSdk 'C:\path\to\Android\Sdk'
python -m unittest discover -s tests -v
```
APK 输出 `phone-debug-bridge/artifacts/RTOS-Phone-Bridge-0.2.0-debug.apk`。这是 Android Debug 签名工具,不是商店上架包;自行构建会使用自己的 debug 证书,与作者发布版可能不同。
### Glyphix 探针
自行按厂商许可取得完整 Windows Glyphix SDK,将含 `bin/gx.exe` 和 `share/` 的 SDK 放在仓库根 `temp/glyphix-v0.7.2-windows-x64/`。本次验证 CLI v0.10.1 / 3ed38835,目录名保留历史命名;不要仅凭目录名判断实际版本。
```powershell
cd com.sydxky.rtos.deviceprobe
node --test tests/screen-lifecycle.cjs
.\build.ps1 -QuickAppOnly
```
输出在 `.glyphix-work/dist/generic-watch-466x466-quickapp/` 和 `generic-watch-390x450-quickapp/`,每屏必须保留完整三个文件。这些是 Glyphix QuickApp,不是 APK 或 HAP。
原生 UI 验收需厂商模拟器和初始化的 global/launcher 镜像。先按官方教程构建普通探针镜像并初始化模拟器资源,再显式提供 `--seed`:
```powershell
python phone-debug-bridge/tests/native_ui.py --seed 'C:\path\to\initialized-image' --output work/native-ui
```
脚本拒绝占用中的 Inspector 14201,只终止自己启动的模拟器。相关资源不会随源码分发。完整路径、工具链及测试边界见[工程说明](phone-debug-bridge/README.md)。
## 发布文件
| 文件 | 内容 |
| --- | --- |
| `RTOS-Phone-Bridge-0.2.0-debug.apk` | 手机 APK,安装到 P30PRO 等 Android 手机 |
| `S2-DeviceProbe-1.0.4-dist.zip` | 圆/方各三文件,安装 bundle.pkg 到手表 |
| `RTOS-Phone-Bridge-0.2.0-source.zip` | 独立源码、构建脚本、完整许可和文档 |
| `RTOS-S2-DebugKit-0.2.0.zip` | APK、探针、源码、文档及脱敏证据 |
| `SHA256SUMS.txt` / `KIT-SHA256.txt` | 逐文件与完整工具包校验 |
APK SHA-256:`316221A6751C9ED8A23BD1FA4381F8AA35620AB1A85123468F8DD04811F880E0`。
可用 `Get-FileHash -Algorithm SHA256 <文件>` 对照发布校验表。发布附件中包含 LICENSE、NOTICE 及第三方许可,使用和再分发遵守各自条款。
## 常见问题
**Binder 已绑定但手表不在线:** 先在健康确认已连接,再执行 `wait-link`;绑定成功早于蓝牙重连。`bind_rejected` 时先正常打开已配对的健康。
**请求超时或返回 3000:** 先查同一个作业的实际结果,不要自动重复安装。已有一次会话通过保留配对数据重启健康并等待上线恢复,但内部根因尚未确定。
**安装回调成功却找不到应用:** 从图标列表检查实际入口,结合官方截图核实。回调 200 不代表远程调至前台。
**截图无法导出:** 当前适配健康 6.10.15 的公开截图目录和 JPEG 编号规则;其他版本可能需要重新适配。手机锁屏时先在本机解锁,不绕过锁屏。
**为什么没有通用手表遥控:** 当前接口没有取得可验证的真机通用触摸或 Inspector 隧道。手机 ADB 输入和模拟器自动化不会被计为 S2 遥控成功。
结束调试:先 `logs off`(若开启过),再执行 `disconnect`、`cleanup`、`stop`,并退出手表探针。清理只删除调试桥上传缓存,不删除健康配对、用户图片或其他应用数据。
## 参考与许可
参考 [Glyphix 教程](https://docs.xfaith-tech.com/glyphix/docs/tutorials/)、[亮度接口](https://docs.xfaith-tech.com/glyphix/docs/api/system-brightness.html)、[测试框架](https://docs.xfaith-tech.com/glyphix/docs/api/system-test.html) 和 [oppo-watch-s-sideload](https://github.com/chengchengking/oppo-watch-s-sideload)。本项目独立实现手机桥和 PC 工具,保留上游 MIT 署名;厂商 SDK 和第三方构建工具不受本项目自研部分许可重新授权。完整声明见 [NOTICE.md](NOTICE.md)。
+81
查看文件
@@ -0,0 +1,81 @@
param(
[Parameter(Mandatory = $true)][string]$ProjectRoot,
[switch]$QuickAppOnly,
[switch]$Clean
)
Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'
$ProjectRoot = (Resolve-Path -LiteralPath $ProjectRoot).Path
$toolBin = Join-Path $PSScriptRoot 'temp\glyphix-v0.7.2-windows-x64\bin'
$gx = Join-Path $toolBin 'gx.exe'
if (-not (Test-Path -LiteralPath $gx)) { throw "Glyphix toolchain not found: $gx" }
$manifestPath = Join-Path $ProjectRoot 'src\manifest.json'
$manifest = Get-Content -LiteralPath $manifestPath -Raw | ConvertFrom-Json
if ($manifest.package -cnotmatch '^[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*)+$') {
throw 'Invalid Glyphix package name'
}
$quickAppTargets = @('generic-watch-466x466-quickapp', 'generic-watch-390x450-quickapp')
$targets = if ($QuickAppOnly) {
$quickAppTargets
} else {
@('generic-watch-466x466', 'generic-watch-390x450', 'generic-watch-466x466-quickapp', 'generic-watch-390x450-quickapp')
}
$originalPath = $env:Path
Push-Location $ProjectRoot
try {
$env:Path = "$toolBin;$originalPath"
$availableDevices = @(& $gx list device)
if ($LASTEXITCODE -ne 0) { throw 'Unable to read Glyphix device profiles' }
foreach ($device in $targets) {
if ($availableDevices -cnotcontains $device) { throw "Missing Glyphix device profile: $device" }
}
if ($Clean) {
& $gx clean
if ($LASTEXITCODE -ne 0) { throw 'Glyphix clean failed' }
}
foreach ($device in $targets) {
$arguments = @('build', '-d', $device)
if (-not $device.Contains('quickapp')) { $arguments += '-e' }
$output = @(& $gx @arguments 2>&1 | ForEach-Object { $_.ToString() })
$output | ForEach-Object { Write-Host $_ }
if ($LASTEXITCODE -ne 0 -or ($output -join "`n") -match '(?im)^\s*(?:error|fatal):\s') {
throw "Glyphix build failed for $device"
}
}
foreach ($device in $quickAppTargets) {
$deliveryRoot = Join-Path $ProjectRoot ".glyphix-work\dist\$device\$($manifest.package)"
foreach ($fileName in @('bundle.pkg', 'manifest.json', 'icon.png')) {
$artifact = Join-Path $deliveryRoot $fileName
if (-not (Test-Path -LiteralPath $artifact -PathType Leaf) -or (Get-Item -LiteralPath $artifact).Length -eq 0) {
throw "Missing or empty QuickApp artifact: $artifact"
}
}
$packedManifest = Get-Content -LiteralPath (Join-Path $deliveryRoot 'manifest.json') -Raw | ConvertFrom-Json
if ($packedManifest.package -cne $manifest.package -or
$packedManifest.versionName -cne $manifest.versionName -or
$packedManifest.versionCode -ne $manifest.versionCode) {
throw "QuickApp package/version mismatch: $device"
}
$icon = [IO.File]::ReadAllBytes((Join-Path $deliveryRoot 'icon.png'))
if ($icon.Length -lt 8 -or [Convert]::ToHexString($icon[0..7]) -cne '89504E470D0A1A0A') {
throw "Invalid QuickApp PNG icon: $device"
}
foreach ($fileName in @('bundle.pkg', 'manifest.json', 'icon.png')) {
$artifact = Join-Path $deliveryRoot $fileName
[pscustomobject]@{
Package = $manifest.package
Device = $device
File = $fileName
Bytes = (Get-Item -LiteralPath $artifact).Length
SHA256 = (Get-FileHash -LiteralPath $artifact -Algorithm SHA256).Hash
}
}
}
} finally {
Pop-Location
$env:Path = $originalPath
}
+1
查看文件
@@ -0,0 +1 @@
.glyphix-work/
+131
查看文件
@@ -0,0 +1,131 @@
# PolyForm Noncommercial License 1.0.0
<https://polyformproject.org/licenses/noncommercial/1.0.0>
## Acceptance
In order to get any license under these terms, you must agree
to them as both strict obligations and conditions to all
your licenses.
## Copyright License
The licensor grants you a copyright license for the
software to do everything you might do with the software
that would otherwise infringe the licensor's copyright
in it for any permitted purpose. However, you may
only distribute the software according to [Distribution
License](#distribution-license) and make changes or new works
based on the software according to [Changes and New Works
License](#changes-and-new-works-license).
## Distribution License
The licensor grants you an additional copyright license
to distribute copies of the software. Your license
to distribute covers distributing the software with
changes and new works permitted by [Changes and New Works
License](#changes-and-new-works-license).
## Notices
You must ensure that anyone who gets a copy of any part of
the software from you also gets a copy of these terms or the
URL for them above, as well as copies of any plain-text lines
beginning with `Required Notice:` that the licensor provided
with the software. For example:
> Required Notice: Copyright Yoyodyne, Inc. (http://example.com)
## Changes and New Works License
The licensor grants you an additional copyright license to
make changes and new works based on the software for any
permitted purpose.
## Patent License
The licensor grants you a patent license for the software that
covers patent claims the licensor can license, or becomes able
to license, that you would infringe by using the software.
## Noncommercial Purposes
Any noncommercial purpose is a permitted purpose.
## Personal Uses
Personal use for research, experiment, and testing for
the benefit of public knowledge, personal study, private
entertainment, hobby projects, amateur pursuits, or religious
observance, without any anticipated commercial application,
is use for a permitted purpose.
## Noncommercial Organizations
Use by any charitable organization, educational institution,
public research organization, public safety or health
organization, environmental protection organization,
or government institution is use for a permitted purpose
regardless of the source of funding or obligations resulting
from the funding.
## Fair Use
You may have "fair use" rights for the software under the
law. These terms do not limit them.
## No Other Rights
These terms do not allow you to sublicense or transfer any of
your licenses to anyone else, or prevent the licensor from
granting licenses to anyone else. These terms do not imply
any other licenses.
## Patent Defense
If you make any written claim that the software infringes or
contributes to infringement of any patent, your patent license
for the software granted under these terms ends immediately. If
your company makes such a claim, your patent license ends
immediately for work on behalf of your company.
## Violations
The first time you are notified in writing that you have
violated any of these terms, or done anything with the software
not covered by your licenses, your licenses can nonetheless
continue if you come into full compliance with these terms,
and take practical steps to correct past violations, within
32 days of receiving notice. Otherwise, all your licenses
end immediately.
## No Liability
***As far as the law allows, the software comes as is, without
any warranty or condition, and the licensor will not be liable
to you for any damages arising out of these terms or the use
or nature of the software, under any kind of legal claim.***
## Definitions
The **licensor** is the individual or entity offering these
terms, and the **software** is the software the licensor makes
available under these terms.
**You** refers to the individual or entity agreeing to these
terms.
**Your company** is any legal entity, sole proprietorship,
or other kind of organization that you work for, plus all
organizations that have control over, are under the control of,
or are under common control with that organization. **Control**
means ownership of substantially all the assets of an entity,
or the power to direct its management and policies by vote,
contract, or otherwise. Control can be direct or indirect.
**Your licenses** are all the licenses granted to you for the
software under these terms.
**Use** means anything you do with the software requiring one
of your licenses.
+20
查看文件
@@ -0,0 +1,20 @@
# 真机链路验证
自研部分采用 [PolyForm Noncommercial 1.0.0](LICENSE),仅限许可允许的非商业用途;版权、Required Notice 和第三方声明见[手机桥 NOTICE](../phone-debug-bridge/NOTICE.md)。
独立 Glyphix 应用 `com.sydxky.rtos.deviceprobe`,版本 1.0.4 / 10004。供 [手机调试桥](../phone-debug-bridge/README.md) 测试安装、启动、手动点击和应用内调试常亮,保留 `icon` 清单字段。
```powershell
.\build.ps1 -QuickAppOnly
node --test tests/screen-lifecycle.cjs
```
沿用 RTOS 固定厂商 `gx.exe`,生成圆 / 方两种 QuickApp 包。页面初始化输出 `RTOS_DEVICE_PROBE_READY_V1`,点击按钮增加次数并输出 `RTOS_DEVICE_PROBE_TAP_V1=<次数>`。无网络、账号和后台订阅;前台常亮只维护一个 15 秒定时器。`READY` 日志只证明执行到页面就绪阶段,屏幕和点击须另行观察。
1.0.3 仅调用 `@system.brightness.setKeepScreenOn(true)`,在 S2 上静置至少 79 秒后回到表盘,用户确认已熄屏,常亮实测失败。1.0.4 增加官方 `wakeScreenOn({ screenOn: true })`,省略 timeout(文档定义为不限时间),每 15 秒续期。隐藏/销毁均清理定时器、使旧回调失效并释放 setKeepScreenOn(false);亮屏调用缺失、抛错或拒绝时停止续期。不会修改亮度或自动亮度,不在后台续期。
2026-11-14,1.0.4 已在 S2 / OWW265 实装。用户取下充电座并打开后,起始采集结束 13:01:35,复查请求始于 13:04:14,结束 13:04:25(Asia/Shanghai),保守静置至少 159 秒;截图仍为探针,用户确认实体屏幕仍亮着。随后用户手动点击,截图确认次数由 0 变成 1。该结果只覆盖本固件上的短时前台调试常亮及手动触摸;不是永久系统常亮或电脑远程输入。页面保留“常亮续期中 · 待实测”,因为每次新会话仍需观察实际结果。
1.0.4 的圆/方 QuickApp 构建、两种原生模拟器 UI 和 5 项生命周期回归通过。真机 READY/TAP 日志与 Inspector 隧道尚未取得。来源:[官方亮度接口](https://docs.xfaith-tech.com/glyphix/docs/api/system-brightness.html);完整证据见[补测记录](../docs/VALIDATION.md)。退出探针可结束调试常亮。
图标暂沿用本仓库贪吃蛇应用的本地资源,仅供开发验证。实际设备状态见手机桥的验收记录。
+2
查看文件
@@ -0,0 +1,2 @@
param([switch]$QuickAppOnly, [switch]$Clean)
& (Join-Path $PSScriptRoot '..\build-rtos-game.ps1') -ProjectRoot $PSScriptRoot -QuickAppOnly:$QuickAppOnly -Clean:$Clean
@@ -0,0 +1 @@
module.exports = { minify: false };
+6
查看文件
@@ -0,0 +1,6 @@
export default {
onCreate() { console.log('RTOS_DEVICE_PROBE_APP_CREATE_V1'); },
onShow() { console.log('RTOS_DEVICE_PROBE_APP_SHOW_V1'); },
onHide() { console.log('RTOS_DEVICE_PROBE_APP_HIDE_V1'); },
onDestroy() { console.log('RTOS_DEVICE_PROBE_APP_DESTROY_V1'); }
};
二进制文件未显示。

之后

宽度:  |  高度:  |  大小: 2.1 KiB

@@ -0,0 +1,70 @@
<template>
<div class="page">
<p class="title">真机链路验证</p>
<p class="status">手机桥接 · S2 · 1.0.4</p>
<p class="body">{{ screenStatus }}</p>
<p class="body">点击次数:{{ count }}</p>
<button on:click="tap">点击验证</button>
</div>
</template>
<style>
.page { width: 100%; height: 100%; background-color: #102338; align-items: center; justify-content: center; flex-direction: column; padding: 48px 42px; }
.title { color: #ffffff; font-size: 1.15rem; margin-bottom: 12px; }
.status { color: #83ddd4; font-size: 0.8rem; margin-bottom: 20px; }
.body { color: #e1e9f2; font-size: 0.8rem; margin-bottom: 12px; }
button { width: 220px; height: 60px; margin-top: 12px; font-size: 0.8rem; }
</style>
<script>
export default {
data: { count: 0, screenStatus: '页面已就绪' },
screenEpoch: 0,
screenActive: false,
wakeTimer: null,
onReady() { console.log('RTOS_DEVICE_PROBE_READY_V1'); },
onShow() { this.keepScreen(true); },
onHide() { this.keepScreen(false); },
onDestroy() { this.keepScreen(false); },
keepScreen(on) {
if (on && this.screenActive) return;
this.screenActive = on;
const epoch = ++this.screenEpoch;
if (this.wakeTimer !== null) { clearInterval(this.wakeTimer); this.wakeTimer = null; }
try {
const brightness = require('@system.brightness').default;
const result = brightness.setKeepScreenOn(on);
this.screenStatus = on ? '常亮待实测' : '已释放常亮';
Promise.resolve(result).catch(() => {
if (epoch === this.screenEpoch) this.screenStatus = '当前固件未接受常亮';
});
if (on) {
if (typeof brightness.wakeScreenOn !== 'function') {
this.screenStatus = '固件缺少亮屏接口';
return;
}
if (!this.wakeScreen(brightness, epoch)) return;
this.wakeTimer = setInterval(() => this.wakeScreen(brightness, epoch), 15000);
}
} catch (error) { this.screenStatus = '当前固件不支持常亮'; }
},
wakeScreen(brightness, epoch) {
if (!this.screenActive || epoch !== this.screenEpoch) return false;
try {
// The official API documents an omitted timeout as unlimited.
const result = brightness.wakeScreenOn({ screenOn: true });
this.screenStatus = '常亮续期中 · 待实测';
Promise.resolve(result).catch(() => {
if (this.screenActive && epoch === this.screenEpoch) {
if (this.wakeTimer !== null) { clearInterval(this.wakeTimer); this.wakeTimer = null; }
this.screenStatus = '固件未接受亮屏';
}
});
return true;
} catch (error) {
if (this.wakeTimer !== null) { clearInterval(this.wakeTimer); this.wakeTimer = null; }
this.screenStatus = '亮屏调用失败';
return false;
}
},
tap() { this.count += 1; console.log('RTOS_DEVICE_PROBE_TAP_V1=' + this.count); }
};
</script>
@@ -0,0 +1,10 @@
{
"package": "com.sydxky.rtos.deviceprobe",
"name": "真机链路验证",
"icon": "/assets/icon.png",
"versionName": "1.0.4",
"versionCode": 10004,
"features": [],
"router": { "entry": "main", "pages": { "main": { "component": "index" } } },
"config": { "designWidth": 410 }
}
@@ -0,0 +1,85 @@
const { test } = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const vm = require('node:vm');
const path = require('node:path');
function load(brightness) {
const source = fs.readFileSync(path.join(__dirname, '../src/main/index.ux'), 'utf8')
.match(/<script>([\s\S]*?)<\/script>/)[1].replace('export default', 'module.exports =');
const active = new Map();
const callbacks = [];
let next = 0;
const context = { module: { exports: {} }, Promise, console,
require: () => ({ default: brightness }),
setInterval(fn) { callbacks.push(fn); active.set(++next, fn); return next; },
clearInterval(id) { active.delete(id); } };
vm.runInNewContext(source, context);
const page = context.module.exports;
Object.assign(page, page.data);
return { page, active, callbacks };
}
test('repeated shows own one renewal; hide and destroy prevent queued wakeups', () => {
const calls = [];
const { page, active, callbacks } = load({
setKeepScreenOn: value => calls.push(['keep', value]),
wakeScreenOn: value => calls.push(['wake', value.screenOn]) });
page.onShow(); page.onShow();
assert.equal(active.size, 1);
assert.deepEqual(calls, [['keep', true], ['wake', true]]);
callbacks[0]();
page.onHide();
assert.equal(active.size, 0);
const afterHide = calls.length;
callbacks[0]();
assert.equal(calls.length, afterHide);
page.onShow();
assert.equal(active.size, 1);
page.onDestroy();
assert.equal(active.size, 0);
const afterDestroy = calls.length;
for (const callback of callbacks) callback();
assert.equal(calls.length, afterDestroy);
assert.deepEqual(calls.at(-1), ['keep', false]);
});
test('destroy releases a visible page even without hide', () => {
const calls = [];
const { page, active } = load({ setKeepScreenOn: value => calls.push(value), wakeScreenOn() {} });
page.onShow(); page.onDestroy();
assert.deepEqual(calls, [true, false]);
assert.equal(active.size, 0);
});
test('late rejection cannot overwrite the new visible generation', async () => {
let rejectOld;
let first = true;
const { page } = load({ setKeepScreenOn() {}, wakeScreenOn() {
if (first) { first = false; return new Promise((_, reject) => { rejectOld = reject; }); }
} });
page.onShow(); page.onHide(); page.onShow();
const status = page.screenStatus;
rejectOld(new Error('old request'));
await Promise.resolve(); await Promise.resolve();
assert.equal(page.screenStatus, status);
page.onDestroy();
});
test('a missing wake API is reported and does not start renewal', () => {
const { page, active } = load({ setKeepScreenOn() {} });
page.onShow();
assert.equal(active.size, 0);
assert.equal(page.screenStatus, '固件缺少亮屏接口');
page.onDestroy();
});
test('a rejected wake stops renewal and remains visible as a failure', async () => {
const { page, active } = load({ setKeepScreenOn() {},
wakeScreenOn: () => Promise.reject(new Error('unsupported')) });
page.onShow();
await Promise.resolve(); await Promise.resolve();
assert.equal(active.size, 0);
assert.equal(page.screenStatus, '固件未接受亮屏');
page.onDestroy();
});
+29
查看文件
@@ -0,0 +1,29 @@
# 电脑通过手机调试 S2 真机
入口工程:[phone-debug-bridge](../phone-debug-bridge/README.md)。它是安装到 Android 手机的调试 APK,包名 `com.sydxky.rtos.bridge`;RTOS 手表应用仍使用 Glyphix `bundle.pkg`。
## 2026-11-14 更新
后续“尝试打通”补测:保留配对数据重启健康并等待重连后,取得 **OWW265 / runtime 0.8.0-5 / nucleus 0.8.0-229 / 手表 MAS 2006005**。0.2.0 APK 的安装/检查/启动请求恢复成功。探针 1.0.3 只请求 setKeepScreenOn,静置实测失败;1.0.4 增加 wakeScreenOn 前台 15 秒续期后,静置至少 159 秒仍显示探针,用户确认实体屏幕仍亮。手动点击后的官方截图显示计数 0→1。远程 launch 后仍可能停在表盘,前台调起、READY/TAP 日志、通用远程输入与真机 Inspector 尚未通过;常亮只证明本次短时前台调试。详情见[补测记录](../docs/VALIDATION.md)。电脑新增 `wait-link`,避免把 Binder 刚绑定误作手表已经连上。
后续实测使用已授权网络 ADB `YOUR_PHONE_SERIAL`(已核验为同一 P30PRO),可替换示例 USB 序列号;先用 `adb devices -l` 确认当前目标,地址可能变化。退出探针释放调试常亮。源码、圆/方构建、5 项常亮生命周期回归、模拟器 UI、实体手动触摸和实体短时亮屏分别记录。
工程已升级为 **0.2.0 / 3**,提供 APK 图片预览与圆屏安全区检查,以及电脑 `ui.py` 的截图、控件检查、点击、滑动和步骤报告。目标必须显式选择 `phone`、`watch-health`、`watch-import` 或 `inspector`;具体支持范围见工程 README。圆/方原生模拟器已验证 Inspector 截图、文字断言、按钮点击和步骤报告;S2 通用操控与 Inspector 隧道尚未确认。
**0.2.0 / 3 已实际安装到 P30PRO**,回读 APK SHA-256 与交付包一致;手机新界面的 SAF 导入、预览、安全区辅助线和电脑 PNG 导出通过。电脑已能自动导航官方健康界面并导出 S2 的 480×464 JPEG 表盘截图。该分辨率与 JPEG 格式来自实际公开文件,脚本支持健康添加的同名编号。
此前 0.1.1 已通过电脑认证回环接口绑定 `com.heytap.health`,检测到 Wear Engine **2006006 / 263**,手表连接查询为 true;厂商设备信息、日志开关、探针安装和启动返回成功。设备信息内容为空,探针 READY 日志、探针页面和点击仍需各自证据。最终范围见 [本轮记录](VALIDATION.md)。
修复安装目的路径为 `remote://mass/...pkg`,解决此前只传文件名导致的 `4008 rename remote file failed`;263 的信息、检查、启动和连接订阅使用手机包名,安装使用 appId。P30PRO 遇到 `bind_rejected` 时先打开已配对的运动健康,再重新连接;不修改 `authentication_state` 或配对数据。
后续从 `phone-debug-bridge` 运行 `bridge.py --serial YOUR_PHONE_SERIAL setup`、`connect`、`link`;安装/启动、日志命令和 `verify.py` 详见工程 README。手机 APK 是 Android Debug 签名的本地开发工具,未作为上架包发布。
## 2026-11-13 历史检查
用户于 2026-11-13 表示:P30PRO 已在运动健康配对 S2。电脑 ADB 当前确认手机为 `YOUR_PHONE_SERIAL` / `VOG-AL00` / Android API 29。发现 `com.heytap.health` 中的 `com.glyphix.mas.service.WearEngineService`,Action `com.xfaith.glyphix.WEAR_ENGINE_ACTION`,exported=true、无绑定权限要求。开始检查时健康版本为 6.9.37(6093700);结束前再次查询已为 `6.10.15_9e2a81e_261107`(6101500),后续测试须以手机当时实际版本为准。
电脑调用 Python CLI → USB ADB 端口转发 → 手机回环认证 API → bindService / Binder → 运动健康负责传输 → S2。无需给 RTOS 手表打开 Android ADB。
手机工程提供服务发现、262 / 263 协议选择、设备信息、应用检查 / 安装 / 启动、消息 / 文件、RPC 日志和异步作业查询。另有独立 [deviceprobe](../com.sydxky.rtos.deviceprobe/README.md) 用于验证链路。最短复现命令、构建工具、接口边界和后续验收都在手机工程 README;实际通过与未通过项见 [验收记录](VALIDATION.md)。
注意区分:用户已配对、电脑已识别手机、手机 Binder 已绑定、手表在线、包安装成功、页面运行、人工触摸与显示,以及平台上架,分别需要各自证据。参考仓库针对 Watch S / OWW262 的成功记录不替代 S2 结果。
+18
查看文件
@@ -0,0 +1,18 @@
# 独立公开源码验证
2026-11-14,Windows / PowerShell 7。仅本仓库的源码参与构建,JDK、Android SDK、Glyphix SDK 和模拟器 global/launcher 均从本机已授权工具位置提供,不纳入仓库或源码包。
| 检查 | 结果 |
| --- | --- |
| Python 标准库回归 | 20/20 通过 |
| Node 常亮生命周期 | 5/5 通过 |
| Android assembleDebug + lintDebug | 成功,0 errors / 9 warnings |
| 圆 / 方 QuickApp | 两种构建成功,完整六文件 |
| 圆 / 方原生模拟器 UI | 文字断言、按钮点击、截图及步骤计划通过 |
| 源码敏感扫描 | 未发现真实令牌、私钥、设备序列号、私有目录或内部 Git URL |
独立目录重新构建的 APK SHA-256 为 `1128A0AD6B9EF351C00450C92228CD2A4AF19D2538DB1BDAFD4B0C854EBE440F`。与发行附件 `316221A6751C9ED8A23BD1FA4381F8AA35620AB1A85123468F8DD04811F880E0` 的所有 ZIP 条目内容逐项一致,但完整归档字节不相同。本项目不声称 APK 字节可复现。发行附件沿用已在 P30PRO 实装并回读核验的原始 APK,自行构建也会受本机 debug 签名材料影响。
探针圆屏 bundle.pkg SHA-256:`7E4A2F507CE20290AE05DE32A1AEAF6423E8145A165DA52D658E0E8FCB44E5F3`;方屏:`3D12F4BA7218C9B7140731ED484C8DC7EF625FFE4AC28114DB276690A01A9BE4`。公开源码构建结果与本次 S2 实装的圆屏包一致。
S2 的实体亮屏和手动触摸证据另见 [真机记录](VALIDATION.md),不能用模拟器或构建通过替代。
+11
查看文件
@@ -0,0 +1,11 @@
# 隐私与调试安全
手机桥不连接本项目的云端服务,仅在手机回环地址 127.0.0.1:18765 提供 API,经已授权 ADB forward 供电脑使用。使用随机 256 位 Bearer 令牌,拒绝浏览器 Origin,不开放 CORS。令牌由 PC 工具通过已授权 ADB 的 run-as 读取,不写入 PC 配置或验收报告。
APK 无存储、蓝牙、位置、麦克风或无障碍权限。安装包通过应用私有上传目录传入,跨进程仅交付只读文件描述符;图片通过 Android 系统选择器导入。官方手表截图仍由运动健康负责,可能保存在它自己的公开图片目录。使用网络 ADB 时由用户负责其原有授权和网络环境,桥 API 不改为监听 Wi-Fi 地址。
事件和作业只在手机进程内有界保存,可能包含被调试应用主动输出的业务内容。分享日志前应检查;verify.py 只输出设备白名单和探针标记,不输出 MAC、UUID、vendorId、license 或 Bearer。上传缓存最多 4 个文件 / 64 MiB,单文件最多 32 MiB。
默认 test/test 仅为演示占位值,不是厂商授权凭据。实际互联应使用自己的 appId/license,本地连接文件匹配 *.local.json 并已被 Git 忽略。不要提交或公开该文件、令牌、日志中的个人资料、签名密钥或手机配对数据。
结束时关闭已开启的日志、disconnect、cleanup、stop,并退出探针以释放前台常亮。cleanup 只删除本桥上传缓存,不删除健康配对或用户截图。Debug APK 的 run-as 能力和回环 API 用于开发测试,发行版不是生产后台服务或商店版本。
+57
查看文件
@@ -0,0 +1,57 @@
# S2 真机链路补测与常亮探针
日期:2026-11-14,Asia/Shanghai。手机 APK 保持 **0.2.0 / 3**;手表探针为 **1.0.4 / 10004**。当前已通过真机设备信息、安装、官方截屏、探针页面、手动触摸,以及本固件上至少 159 秒的前台静置常亮。通用远程输入和真机 Inspector 尚未通过。原始失败报告保留。
## 真机链路与设备
保留配对数据重启运动健康、正常打开并等待 connected=true 后,设备信息、应用检查、日志开关、探针安装及启动请求恢复 code 200。Binder bound 早于手表在线;`wait-link --seconds 45` 只轮询在线查询,不重放安装或写入 RPC。尚不能断言所有 `3000 svc exec failed` 都能由此解决。
实际设备信息放在回调 **msg 的 JSON 字符串**中,values 为空;已修复白名单解析并增加脱敏回归。设备报告 OPPO / **OWW265**,nucleus **0.8.0-229**,runtime **0.8.0-5**,手表 MAS **2006005**;手机 SDK **2006006 / 263** 是手机接口版本。报告不保留 MAC、UUID、vendorId 或原始健康业务日志。
P30PRO 为 VOG-AL00 / API29,运动健康 6.10.15。USB 离线后,通过核验为同一手机的已授权网络 ADB `YOUR_PHONE_SERIAL` 完成后续操作。其他 OWW261 ADB 设备不属于本链路。地址可能变化,先查询 `adb devices -l`,按当前手机地址替换示例。手机调试 API 仍仅监听回环地址。
## 常亮:失败记录与修复结果
1.0.3 只调用 `@system.brightness.setKeepScreenOn(true)`。离开充电座、用户重新打开后取得起始探针图;至少 79 秒后复查已回到表盘,用户明确回复“已熄屏”。因此该版本常亮实测失败,不能继续写作仅充电遮挡或待验证。
1.0.4 增加 `wakeScreenOn({ screenOn: true })`,按官方文档省略 timeout 表示不限时间,并在前台每 15 秒续期。隐藏/销毁均清理定时器、使旧回调失效并释放 setKeepScreenOn(false);没有在后台持续唤醒,也没有修改亮度、自动亮度或永久系统设置。参考了官方接口及用户指定仓库的前台续期用法;Watch S 的参考结果不替代 S2 实测。
| 1.0.4 实测 | 结果 |
| --- | --- |
| 用户状态 | 已取下充电座,打开探针后不触摸 |
| 起始截图采集完成 | 13:01:35,探针 1.0.4,次数 0 |
| 复查请求 / 完成 | 13:04:14 / 13:04:25,保守静置至少 159 秒 |
| 复查画面 | 仍显示探针 1.0.4、“常亮续期中 · 待实测”、次数 0 |
| 实体屏幕观察 | 用户回复“仍亮着,显示探针” |
| 手动触摸 | 用户在 S2 点一次按钮;随后官方截图确认次数 0→1 |
静置前后画面相同,JPEG SHA-256 均为 `B46FD339DCEE4D6BA5406C98847867A6F50F89A64F605CADA383125EE6C1C13A`;手动点击后为 `4E0EACFFAEFEF868382D8D92DB2F07864090306F9B3D61114D3CBC9630783AAB`。图片均为官方健康截屏流程导出的 480×464 JPEG。交付证据含前后采集记录、1.0.3 失败记录、实体观察回复及手动点击图。截图单独不能证明 OLED 通电,亮屏结论同时依据用户现场观察。
验收范围为这台 S2、当前固件的短时前台调试常亮,尚未测试长时间续航或全部系统策略。页面保留“待实测”文案,因为每次新设备/会话仍需观察。退出探针可释放调试常亮。P30PRO 原有 stay_on_while_plugged_in=3 已保留。
来源:[Glyphix 亮度管理](https://docs.xfaith-tech.com/glyphix/docs/api/system-brightness.html)、[用户指定参考仓库](https://github.com/chengchengking/oppo-watch-s-sideload/tree/main)(本地快照 `162fca4aa51302e18ee9802dc5269e54814c02e8`,本轮未刷新)。
## 仍未打通的能力
用户从图标打开的探针 1.0.0 和 1.0.4 均有真实页面证据。多次远程 launch 返回 200 后截屏仍为表盘,故远程前台启动尚未确认。当前手动触摸成功不能证明 PC 触摸注入;通用 S2 点击/滑动、Inspector 隧道和 JS console READY/TAP 仍未通过。
`auto_test_start` / `auto_test_stop` 最小脚本均最终返回 **3000 svc exec failed**。之后一次安装在 0 字节进度后失败,重启健康并等待重连后安装恢复。这是观察到的恢复路径,SDK 内部根因尚未确定。
临时 1.0.1/1.0.2 网络探针没有收到电脑服务请求,未作为成功通道,最终源码已移除该通道。未修改认证状态、冒充健康、替换桌面槽位或清理配对数据。
## 软件验证与后续使用
20 项 Python 测试通过;1.0.4 的 5 项生命周期 Node 测试通过,覆盖定时器唯一性、隐藏/销毁释放、旧 Promise 隔离、缺少接口和亮屏拒绝停止续期。圆/方 QuickApp 构建与两种原生模拟器 UI 通过。模拟器控件自动点击独立于 S2 手动触摸证据。本轮未修改 Android 源码或 APK,沿用已实装并回读核验的 0.2.0 包。
从 phone-debug-bridge 目录运行(按 `adb devices -l` 选择同一手机):
```powershell
python bridge.py --serial YOUR_PHONE_SERIAL connect
python bridge.py --serial YOUR_PHONE_SERIAL wait-link --seconds 45
python bridge.py --serial YOUR_PHONE_SERIAL info
python ui.py --target watch-health --serial YOUR_PHONE_SERIAL screenshot --output artifacts/s2.jpg
```
若服务持续 3000,先查看已有作业结果;可保留配对数据重启健康,等待重连再单次验证。重启健康会短暂中断同步。不要把未确认支持的 RPC 放入自动循环。
RPC 日志此前已成功关闭,本轮未重新开启;上传缓存已清理。临时电脑网络服务及 18766 反向转发已移除,手机桥与 18765 正向转发保留供后续调试。结束时执行 `bridge.py --serial <当前手机> disconnect`、`cleanup`、`stop`;退出手表探针结束应用常亮。未发布应用商店或生产服务;独立源码及附件发布另见本仓库发行版。
二进制文件未显示。

之后

宽度:  |  高度:  |  大小: 20 KiB

二进制文件未显示。

之后

宽度:  |  高度:  |  大小: 20 KiB

二进制文件未显示。

之后

宽度:  |  高度:  |  大小: 20 KiB

+138
查看文件
@@ -0,0 +1,138 @@
{
"time": "2026-11-14T13:19:25.716596+08:00",
"phone": {
"model": "VOG-AL00",
"androidApi": 29,
"bridgeVersion": "0.2.0",
"installed_apk_sha256": "316221a6751c9ed8a23bd1fa4381f8aa35620ab1a85123468f8dd04811f880e0",
"stay_on_while_plugged_in": 3,
"setting_preserved": true
},
"wear_engine": {
"bound": true,
"protocol": 263,
"phoneMasVersion": 2006006,
"connected": true
},
"watch": {
"brand": "OPPO",
"model": "OWW265",
"runtimeVersion": "0.8.0-5",
"nucleusVersion": "0.8.0-229",
"masVersion": 2006005
},
"recovery": {
"paired_health_process_restarted": true,
"pairing_data_preserved": true,
"waited_for_actual_link": true,
"info_callback_success": true,
"logs_on_callback_success": true,
"logs_off_callback_success": true,
"probe_check_callback_success": true,
"probe_install_callback_success": true,
"probe_launch_callback_success": true,
"remote_launch_foreground_confirmed": false
},
"probe": {
"manual_open_page_screenshot": true,
"page_screenshot": "S2-1.0.4-静置复查.jpg",
"page_screenshot_sha256": "b46fd339dcee4d6ba5406c98847867a6f50f89a64f605cada383125ee6c1c13a",
"page_version": "1.0.4",
"count_visible": 1,
"ready_console_marker_received": false,
"tap_marker_received": false,
"physical_click_verified": true,
"installed_version_now": "1.0.4",
"installed_version_callback_success": true,
"keep_screen_request_user_reported": true,
"keep_screen_idle_verified": true,
"latest_capture_interfered_by_charging_overlay": false,
"manual_tap": {
"user_response": "已点击,次数变为 1",
"capture_request_started": "2026-11-14T13:05:29.919590+08:00",
"file": "S2-1.0.4-手动点击.jpg",
"sha256": "4e0eacffaefef868382d8d92db2f07864090306f9b3d61114d3cbc9630783aab",
"before_count": 0,
"after_count": 1,
"passed": true,
"input_origin": "human_watch_touch_not_PC_injection"
},
"installed_version_screen_confirmed": "1.0.4",
"keep_screen_idle_minimum_seconds": 159,
"physical_screen_user_response": "仍亮着,显示探针",
"keep_screen_scope": "short foreground idle observation on this S2 firmware; no long endurance or permanent system-setting claim",
"keep_screen_1_0_3": {
"passed": false,
"minimum_idle_seconds": 79,
"after_image": "watchface",
"user_response": "已熄屏"
},
"keep_screen_1_0_4": {
"date": "2026-11-14",
"timezone": "Asia/Shanghai",
"phone_transport": "authorized_network_adb_same_phone_verified",
"watch": "OPPO Watch S2 / OWW265",
"probe_version": "1.0.4",
"charger_removed_user_confirmed": true,
"user_no_touch_requested": true,
"baseline": {
"command_completed": "2026-11-14T13:01:35+08:00",
"file": "S2-1.0.4-静置起始.jpg",
"sha256": "b46fd339dcee4d6ba5406c98847867a6f50f89a64f605cada383125ee6c1c13a",
"image_content": "probe1.0.4; count0; 常亮续期中 · 待实测"
},
"after": {
"request_started": "2026-11-14T13:04:14.148761+08:00",
"command_completed": "2026-11-14T13:04:25+08:00",
"minimum_idle_seconds": 159,
"file": "S2-1.0.4-静置复查.jpg",
"sha256": "b46fd339dcee4d6ba5406c98847867a6f50f89a64f605cada383125ee6c1c13a",
"image_content": "probe1.0.4; count0; 常亮续期中 · 待实测"
},
"physical_screen_user_response": "仍亮着,显示探针",
"keep_screen_idle_passed": true,
"scope": "short foreground idle observation on this S2 firmware; no long endurance or permanent system-setting claim",
"screenshot_alone_proves_physical_light": false,
"manual_tap": {
"user_response": "已点击,次数变为 1",
"capture_request_started": "2026-11-14T13:05:29.919590+08:00",
"file": "S2-1.0.4-手动点击.jpg",
"sha256": "4e0eacffaefef868382d8d92db2f07864090306f9b3d61114d3cbc9630783aab",
"before_count": 0,
"after_count": 1,
"passed": true,
"input_origin": "human_watch_touch_not_PC_injection"
},
"official_screenshot_dimensions": [
480,
464
]
}
},
"unsupported_or_incomplete": {
"auto_test_start": "failed code3000 svc exec failed after initial client timeout",
"auto_test_stop": "failed code3000 svc exec failed after initial client timeout",
"probe_network_poc": "no request received; not retained in final probe",
"general_watch_input": "not verified",
"physical_inspector_tunnel": "not verified"
},
"software": {
"python_tests_passed": 20,
"probe_round_build": true,
"probe_rect_build": true,
"native_emulator_ui_round": true,
"native_emulator_ui_rect": true,
"screen_lifecycle_node_tests_passed": 5,
"probe_version_tested": "1.0.4"
},
"cleanup": {
"rpc_logs_off_callback_success": true,
"temporary_network_server_stopped": true,
"temporary_adb_reverse_removed": true,
"upload_cache": {
"deleted": 1
},
"phone_bridge_left_running_for_user_debugging": true,
"adb_forward_18765_left_active": true
}
}
+6
查看文件
@@ -0,0 +1,6 @@
.gradle/
**/build/
local.properties
artifacts/
*.local.json
__pycache__/
+131
查看文件
@@ -0,0 +1,131 @@
# PolyForm Noncommercial License 1.0.0
<https://polyformproject.org/licenses/noncommercial/1.0.0>
## Acceptance
In order to get any license under these terms, you must agree
to them as both strict obligations and conditions to all
your licenses.
## Copyright License
The licensor grants you a copyright license for the
software to do everything you might do with the software
that would otherwise infringe the licensor's copyright
in it for any permitted purpose. However, you may
only distribute the software according to [Distribution
License](#distribution-license) and make changes or new works
based on the software according to [Changes and New Works
License](#changes-and-new-works-license).
## Distribution License
The licensor grants you an additional copyright license
to distribute copies of the software. Your license
to distribute covers distributing the software with
changes and new works permitted by [Changes and New Works
License](#changes-and-new-works-license).
## Notices
You must ensure that anyone who gets a copy of any part of
the software from you also gets a copy of these terms or the
URL for them above, as well as copies of any plain-text lines
beginning with `Required Notice:` that the licensor provided
with the software. For example:
> Required Notice: Copyright Yoyodyne, Inc. (http://example.com)
## Changes and New Works License
The licensor grants you an additional copyright license to
make changes and new works based on the software for any
permitted purpose.
## Patent License
The licensor grants you a patent license for the software that
covers patent claims the licensor can license, or becomes able
to license, that you would infringe by using the software.
## Noncommercial Purposes
Any noncommercial purpose is a permitted purpose.
## Personal Uses
Personal use for research, experiment, and testing for
the benefit of public knowledge, personal study, private
entertainment, hobby projects, amateur pursuits, or religious
observance, without any anticipated commercial application,
is use for a permitted purpose.
## Noncommercial Organizations
Use by any charitable organization, educational institution,
public research organization, public safety or health
organization, environmental protection organization,
or government institution is use for a permitted purpose
regardless of the source of funding or obligations resulting
from the funding.
## Fair Use
You may have "fair use" rights for the software under the
law. These terms do not limit them.
## No Other Rights
These terms do not allow you to sublicense or transfer any of
your licenses to anyone else, or prevent the licensor from
granting licenses to anyone else. These terms do not imply
any other licenses.
## Patent Defense
If you make any written claim that the software infringes or
contributes to infringement of any patent, your patent license
for the software granted under these terms ends immediately. If
your company makes such a claim, your patent license ends
immediately for work on behalf of your company.
## Violations
The first time you are notified in writing that you have
violated any of these terms, or done anything with the software
not covered by your licenses, your licenses can nonetheless
continue if you come into full compliance with these terms,
and take practical steps to correct past violations, within
32 days of receiving notice. Otherwise, all your licenses
end immediately.
## No Liability
***As far as the law allows, the software comes as is, without
any warranty or condition, and the licensor will not be liable
to you for any damages arising out of these terms or the use
or nature of the software, under any kind of legal claim.***
## Definitions
The **licensor** is the individual or entity offering these
terms, and the **software** is the software the licensor makes
available under these terms.
**You** refers to the individual or entity agreeing to these
terms.
**Your company** is any legal entity, sole proprietorship,
or other kind of organization that you work for, plus all
organizations that have control over, are under the control of,
or are under common control with that organization. **Control**
means ownership of substantially all the assets of an entity,
or the power to direct its management and policies by vote,
contract, or otherwise. Control can be direct or indirect.
**Your licenses** are all the licenses granted to you for the
software under these terms.
**Use** means anything you do with the software requiring one
of your licenses.
+11
查看文件
@@ -0,0 +1,11 @@
# 版权、许可与参考
Required Notice: Copyright 2026 herry / sydxky (https://git2.sydxky.cn/sydxky/rtos-watch-debug-bridge)
本项目自研手机桥、PC 工具、配套探针及文档以 [PolyForm Noncommercial 1.0.0](LICENSE) 提供。允许许可条款覆盖的非商业用途、修改及分发;商业用途须另获许可。分发时保留许可全文与 Required Notice。准确权限和例外以英文许可全文为准,不将第三方原有许可改为本许可。
参考 [chengchengking/oppo-watch-s-sideload](https://github.com/chengchengking/oppo-watch-s-sideload),本地参考版本 `162fca4aa51302e18ee9802dc5269e54814c02e8`。Binder 协议和工具为本工程实现;前台亮屏续期参考其公开用法。保留上游 Copyright (c) 2026 chengchengking 及完整 [MIT 许可](third_party/oppo-watch-s-sideload-MIT.txt)。不分发其助手 APK 或反编译结果。
Gradle Wrapper 是第三方构建工具,按其原有 Apache-2.0 及随附第三方条款提供,见 [Gradle 许可全文](third_party/Gradle-LICENSE.txt)。Gradle、Android Gradle Plugin、Android SDK/JDK、Glyphix SDK/运行时各自适用其许可;除 Wrapper 外,本项目不打包这些工具。
开发图标沿用作者工作区的贪吃蛇应用资源,作为本项目探针开发资源提供。Glyphix 文档、OPPO 运动健康、设备及相关商标属于各自权利人。本项目为独立调试工具,不表示设备厂商或上游作者背书;不包含厂商 SDK、运动健康 APK、配对资料、令牌、私有签名密钥或内部 Git 历史。
+155
查看文件
@@ -0,0 +1,155 @@
# RTOS 手机真机调试桥 0.2.0
自研部分按 [PolyForm Noncommercial 1.0.0](LICENSE) 公开,仅限许可允许的非商业用途;商业用途须另获许可。版权和第三方条款见 [NOTICE.md](NOTICE.md)。独立公开项目:[rtos-watch-debug-bridge](https://git2.sydxky.cn/sydxky/rtos-watch-debug-bridge)。
独立 Android 手机工程,包名 `com.sydxky.rtos.bridge`。供 Windows 电脑通过 USB ADB 操作手机上已配对的 OPPO / Glyphix RTOS 手表。APK 安装到手机,Glyphix `bundle.pkg` 安装到手表。
2026-11-14 补测:恢复健康服务并等待重连后,S2 探针安装与设备信息请求成功。实际型号 OWW265 / runtime 0.8.0-5。探针 1.0.3 单次常亮请求实测失败;1.0.4 增加前台亮屏续期后,静置至少 159 秒仍显示探针,用户确认实体屏幕仍亮,随后手动点击计数由 0 变成 1,均保留官方截图。远程调至前台、通用手表操控及真机 Inspector 仍未通过。最新状态见[补测记录](../docs/VALIDATION.md);此前 3000 失败报告保留。
本轮 USB 离线后,经核验同一 P30PRO 的已授权网络 ADB `YOUR_PHONE_SERIAL` 完成后续安装及截屏,使用时可将命令的 `--serial YOUR_PHONE_SERIAL` 替换为当前手机实际 ADB 地址;网络地址可能变化。先运行 `adb devices -l` 确认设备,勿选择其他 OWW261。手机 API 仍只监听回环地址,经 ADB forward 访问。
```text
电脑 bridge.py
→ adb forward tcp:18765 tcp:18765
→ 手机调试桥(127.0.0.1:18765,随机 Bearer 令牌)
→ bindService + Binder.transact
→ 手机运动健康 WearEngineService
→ 厂商蓝牙 / 互联传输
→ S2 手表 / Glyphix 应用
```
## 构建和首次连接
使用非 MSIX PowerShell 7。工程不引用运动健康私有 APK 或 SDK,不与现有 Android 手表工程共用构建脚本。
```powershell
Set-Location -LiteralPath 'C:\path\to\rtos-watch-debug-bridge\phone-debug-bridge'
.\build.ps1 -JavaHome 'C:\path\to\jdk17'
python -m unittest discover -s tests -v
python .\bridge.py --serial YOUR_PHONE_SERIAL setup
python .\bridge.py --serial YOUR_PHONE_SERIAL connect
python .\bridge.py --serial YOUR_PHONE_SERIAL wait-link --seconds 45
python .\bridge.py --serial YOUR_PHONE_SERIAL link
python .\bridge.py --serial YOUR_PHONE_SERIAL info
```
工具链:JDK 17、Gradle 8.13、Android Gradle Plugin 8.13.1、compileSdk 35、targetSdk 34、minSdk 27。JDK / Android SDK 可通过 `build.ps1 -JavaHome ... -AndroidSdk ...` 指定。`ANDROID_HOME` 只对当前构建进程设置。产物:`artifacts/RTOS-Phone-Bridge-0.2.0-debug.apk`,versionCode 3。
首次安装时解锁手机并处理华为系统的安装确认,保持运动健康已配对、手表唤醒;Android 13 及以后可允许调试桥通知。手机界面也提供连接、设备信息、选包安装、启动与日志按钮。`setup` 最长等待安装 45 秒;遇到系统确认超时,先在手机完成确认,再重新运行。
P30PRO 若返回 `bind_rejected`,先打开已经配对的运动健康,再执行 `connect`。2026-11-14 实测启动 `com.heytap.health/.oobe.LaunchActivity` 后绑定成功,不需要修改配对数据或手机认证设置。系统安装确认期间不要执行会打开旧版桥接界面的命令,以免遮住安装页面。
绑定成功可能早于手表完成重连。`wait-link` 只轮询在线查询(1–120 秒,默认 45 秒);未上线时退出码为 2。它不会重复安装或其他写操作。持续 3000 的一次会话在重启健康并等待重连后恢复;这不是已确定的 SDK 根因。
默认互联 appId / license 为参考助手演示使用的 `test` / `test`,仅为开发尝试值,不能证明厂商授权。正式互联消息需要匹配应用的 appId 和 license。使用本地文件避免凭据进入进程命令行:
```powershell
python .\bridge.py --serial YOUR_PHONE_SERIAL connect --config .\connection.local.json
```
本地 JSON 含 `appId`、`license`、可选 `service`,已忽略 `*.local.json`。默认服务包 `com.heytap.health`;其他配套应用需先通过 `/status` 的 `services` 确认实际实现,再在本地配置中选择。`state=bound` 只表示手机 Binder 已就绪;`link` 返回 true 和真实手表回调才构成后续设备证据。
## 常用命令
```powershell
# 安装项目的圆屏 QuickApp 包。先按对应应用的构建说明生成包。
python .\bridge.py --serial YOUR_PHONE_SERIAL install '..\com.sydxky.rtos.deviceprobe\.glyphix-work\dist\generic-watch-466x466-quickapp\com.sydxky.rtos.deviceprobe\bundle.pkg'
python .\bridge.py --serial YOUR_PHONE_SERIAL check com.sydxky.rtos.deviceprobe
python .\bridge.py --serial YOUR_PHONE_SERIAL launch com.sydxky.rtos.deviceprobe
# 开启手表日志后读取事件;Ctrl+C 只停止电脑读取。
python .\bridge.py --serial YOUR_PHONE_SERIAL logs on
python .\bridge.py --serial YOUR_PHONE_SERIAL events --follow
python .\bridge.py --serial YOUR_PHONE_SERIAL logs off
# 消息/文件必须对应支持互联的目标应用,263 消息会检查授权握手。
python .\bridge.py --serial YOUR_PHONE_SERIAL message '{"type":"ping"}'
python .\bridge.py --serial YOUR_PHONE_SERIAL send-file '.\sample.txt' --remote 'internal://files/sample.txt'
# 仅向明确支持的方法发送 RPC;参数是 JSON 字符串。
python .\bridge.py --serial YOUR_PHONE_SERIAL rpc toggle_rpc_log_feature --params '{"status":0}'
# 结束调试:先关闭日志、断开服务,再清手机上传缓存并停止进程。
python .\bridge.py --serial YOUR_PHONE_SERIAL disconnect
python .\bridge.py --serial YOUR_PHONE_SERIAL cleanup
python .\bridge.py --serial YOUR_PHONE_SERIAL stop
```
安装只上传包本身;交给 OPPO 的完整 `dist` 仍须保留 `bundle.pkg`、`manifest.json`、`icon.png`。服务端以回调 `success/failed/progress` 更新作业;电脑退出码 2 表示回调失败或超时,1 表示本地 / HTTP 错误,130 表示用户中断。超时不表示手表操作已取消,避免立即重复安装。`check` 的布尔结果沿用厂商实现,不能替代安装和启动结果。
## 实际验收脚本
```powershell
python .\verify.py --serial YOUR_PHONE_SERIAL `
--probe '..\com.sydxky.rtos.deviceprobe\.glyphix-work\dist\generic-watch-466x466-quickapp\com.sydxky.rtos.deviceprobe\bundle.pkg' `
--output '.\artifacts\device-validation.json'
```
这个命令会安装独立探针、启用 RPC 日志、启动应用并查找 `RTOS_DEVICE_PROBE_READY_V1`,最后关闭日志。可用 `--ready-wait 60` 延长日志等待,范围 1–300 秒。报告仅保留明确允许的模型/版本字段及探针标记,省略令牌、license、原始日志和设备唯一标识。可选 `--config` 使用匹配的互联参数。手表离线时停止后续安装;手机绑定失败也写入具体阶段。安装、启动、设备信息的条目使用 `_callback` 后缀,分别表示厂商成功回调;空设备信息不能推断型号,回调不能替代页面运行或人工点击。当前实际状态见 [2026-11-14 记录](../docs/VALIDATION.md),[早期记录](../docs/VALIDATION.md) 保留为历史。
## 截图、UI 检查与操控
手机 APK 新增“截图与 UI 检查”:打开运动健康、提示官方手表截屏路径、通过系统文件选择器导入图片、显示原比例预览和圆屏 5% 安全区参考线。导入上限 8 MiB / 2048×2048,转换 PNG 后保存在应用私有目录。参考线只显示在预览中;来源标注为用户选择、未经设备身份确认。
电脑工具 `ui.py` 仅使用 Python 标准库,所有操作必须显式选择目标:
| target | 截图来源 | 控件树与操控 | 当前证据 |
| --- | --- | --- | --- |
| `phone` | ADB 手机屏幕 | uiautomator、点击、滑动、文字/ID 断言 | 依赖手机解锁;这是手机界面 |
| `watch-health` | 自动导航运动健康的“设备 → 更多功能 → 手表截屏”,等待官方目录中新保存的图片 | 只提供官方截屏导航 | P30PRO + S2 实测自动导出 480×464 JPEG;50 秒无图则报错 |
| `watch-import` | APK 中用户选择的图片,导出前核验 SHA-256 | 私有图片导出 | 已验证官方 JPEG 导入、预览和 PNG 导出;来源仍标注用户选择 |
| `inspector` | 显式 Glyphix Inspector 的原生快照 | `@system.test` 点击/滑动/等待,控件快照、步骤报告 | 圆/方模拟器实测通过;S2 端点与隧道未确认 |
```powershell
# 手机截图和控件树,文件均代表手机界面。
python .\ui.py --target phone --serial YOUR_PHONE_SERIAL screenshot --output '.\artifacts\phone.png'
python .\ui.py --target phone --serial YOUR_PHONE_SERIAL tree --output '.\artifacts\phone.xml'
python .\ui.py --target phone --serial YOUR_PHONE_SERIAL click --by text --value '截图与 UI 检查'
# 官方截屏;仅当健康将新图片保存到公开图库时可自动导出。
python .\ui.py --target watch-health --serial YOUR_PHONE_SERIAL screenshot --output '.\artifacts\s2.jpg'
# 若官方只保存在私有缓存,先用健康的保存功能,再到本 APK 选择图片。
python .\ui.py --target watch-import --serial YOUR_PHONE_SERIAL screenshot --output '.\artifacts\selected-watch.png'
# 已独立确认的 Inspector。以下端口通常属于本机模拟器。
python .\ui.py --target inspector --inspector http://127.0.0.1:14201 tree --output '.\artifacts\runtime.tree.json'
python .\ui.py --target inspector --inspector http://127.0.0.1:14201 run '.\examples\probe-inspector.json' --output '.\artifacts\ui-run'
```
`run` 接受 1–50 步 JSON,白名单为 `click`、`scroll`、`assert-visible`、`screenshot`;第一步失败即停止并写 `report.json`,退出码 2。手机选择器为 `id/text/description`,重复匹配拒绝点击;Inspector 为 `id/text/tag/class`。示例计划要求探针点击计数从 0 开始。`scroll` 的 `dx/dy` 是像素偏移;`assert-visible` 在 Inspector 中会等元素并尝试滚入视野,不承诺全程静止检查。每次 Inspector 快照均在 finally 恢复运行时,防止截图后暂停计时器。
此次健康 `6.10.15` 将手表截图保存到公开 `Pictures/com.heytap.health/screenshots/watch_screen_shot.jpeg`,后续同名图自动增加 `(1)` 等编号。工具只读取此目录内匹配的官方文件名,并比较图片 ID、修改时间及内容 hash。原图可能因显示缓冲区对齐而为 480×464,不要求严格方形。JPEG 保留原字节;若 `--output` 扩展名不符,会使用实际格式的 `.jpg` 或 `.png` 并在结果中报告最终路径。图片导入 APK 后转为 PNG,因此与 JPEG 的 SHA 不同;导出会与 APK 保存的 PNG 核验一致。其他健康版本若改变保存路径,须重新验证适配。
可用 `python tests/native_ui.py --seed '<已初始化的厂商圆屏镜像目录>' --output '.\artifacts\native-ui'` 复现两个原生模拟器配置,要求本机厂商 SDK、探针圆/方包,以及兼容的 global/launcher 资源。默认读取探针自身的圆屏 image 目录,可先构建普通镜像并按厂商教程初始化模拟器资源。端口被占用时拒绝附加到其他测试。该命令只终止自己启动的模拟器,源码交付不包含厂商工具或全局镜像。
Wear Engine 263 当前已确认安装/启动等能力,未发现通用 S2 触摸注入、控件树或 Inspector 转发接口。因此 `phone` 操作不能用作 S2 点击证据;`inspector` 的端点身份必须另行核验。官方截屏失败时不会回退保存手机截图。
## 接口与资源边界
- 手机仅监听 `127.0.0.1:18765`,不监听 Wi-Fi 地址;所有接口要求随机 256-bit Bearer 令牌,拒绝浏览器 Origin 请求,不提供 CORS。
- `bridge.py` 通过当前已授权 USB ADB 的 `run-as` 读取手机应用私有令牌,令牌不写入电脑文件或日志。这是供本地调试使用的 **debug 签名 APK**,未制作上架版。
- 只有 Launcher Activity 导出,桥接 Service 和图片检查 Activity 不导出;无需存储、蓝牙、位置、麦克风或无障碍权限。文件通过文件选择器 / 认证上传接口进入应用私有目录,跨进程只传只读文件描述符。
- HTTP:`GET /status`、`GET /events?after=N`、`GET /jobs/<id>`;`POST /connect`、`/disconnect`、`/command`、`/cleanup`;`PUT /files/<简单文件名>`。连接 / 命令返回 202,命令返回 `id` 后轮询作业。
- 单文件最多 32 MiB,电脑上传缓存最多 4 个文件 / 64 MiB;HTTP 客户端并发 2,等待队列 4;事件最多 1000 条,作业最多 200 条,同时 pending 作业最多 8 条。离开手机界面后前台服务继续工作,通知可停止;不自动复活进程。
- 日志只在手机进程内保留。运行中的事件接口可能含手表应用自己的内容,分享前自行筛选;验收脚本只保存固定探针标记。结束后执行 `logs off` 和 `stop`。
- `rpc` 可调用厂商方法,但不自动执行卸载、系统改写、认证设置修改或桌面槽位替换。不同固件的支持范围以当前手表回调为准。
- 未实现蓝牙底层协议、手表 ADB、Inspector 端口隧道或通用手表触摸注入。官方截屏导航和用户图片导入在 `ui.py` / APK 图片检查页提供;未来应用真机验证可先通过安装 / 启动 / 生命周期日志进入。
## 协议与参考
发现 Action:`com.xfaith.glyphix.WEAR_ENGINE_ACTION`。绑定传 `packageName`、`appId`、`license`。基础接口 `com.glyphix.mas.GlyphixWear` 的 transaction 14 查询版本;版本至少 `2006003` 时 transaction 18 的参数为 **263**,返回 `com.glyphix.mas.GlyphixWear263`。
| 功能 | 263 | 旧版 |
| --- | ---: | ---: |
| 手表连接状态 | 1 | 1 |
| 设备信息 | 7 | 4 |
| 检查应用 | 8 | 5 |
| 启动应用 | 9 | 6 |
| 发送消息 | 10 | 7 |
| 安装应用 | 16 | 15 |
| 发送文件 | 15 | 12 |
| execLpc / RPC | 4 | 17 |
263 的设备信息 / 检查 / 启动 / 连接状态订阅传手机包名;安装传 appId。安装的字符串参数是手表目标 URI,使用 `remote://mass/bridge_<时间>.pkg`;只传文件名会在此次目标设备返回 `4008 rename remote file failed`。消息参数为手机包名、appId、正文;文件参数为 fd、文件名、目标 URI、appId。消息和文件在 263 模式都先检查互联授权。回调 `WearEngineProgressResolver`:1=成功、2=失败、3=进度。消息授权使用 `wear-engine-auth-<手机包名>`,普通消息订阅使用 `wear-engine-<手机包名>`。
参考 [Glyphix 官方教程](https://docs.xfaith-tech.com/glyphix/docs/tutorials/)、[测试框架](https://docs.xfaith-tech.com/glyphix/docs/api/system-test.html) 和 [oppo-watch-s-sideload](https://github.com/chengchengking/oppo-watch-s-sideload/tree/main)。参考仓库使用此前本地快照 `162fca4aa51302e18ee9802dc5269e54814c02e8`,本轮未重新拉取。后者验证的是 Watch S / OWW262,不能直接视作本项目 S2 验收。本工程独立实现 Binder 线协议;上游文档 MIT 归 chengchengking,参考助手 APK 的版权单独归其作者,本工程不随源码或交付包分发该 APK / SDK / 反编译输出。未采用该仓库底层文件探针中的认证状态修改方案。
+17
查看文件
@@ -0,0 +1,17 @@
plugins { id 'com.android.application' }
android {
namespace 'com.sydxky.rtos.bridge'
compileSdk 35
defaultConfig {
applicationId 'com.sydxky.rtos.bridge'
minSdk 27
targetSdk 34
versionCode 3
versionName '0.2.0'
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_17
targetCompatibility JavaVersion.VERSION_17
}
buildTypes { debug { minifyEnabled false } }
}
@@ -0,0 +1,19 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<queries><intent><action android:name="com.xfaith.glyphix.WEAR_ENGINE_ACTION" /></intent></queries>
<application android:label="RTOS 真机调试桥" android:allowBackup="false" android:icon="@drawable/ic_bridge"
android:dataExtractionRules="@xml/data_extraction_rules"
android:theme="@android:style/Theme.Material.Light.NoActionBar" android:supportsRtl="true">
<activity android:name=".MainActivity" android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".UiToolsActivity" android:exported="false" />
<service android:name=".BridgeService" android:exported="false" android:foregroundServiceType="dataSync" />
</application>
</manifest>
@@ -0,0 +1,53 @@
package com.sydxky.rtos.bridge;
import android.app.*;
import android.content.*;
import android.os.*;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.security.SecureRandom;
public final class BridgeService extends Service {
final Journal journal = new Journal();
WearEngine engine;
private LocalApi api;
final class LocalBinder extends Binder { BridgeService get() { return BridgeService.this; } }
@Override public IBinder onBind(Intent intent) { return new LocalBinder(); }
@Override public void onCreate() {
super.onCreate();
startBridge();
}
private void startBridge() {
NotificationManager nm = getSystemService(NotificationManager.class);
nm.createNotificationChannel(new NotificationChannel("bridge", "RTOS 调试连接", NotificationManager.IMPORTANCE_LOW));
PendingIntent open = PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), PendingIntent.FLAG_IMMUTABLE);
PendingIntent stop = PendingIntent.getService(this, 1, new Intent(this, BridgeService.class).setAction("stop"), PendingIntent.FLAG_IMMUTABLE);
startForeground(1, new Notification.Builder(this, "bridge").setSmallIcon(android.R.drawable.stat_notify_sync)
.setContentTitle("RTOS 真机调试桥运行中").setContentText("USB ADB → 手机 → 已配对手表")
.setContentIntent(open).addAction(new Notification.Action.Builder(null, "停止", stop).build()).build());
engine = new WearEngine(this, journal);
try {
File secret = new File(getFilesDir(), "bridge-token");
if (!secret.exists()) {
byte[] random = new byte[32]; new SecureRandom().nextBytes(random);
String token = java.util.Base64.getUrlEncoder().withoutPadding().encodeToString(random);
Files.write(secret.toPath(), token.getBytes(StandardCharsets.US_ASCII));
}
String token = new String(Files.readAllBytes(secret.toPath()), StandardCharsets.US_ASCII);
api = new LocalApi(engine, journal, token, getFilesDir());
journal.event("bridge.started", "127.0.0.1:" + LocalApi.PORT);
} catch (Exception e) { journal.event("bridge.failed", e.toString()); stopSelf(); }
}
@Override public int onStartCommand(Intent intent, int flags, int startId) {
if (intent != null && "stop".equals(intent.getAction())) {
shutdown(); stopForeground(STOP_FOREGROUND_REMOVE); stopSelf();
} else if (api == null) startBridge();
return START_NOT_STICKY;
}
private void shutdown() {
if (api != null) { try { api.close(); } catch (IOException ignored) {} api = null; }
if (engine != null) engine.close();
}
@Override public void onDestroy() { shutdown(); super.onDestroy(); }
}
@@ -0,0 +1,60 @@
package com.sydxky.rtos.bridge;
import android.util.Log;
import org.json.*;
import java.util.*;
final class Journal {
private long sequence;
private final ArrayDeque<JSONObject> events = new ArrayDeque<>();
private final LinkedHashMap<String, JSONObject> jobs = new LinkedHashMap<>();
static JSONObject json(Object... pairs) {
JSONObject out = new JSONObject();
try { for (int i = 0; i < pairs.length; i += 2) out.put(pairs[i].toString(), pairs[i+1]); }
catch (JSONException e) { throw new IllegalArgumentException(e); }
return out;
}
synchronized void event(String type, Object data) {
Object snapshot = data;
if (data instanceof JSONObject) try { snapshot = new JSONObject(data.toString()); } catch (JSONException ignored) {}
JSONObject item = json("seq", ++sequence, "time", System.currentTimeMillis(), "type", type, "data", snapshot);
events.addLast(item);
while (events.size() > 1000) events.removeFirst();
// Contents stay in the app's authenticated event stream, not the shared Android log.
Log.i("RtosBridge", type);
}
synchronized String newJob(String command) {
long pending = jobs.values().stream().filter(j -> "pending".equals(j.optString("state"))).count();
if (pending >= 8) throw new IllegalStateException("Too many pending operations; wait or reconnect");
String id = UUID.randomUUID().toString();
jobs.put(id, json("id", id, "command", command, "state", "pending", "created", System.currentTimeMillis()));
while (jobs.size() > 200) {
String completed = jobs.entrySet().stream().filter(e -> !"pending".equals(e.getValue().optString("state")))
.map(Map.Entry::getKey).findFirst().orElse(null);
if (completed == null) break;
jobs.remove(completed);
}
return id;
}
synchronized boolean pending(String id) { return jobs.containsKey(id) && "pending".equals(jobs.get(id).optString("state")); }
synchronized void result(String id, String state, Object value) {
if (!pending(id)) return;
JSONObject job = jobs.get(id);
try { job.put("state", state); job.put("result", value); }
catch (JSONException e) { throw new IllegalArgumentException(e); }
event("job." + state, job);
}
synchronized void failPending(String reason) {
for (String id : new ArrayList<>(jobs.keySet())) result(id, "failed", reason);
}
synchronized JSONObject job(String id) {
JSONObject value = jobs.get(id);
if (value == null) return null;
try { return new JSONObject(value.toString()); } catch (JSONException e) { throw new IllegalStateException(e); }
}
synchronized JSONArray events(long after) {
JSONArray out = new JSONArray();
for (JSONObject e : events) if (e.optLong("seq") > after) out.put(e);
return out;
}
}
@@ -0,0 +1,159 @@
package com.sydxky.rtos.bridge;
import org.json.*;
import java.io.*;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.security.MessageDigest;
import java.util.*;
import java.util.concurrent.*;
/** Authenticated loopback endpoint, reachable from the PC using adb forward. */
final class LocalApi implements Closeable {
static final int PORT = 18765;
static final int MAX_FILE = 32 * 1024 * 1024;
private final ServerSocket server;
private final ThreadPoolExecutor clients = new ThreadPoolExecutor(2, 2, 0, TimeUnit.SECONDS, new ArrayBlockingQueue<>(4));
private final Set<Socket> sockets = ConcurrentHashMap.newKeySet();
private final WearEngine engine;
private final Journal journal;
private final String token;
private final File inbox;
private volatile boolean closed;
LocalApi(WearEngine engine, Journal journal, String token, File files) throws IOException {
this.engine = engine; this.journal = journal; this.token = token;
inbox = new File(files, "inbox");
if (!inbox.isDirectory() && !inbox.mkdirs()) throw new IOException("Cannot create inbox");
server = new ServerSocket();
server.setReuseAddress(true);
server.bind(new InetSocketAddress(InetAddress.getByName("127.0.0.1"), PORT), 4);
new Thread(this::accept, "bridge-loopback").start();
}
private void accept() {
while (!closed) try {
Socket socket = server.accept();
socket.setSoTimeout(15000); sockets.add(socket);
try { clients.execute(() -> handle(socket)); }
catch (RejectedExecutionException e) { sockets.remove(socket); socket.close(); }
} catch (IOException e) { if (!closed) journal.event("api.error", e.getClass().getSimpleName()); }
}
private String line(InputStream in) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
for (int i = 0; i < 8192; i++) {
int c = in.read();
if (c < 0) throw new EOFException();
if (c == '\n') return out.toString(StandardCharsets.US_ASCII.name()).replace("\r", "");
out.write(c);
}
throw new IOException("Header line too long");
}
private void handle(Socket socket) {
try (Socket ignored = socket) {
try {
InputStream in = new BufferedInputStream(socket.getInputStream());
String[] request = line(in).split(" ");
if (request.length != 3) { respond(socket, 400, Journal.json("error", "Bad request")); return; }
Map<String, String> headers = new HashMap<>();
int size = 0;
while (true) {
String l = line(in); size += l.length();
if (size > 8192) throw new IOException("Headers too long");
if (l.isEmpty()) break;
int colon = l.indexOf(':');
if (colon < 1) throw new IOException("Bad header");
String key = l.substring(0, colon).trim().toLowerCase(Locale.ROOT);
if (headers.put(key, l.substring(colon+1).trim()) != null) throw new IOException("Duplicate header");
}
if (headers.containsKey("origin") || !MessageDigest.isEqual(("Bearer " + token).getBytes(StandardCharsets.US_ASCII),
headers.getOrDefault("authorization", "").getBytes(StandardCharsets.US_ASCII))) {
respond(socket, 401, Journal.json("error", "Unauthorized")); return;
}
if (headers.containsKey("transfer-encoding")) { respond(socket, 400, Journal.json("error", "Content-Length required")); return; }
URI uri = URI.create(request[1]);
String method = request[0], path = uri.getPath();
if (method.equals("GET") && path.equals("/status")) { respond(socket, 200, engine.status()); return; }
if (method.equals("GET") && path.equals("/events")) {
String q = uri.getQuery();
long after = q == null ? 0 : Long.parseLong(q.replaceFirst("^after=", ""));
respond(socket, 200, Journal.json("events", journal.events(after))); return;
}
if (method.equals("GET") && path.startsWith("/jobs/")) {
JSONObject job = journal.job(path.substring(6));
respond(socket, job == null ? 404 : 200, job == null ? Journal.json("error", "Job expired or unknown") : job); return;
}
int length = Integer.parseInt(headers.getOrDefault("content-length", "0"));
if (length < 0 || length > MAX_FILE) { respond(socket, 413, Journal.json("error", "File too large")); return; }
if (method.equals("PUT") && path.startsWith("/files/")) {
String name = path.substring(7);
if (!name.matches("[a-zA-Z0-9._-]{1,100}") || name.startsWith(".") || length == 0) {
respond(socket, 400, Journal.json("error", "Invalid file name or empty file")); return;
}
synchronized (inbox) {
File target = new File(inbox, name);
File[] files = inbox.listFiles();
long total = 0; int count = 0;
if (files != null) for (File f : files) if (!f.equals(target)) { total += f.length(); count++; }
if (count >= 4 || total + length > 64L * 1024 * 1024) {
respond(socket, 413, Journal.json("error", "Inbox full; use cleanup after transfers finish")); return;
}
File temp = new File(inbox, ".upload");
MessageDigest digest = MessageDigest.getInstance("SHA-256");
try {
try (OutputStream out = new FileOutputStream(temp)) {
byte[] buffer = new byte[16384]; int left = length;
while (left > 0) {
int n = in.read(buffer, 0, Math.min(left, buffer.length));
if (n < 0) throw new EOFException();
out.write(buffer, 0, n); digest.update(buffer, 0, n); left -= n;
}
}
StringBuilder sha = new StringBuilder();
for (byte b : digest.digest()) sha.append(String.format(Locale.ROOT, "%02x", b & 255));
String expected = headers.get("x-sha256");
if (expected != null && !expected.equalsIgnoreCase(sha.toString())) throw new IOException("SHA-256 mismatch");
Files.move(temp.toPath(), target.toPath(), java.nio.file.StandardCopyOption.REPLACE_EXISTING);
respond(socket, 200, Journal.json("file", name, "size", length, "sha256", sha.toString()));
} finally { if (temp.exists()) temp.delete(); }
}
return;
}
if (!method.equals("POST") || length > 65536) { respond(socket, 404, Journal.json("error", "Unknown route")); return; }
byte[] body = new byte[length];
new DataInputStream(in).readFully(body);
JSONObject args = new JSONObject(length == 0 ? "{}" : new String(body, StandardCharsets.UTF_8));
switch (path) {
case "/connect": engine.connect(args); respond(socket, 202, Journal.json("accepted", true)); break;
case "/disconnect": engine.disconnect(); respond(socket, 202, Journal.json("accepted", true)); break;
case "/command": respond(socket, 202, Journal.json("id", engine.execute(args))); break;
case "/cleanup":
synchronized (inbox) {
File[] files = inbox.listFiles(); int deleted = 0;
if (files != null) for (File f : files) if (f.isFile() && f.delete()) deleted++;
respond(socket, 200, Journal.json("deleted", deleted));
}
break;
default: respond(socket, 404, Journal.json("error", "Unknown route"));
}
} catch (Exception e) {
journal.event("api.request_failed", e.getClass().getSimpleName());
respond(socket, e instanceof IllegalStateException ? 409 : 400,
Journal.json("error", "Invalid request", "kind", e.getClass().getSimpleName()));
}
} catch (Exception e) {
// Never put request bodies, license values or bearer tokens in logcat.
journal.event("api.request_failed", e.getClass().getSimpleName());
} finally { sockets.remove(socket); }
}
private void respond(Socket socket, int status, JSONObject value) throws IOException {
byte[] body = value.toString().getBytes(StandardCharsets.UTF_8);
String head = "HTTP/1.1 " + status + " Response\r\nContent-Type: application/json; charset=utf-8\r\nCache-Control: no-store\r\nConnection: close\r\nContent-Length: " + body.length + "\r\n\r\n";
OutputStream out = socket.getOutputStream(); out.write(head.getBytes(StandardCharsets.US_ASCII)); out.write(body); out.flush();
}
@Override public void close() throws IOException {
closed = true; server.close();
for (Socket socket : sockets) try { socket.close(); } catch (IOException ignored) {}
clients.shutdownNow();
}
}
@@ -0,0 +1,105 @@
package com.sydxky.rtos.bridge;
import android.app.*;
import android.content.*;
import android.graphics.Color;
import android.os.*;
import android.view.*;
import android.widget.*;
import org.json.*;
import java.io.*;
public final class MainActivity extends Activity {
private BridgeService bridge;
private boolean bound;
private final Handler handler = new Handler(Looper.getMainLooper());
private TextView status, events;
private EditText app, license, pkg;
private final ServiceConnection connection = new ServiceConnection() {
@Override public void onServiceConnected(ComponentName name, IBinder binder) { bridge = ((BridgeService.LocalBinder) binder).get(); refresh(); }
@Override public void onServiceDisconnected(ComponentName name) { bridge = null; }
};
private final Runnable tick = new Runnable() { public void run() { refresh(); handler.postDelayed(this, 1500); } };
@Override public void onCreate(Bundle saved) {
super.onCreate(saved);
getWindow().setStatusBarColor(Color.rgb(19, 40, 63));
ScrollView scroll = new ScrollView(this);
LinearLayout root = new LinearLayout(this); root.setOrientation(LinearLayout.VERTICAL); root.setPadding(dp(22), dp(24), dp(22), dp(24));
scroll.addView(root); setContentView(scroll);
TextView title = label("RTOS 真机调试桥", 26); root.addView(title);
root.addView(label("电脑 USB ADB → P30PRO → 已配对 S2\n请保持运动健康与手表连接。", 15));
status = label("正在启动…", 14); root.addView(status);
app = field("互联 appId", "test"); root.addView(app);
license = field("互联 license(按厂商要求填写)", "test");
license.setInputType(129); root.addView(license);
button(root, "连接运动健康", () -> { if (bridge != null) bridge.engine.connect(Journal.json("appId", app.getText().toString().trim(), "license", license.getText().toString())); });
button(root, "获取手表信息", () -> command(Journal.json("command", "info")));
pkg = field("手表应用包名", "com.sydxky.rtos.deviceprobe"); root.addView(pkg);
button(root, "检查应用", () -> command(Journal.json("command", "check", "package", pkg.getText().toString().trim())));
button(root, "启动应用", () -> command(Journal.json("command", "launch", "package", pkg.getText().toString().trim())));
button(root, "选择 PKG / RPK 安装", () -> startActivityForResult(new Intent(Intent.ACTION_OPEN_DOCUMENT).setType("*/*").addCategory(Intent.CATEGORY_OPENABLE), 10));
button(root, "开启手表日志", () -> command(Journal.json("command", "logs", "enabled", true)));
button(root, "关闭手表日志", () -> command(Journal.json("command", "logs", "enabled", false)));
button(root, "截图与 UI 检查", () -> startActivity(new Intent(this, UiToolsActivity.class)));
button(root, "断开互联服务", () -> { if (bridge != null) bridge.engine.disconnect(); });
button(root, "停止调试桥", () -> { unbind(); stopService(new Intent(this, BridgeService.class)); status.setText("已停止。重新打开应用可启动。"); });
events = label("等待操作", 12); events.setTextIsSelectable(true); root.addView(events);
startForegroundService(new Intent(this, BridgeService.class));
bound = bindService(new Intent(this, BridgeService.class), connection, BIND_AUTO_CREATE);
if (Build.VERSION.SDK_INT >= 33 && checkSelfPermission(android.Manifest.permission.POST_NOTIFICATIONS) != android.content.pm.PackageManager.PERMISSION_GRANTED)
requestPermissions(new String[]{android.Manifest.permission.POST_NOTIFICATIONS}, 11);
}
private void command(JSONObject request) {
if (bridge == null) return;
try { bridge.engine.execute(request); } catch (Exception e) { Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show(); }
}
@Override protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
startForegroundService(new Intent(this, BridgeService.class));
if (!bound) bound = bindService(new Intent(this, BridgeService.class), connection, BIND_AUTO_CREATE);
}
private void refresh() {
if (bridge == null) return;
JSONObject s = bridge.engine.status();
status.setText("服务:" + s.optString("state") + " · 协议 " + s.optInt("protocol") + "\n电脑转发端口:18765");
JSONArray rows = bridge.journal.events(0);
StringBuilder text = new StringBuilder();
for (int i = Math.max(0, rows.length() - 18); i < rows.length(); i++) {
JSONObject row = rows.optJSONObject(i);
String data = String.valueOf(row.opt("data"));
text.append(row.optLong("seq")).append(" ").append(row.optString("type")).append("\n")
.append(data.substring(0, Math.min(1200, data.length()))).append("\n\n");
}
events.setText(text.toString());
}
@Override protected void onActivityResult(int request, int result, Intent data) {
super.onActivityResult(request, result, data);
if (request != 10 || result != RESULT_OK || data == null || data.getData() == null) return;
final android.net.Uri uri = data.getData();
new Thread(() -> {
File inbox = new File(getFilesDir(), "inbox");
File target = new File(inbox, "selected.pkg");
File temporary = new File(inbox, ".selected");
try {
if (!inbox.isDirectory() && !inbox.mkdirs()) throw new IOException("Cannot create inbox");
try (InputStream in = getContentResolver().openInputStream(uri); OutputStream out = new FileOutputStream(temporary)) {
byte[] buffer = new byte[16384]; int n, total = 0;
if (in == null) throw new IOException("Cannot read document");
while ((n = in.read(buffer)) != -1) { total += n; if (total > LocalApi.MAX_FILE) throw new IOException("包超过 32 MiB"); out.write(buffer, 0, n); }
if (total == 0) throw new IOException("空文件");
}
java.nio.file.Files.move(temporary.toPath(), target.toPath(), java.nio.file.StandardCopyOption.REPLACE_EXISTING);
handler.post(() -> command(Journal.json("command", "install", "file", "selected.pkg")));
} catch (Exception e) { handler.post(() -> Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show()); }
finally { if (temporary.exists()) temporary.delete(); }
}, "document-import").start();
}
private int dp(int n) { return (int) (n * getResources().getDisplayMetrics().density); }
private TextView label(String text, int size) { TextView v = new TextView(this); v.setText(text); v.setTextSize(size); v.setPadding(0, dp(8), 0, dp(8)); return v; }
private EditText field(String hint, String value) { EditText v = new EditText(this); v.setHint(hint); v.setText(value); v.setTextSize(15); v.setSingleLine(true); return v; }
private void button(LinearLayout parent, String text, Runnable action) { Button b = new Button(this); b.setText(text); b.setAllCaps(false); b.setOnClickListener(v -> action.run()); parent.addView(b); }
private void unbind() { if (bound) { unbindService(connection); bound = false; } bridge = null; }
@Override protected void onResume() { super.onResume(); handler.post(tick); }
@Override protected void onPause() { handler.removeCallbacks(tick); super.onPause(); }
@Override protected void onDestroy() { unbind(); super.onDestroy(); }
}
@@ -0,0 +1,150 @@
package com.sydxky.rtos.bridge;
import android.app.Activity;
import android.content.Intent;
import android.graphics.*;
import android.os.Bundle;
import android.view.View;
import android.widget.*;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.security.MessageDigest;
import java.util.Locale;
/** Watch screenshot entry, private import and visual safe-area inspection. */
public final class UiToolsActivity extends Activity {
private TextView details;
private CaptureView preview;
private Button select;
private volatile boolean closed;
private static final Object CAPTURE_LOCK = new Object();
@Override public void onCreate(Bundle saved) {
super.onCreate(saved);
LinearLayout root = new LinearLayout(this);
root.setOrientation(LinearLayout.VERTICAL);
int padding = (int) (18 * getResources().getDisplayMetrics().density);
root.setPadding(padding, padding, padding, padding);
ScrollView scroll = new ScrollView(this); scroll.addView(root); setContentView(scroll);
TextView title = new TextView(this); title.setText("S2 截图与 UI 检查"); title.setTextSize(24); root.addView(title);
TextView help = new TextView(this);
help.setText("手表截屏:运动健康 → 设备 → 更多功能 → 手表截屏。\n选择生成的图片后可预览、检查圆屏安全区,并由电脑导出。\n\n控件树、点击和滑动:电脑 ui.py 支持 ADB 手机界面,以及已连接的 Glyphix Inspector。当前 Wear Engine 接口没有确认通用 S2 触摸和控件树通道。");
help.setTextSize(15); root.addView(help);
button(root, "打开运动健康截屏入口", () -> {
Intent launch = getPackageManager().getLaunchIntentForPackage("com.heytap.health");
if (launch == null) Toast.makeText(this, "请先安装并配对运动健康", Toast.LENGTH_LONG).show();
else {
try { startActivity(launch); }
catch (RuntimeException error) { Toast.makeText(this, "运动健康暂不可打开", Toast.LENGTH_LONG).show(); }
}
});
select = button(root, "选择官方生成的手表截屏", () -> startActivityForResult(
new Intent(Intent.ACTION_OPEN_DOCUMENT).setType("image/*").addCategory(Intent.CATEGORY_OPENABLE), 20));
CheckBox safe = new CheckBox(this); safe.setText("显示圆屏 5% 安全区参考线"); safe.setChecked(true); root.addView(safe);
preview = new CaptureView();
root.addView(preview, new LinearLayout.LayoutParams(-1, (int) (320 * getResources().getDisplayMetrics().density)));
safe.setOnCheckedChangeListener((button, checked) -> { preview.safeArea = checked; preview.invalidate(); });
details = new TextView(this); details.setTextSize(13); details.setTextIsSelectable(true); root.addView(details);
button(root, "返回调试桥", this::finish);
loadExisting();
}
private Button button(LinearLayout parent, String text, Runnable action) {
Button b = new Button(this); b.setText(text); b.setAllCaps(false); b.setOnClickListener(v -> action.run()); parent.addView(b);
return b;
}
private void loadExisting() {
File image = new File(getFilesDir(), "ui/watch-capture.png");
File meta = new File(getFilesDir(), "ui/watch-capture.json");
if (image.isFile() && meta.isFile()) {
new Thread(() -> {
try {
Bitmap bitmap;
String text;
synchronized (CAPTURE_LOCK) {
bitmap = BitmapFactory.decodeFile(image.toString());
text = new String(Files.readAllBytes(meta.toPath()), StandardCharsets.UTF_8);
}
runOnUiThread(() -> { if (!closed) { preview.setBitmap(bitmap); details.setText(text); } else if (bitmap != null) bitmap.recycle(); });
} catch (IOException ignored) { }
}, "capture-preview").start();
} else details.setText("尚未选择图片。选择的图片由用户确认来源,不自动作为 S2 实机验收证据。");
}
@Override protected void onActivityResult(int request, int result, Intent data) {
super.onActivityResult(request, result, data);
if (request != 20 || result != RESULT_OK || data == null || data.getData() == null) return;
android.net.Uri source = data.getData();
select.setEnabled(false);
details.setText("正在检查并保存截屏…");
new Thread(() -> {
File temp = null;
Bitmap bitmap = null;
try {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
try (InputStream in = getContentResolver().openInputStream(source)) {
if (in == null) throw new IOException("无法读取图片");
byte[] block = new byte[16384]; int n, total = 0;
while ((n = in.read(block)) != -1) {
total += n; if (total > 8 * 1024 * 1024) throw new IOException("图片超过 8 MiB");
bytes.write(block, 0, n);
}
}
byte[] encoded = bytes.toByteArray();
BitmapFactory.Options bounds = new BitmapFactory.Options(); bounds.inJustDecodeBounds = true;
BitmapFactory.decodeByteArray(encoded, 0, encoded.length, bounds);
if (bounds.outWidth <= 0 || bounds.outHeight <= 0 || bounds.outWidth > 2048 || bounds.outHeight > 2048)
throw new IOException("请选择不超过 2048×2048 的手表截屏");
bitmap = BitmapFactory.decodeByteArray(encoded, 0, encoded.length);
if (bitmap == null) throw new IOException("图片解码失败");
File folder = new File(getFilesDir(), "ui");
if (!folder.isDirectory() && !folder.mkdirs()) throw new IOException("无法创建截屏目录");
temp = File.createTempFile("capture-", ".png", folder);
try (OutputStream out = new FileOutputStream(temp)) {
if (!bitmap.compress(Bitmap.CompressFormat.PNG, 100, out)) throw new IOException("PNG 保存失败");
}
byte[] hash = MessageDigest.getInstance("SHA-256").digest(Files.readAllBytes(temp.toPath()));
StringBuilder sha = new StringBuilder(); for (byte b : hash) sha.append(String.format(Locale.ROOT, "%02x", b & 255));
String metadata = Journal.json("source", "user_selected_image_origin_not_attested", "width", bitmap.getWidth(),
"height", bitmap.getHeight(), "sha256", sha.toString(), "importedAt", System.currentTimeMillis()).toString();
synchronized (CAPTURE_LOCK) {
Files.move(temp.toPath(), new File(folder, "watch-capture.png").toPath(), StandardCopyOption.REPLACE_EXISTING);
Files.write(new File(folder, "watch-capture.json").toPath(), metadata.getBytes(StandardCharsets.UTF_8));
}
Bitmap resultBitmap = bitmap; bitmap = null;
runOnUiThread(() -> {
if (closed) { resultBitmap.recycle(); return; }
preview.setBitmap(resultBitmap);
details.setText("图片已保存在本应用私有目录。安全区参考线不会写入原图。\n" + metadata +
"\n\n电脑导出:python ui.py --target watch-import --serial <手机序列号> screenshot --output watch.png");
});
} catch (Exception error) {
runOnUiThread(() -> { if (!closed) details.setText("导入失败:" + error.getClass().getSimpleName()); });
} finally {
if (bitmap != null) bitmap.recycle();
if (temp != null && temp.exists()) temp.delete();
runOnUiThread(() -> { if (!closed) select.setEnabled(true); });
}
}, "watch-capture-import").start();
}
@Override protected void onDestroy() { closed = true; preview.setBitmap(null); super.onDestroy(); }
private final class CaptureView extends View {
Bitmap bitmap;
boolean safeArea = true;
final Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG);
CaptureView() { super(UiToolsActivity.this); setBackgroundColor(Color.rgb(24, 35, 49)); }
void setBitmap(Bitmap image) { if (bitmap != null && bitmap != image) bitmap.recycle(); bitmap = image; invalidate(); }
@Override protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (bitmap == null) return;
float scale = Math.min((float)getWidth() / bitmap.getWidth(), (float)getHeight() / bitmap.getHeight());
float w = bitmap.getWidth() * scale, h = bitmap.getHeight() * scale;
RectF destination = new RectF((getWidth()-w)/2, (getHeight()-h)/2, (getWidth()+w)/2, (getHeight()+h)/2);
paint.setStyle(Paint.Style.FILL); canvas.drawBitmap(bitmap, null, destination, paint);
if (safeArea) {
paint.setColor(Color.CYAN); paint.setStyle(Paint.Style.STROKE); paint.setStrokeWidth(2);
canvas.drawCircle(getWidth()/2f, getHeight()/2f, Math.min(w, h) * .45f, paint);
}
}
}
}
@@ -0,0 +1,241 @@
package com.sydxky.rtos.bridge;
import android.content.*;
import android.content.pm.ResolveInfo;
import android.os.*;
import org.json.*;
import java.io.*;
import java.util.*;
import java.util.concurrent.*;
/** Small independent implementation of the observed Wear Engine Binder wire contract. */
final class WearEngine {
static final String ACTION = "com.xfaith.glyphix.WEAR_ENGINE_ACTION";
static final String OLD = "com.glyphix.mas.GlyphixWear";
static final String NEW = "com.glyphix.mas.GlyphixWear263";
private final Context context;
private final Journal journal;
private final Handler main = new Handler(Looper.getMainLooper());
private final ExecutorService worker = Executors.newSingleThreadExecutor();
private final Map<String, Binder> callbacks = new ConcurrentHashMap<>();
private volatile IBinder remote;
private volatile String descriptor = OLD, appId = "test", servicePackage = "", state = "disconnected";
private volatile int version, generation;
private ServiceConnection connection;
private Binder heartbeat, rpc, messages, link, auth;
private volatile boolean authorized;
private volatile boolean closing;
WearEngine(Context context, Journal journal) { this.context = context; this.journal = journal; }
interface Writer { void write(Parcel p) throws Exception; }
interface Reader<T> { T read(Parcel p) throws Exception; }
private <T> T call(IBinder binder, String token, int code, Writer writer, Reader<T> reader) throws Exception {
if (binder == null || !binder.isBinderAlive()) throw new IllegalStateException("Wear Engine is disconnected");
Parcel data = Parcel.obtain(), reply = Parcel.obtain();
try {
data.writeInterfaceToken(token);
writer.write(data);
if (!binder.transact(code, data, reply, 0)) throw new IOException("Unsupported Binder transaction " + code);
reply.readException();
return reader.read(reply);
} finally { data.recycle(); reply.recycle(); }
}
private void transact(int code, Writer writer) throws Exception { call(remote, descriptor, code, writer, p -> null); }
private boolean modern() { return version >= 2006003; }
JSONArray services() {
JSONArray out = new JSONArray();
for (ResolveInfo r : context.getPackageManager().queryIntentServices(new Intent(ACTION), 0))
out.put(Journal.json("package", r.serviceInfo.packageName, "class", r.serviceInfo.name,
"exported", r.serviceInfo.exported));
return out;
}
JSONObject status() {
return Journal.json("state", state, "service", servicePackage, "masVersion", version,
"protocol", modern() ? 263 : 262, "appId", appId, "messageAuthorized", authorized, "services", services());
}
void connect(JSONObject args) {
if (closing) throw new IllegalStateException("Bridge is stopping");
String requested = args.optString("service", "com.heytap.health");
String requestedApp = args.optString("appId", "test");
String license = args.optString("license", "test");
main.post(() -> {
disconnectNow();
appId = requestedApp;
int epoch = ++generation;
List<ResolveInfo> found = context.getPackageManager().queryIntentServices(new Intent(ACTION), 0);
ResolveInfo selected = null;
for (ResolveInfo r : found) if (requested.equals(r.serviceInfo.packageName)) { selected = r; break; }
if (selected == null && requested.isEmpty() && found.size() == 1) selected = found.get(0);
if (selected == null) { state = "service_not_found"; journal.event("connect.failed", status()); return; }
servicePackage = selected.serviceInfo.packageName;
Intent intent = new Intent(ACTION).setComponent(new ComponentName(servicePackage, selected.serviceInfo.name));
intent.putExtra("packageName", context.getPackageName());
intent.putExtra("appId", appId);
intent.putExtra("license", license);
state = "binding";
connection = new ServiceConnection() {
@Override public void onServiceConnected(ComponentName name, IBinder binder) {
worker.execute(() -> {
try {
int detected = call(binder, OLD, 14, p -> {}, Parcel::readInt);
IBinder target = detected >= 2006003 ? call(binder, OLD, 18, p -> p.writeInt(263), Parcel::readStrongBinder) : binder;
if (epoch != generation) return;
version = detected; remote = target; descriptor = modern() ? NEW : OLD;
if (target == null) throw new IOException("263 Binder is null");
if (!descriptor.equals(target.getInterfaceDescriptor())) throw new IOException("Unexpected interface descriptor");
heartbeat = callback("WearEngineHearBeatResolver", (code, data) -> {});
rpc = callback("WearEngineMessageResolver", (code, data) -> journal.event("watch.log", data.readString()));
messages = callback("WearEngineMessageResolver", (code, data) -> journal.event("watch.message", data.readString()));
link = callback("WearEngineDeviceLinkStatusResolver", (code, data) -> journal.event("watch.link", data.readInt() != 0));
transact(modern() ? 11 : 8, p -> { if (modern()) { p.writeString(context.getPackageName()); p.writeString(appId); } p.writeStrongBinder(heartbeat); });
transact(modern() ? 3 : 16, p -> p.writeStrongBinder(rpc));
transact(modern() ? 5 : 2, p -> { if (modern()) p.writeString(context.getPackageName()); p.writeStrongBinder(link); });
transact(modern() ? 13 : 10, p -> { if (modern()) { p.writeString(context.getPackageName()); p.writeString("wear-engine-" + context.getPackageName()); } p.writeStrongBinder(messages); });
if (modern()) {
auth = callback("WearEngineMessageResolver", (code, data) -> {
JSONObject payload = new JSONObject(data.readString());
authorized = license.equals(payload.optString("fingerprint"));
journal.event("watch.auth", authorized);
if (authorized) worker.execute(() -> {
if (epoch != generation) return;
try { transact(10, p -> {
p.writeString(context.getPackageName()); p.writeString(appId);
p.writeString("{\"event\":\"OnOpen\",\"data\":{}}"); p.writeStrongBinder(null);
}); } catch (Exception e) { journal.event("auth.notify_failed", e.getClass().getSimpleName()); }
});
});
transact(17, p -> { p.writeString(context.getPackageName()); p.writeString("wear-engine-auth-" + context.getPackageName()); p.writeStrongBinder(auth); });
}
state = "bound";
journal.event("connect.bound", status());
} catch (Exception e) {
if (epoch == generation) { state = "failed"; remote = null; journal.event("connect.failed", e.toString()); }
}
});
}
@Override public void onServiceDisconnected(ComponentName name) { lost(epoch, "service_disconnected"); }
@Override public void onNullBinding(ComponentName name) { lost(epoch, "null_binding"); }
@Override public void onBindingDied(ComponentName name) { lost(epoch, "binding_died"); }
};
try {
if (!context.bindService(intent, connection, Context.BIND_AUTO_CREATE)) { state = "bind_rejected"; connection = null; }
} catch (Exception e) { state = "failed"; journal.event("connect.failed", e.toString()); }
main.postDelayed(() -> { if (epoch == generation && "binding".equals(state)) { state = "bind_timeout"; journal.event("connect.failed", "No service callback within 15s"); } }, 15000);
});
}
private void lost(int epoch, String reason) {
if (epoch != generation) return;
remote = null; state = reason; callbacks.clear(); journal.failPending(reason); journal.event("connect.lost", reason);
}
interface Callback { void accept(int code, Parcel data) throws Exception; }
private Binder callback(String name, Callback body) {
String token = "com.glyphix.mas." + name;
int epoch = generation;
return new Binder() {
@Override protected boolean onTransact(int code, Parcel data, Parcel reply, int flags) throws RemoteException {
if (code == INTERFACE_TRANSACTION) { if (reply != null) reply.writeString(token); return true; }
if (code >= 1 && code <= 3) {
data.enforceInterface(token);
if (epoch == generation) {
try { body.accept(code, data); }
catch (Exception e) { journal.event("callback.error", e.getClass().getSimpleName()); }
}
if (reply != null) reply.writeNoException();
return true;
}
return super.onTransact(code, data, reply, flags);
}
};
}
String execute(JSONObject args) {
String command = args.optString("command");
if (!Arrays.asList("info", "link", "check", "launch", "install", "message", "send-file", "rpc", "logs").contains(command))
throw new IllegalArgumentException("Unknown command");
String id = journal.newJob(command);
int epoch = generation;
Binder resolver = callback("WearEngineProgressResolver", (code, data) -> {
if (!journal.pending(id)) return;
String raw = data.readString();
Object value;
try { value = new JSONTokener(raw == null ? "null" : raw).nextValue(); }
catch (JSONException e) { value = raw == null ? "" : raw; }
journal.result(id, code == 1 ? "success" : code == 2 ? "failed" : "pending", value);
if (code != 3) callbacks.remove(id);
});
callbacks.put(id, resolver);
main.postDelayed(() -> {
if (callbacks.remove(id) != null) journal.result(id, "timeout", "No terminal watch callback; operation may still complete on the watch");
}, 180000);
worker.execute(() -> {
try {
if (epoch != generation) throw new IOException("Connection changed");
if (!"bound".equals(state)) throw new IOException("Bind the service first");
switch (command) {
case "link":
boolean connected = call(remote, descriptor, 1, p -> {}, p -> p.readInt() != 0);
callbacks.remove(id); journal.result(id, "success", Journal.json("connected", connected)); break;
case "info": transact(modern() ? 7 : 4, p -> { if (modern()) p.writeString(context.getPackageName()); p.writeStrongBinder(resolver); }); break;
case "check": case "launch": {
String pkg = args.getString("package");
if (!pkg.matches("[A-Za-z0-9_]+(\\.[A-Za-z0-9_]+)+")) throw new IllegalArgumentException("Invalid package name");
int code = command.equals("check") ? (modern() ? 8 : 5) : (modern() ? 9 : 6);
transact(code, p -> { if (modern()) p.writeString(context.getPackageName()); p.writeString(pkg); p.writeStrongBinder(resolver); }); break;
}
case "install": case "send-file": {
if (command.equals("send-file") && modern() && !authorized)
throw new IllegalStateException("Watch interconnect authorization pending; use matching appId/license");
String name = args.getString("file");
if (!name.matches("[a-zA-Z0-9._-]{1,100}") || name.startsWith(".")) throw new IllegalArgumentException("Invalid file name");
File file = new File(context.getFilesDir(), "inbox/" + name);
if (!file.isFile() || file.length() == 0) throw new IOException("Upload file first");
try (ParcelFileDescriptor fd = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY)) {
if (command.equals("install")) transact(modern() ? 16 : 15, p -> {
if (modern()) p.writeString(appId);
// The argument is a watch destination URI, not a display filename.
p.writeInt(1); fd.writeToParcel(p, 0); p.writeString("remote://mass/bridge_" + System.currentTimeMillis() + ".pkg"); p.writeStrongBinder(resolver);
});
else transact(modern() ? 15 : 12, p -> {
p.writeInt(1); fd.writeToParcel(p, 0); p.writeString(name); p.writeString(args.getString("remote")); p.writeString(appId); p.writeStrongBinder(resolver);
});
}
break;
}
case "message":
if (modern() && !authorized) throw new IllegalStateException("Watch interconnect authorization pending; use matching appId/license");
transact(modern() ? 10 : 7, p -> {
if (modern()) p.writeString(context.getPackageName());
p.writeString(appId);
p.writeString(args.getString("message")); p.writeStrongBinder(resolver);
}); break;
case "rpc": case "logs": {
String method = command.equals("logs") ? "toggle_rpc_log_feature" : args.getString("method");
String params = command.equals("logs") ? Journal.json("status", args.optBoolean("enabled", true) ? 1 : 0).toString() : args.optString("params", "{}");
transact(modern() ? 4 : 17, p -> { p.writeString(method); p.writeString(params); p.writeStrongBinder(resolver); }); break;
}
default: throw new IllegalArgumentException(command);
}
} catch (Exception e) { callbacks.remove(id); journal.result(id, "failed", e.toString()); }
});
return id;
}
void disconnect() { main.post(this::disconnectNow); }
private void disconnectNow() {
++generation;
IBinder old = remote;
String oldDescriptor = descriptor, oldApp = appId;
boolean wasModern = modern();
if (old != null && !worker.isShutdown()) worker.execute(() -> {
try {
call(old, oldDescriptor, wasModern ? 12 : 9, p -> { if (wasModern) { p.writeString(context.getPackageName()); p.writeString(oldApp); } }, p -> null);
call(old, oldDescriptor, wasModern ? 14 : 11, p -> { if (wasModern) { p.writeString(context.getPackageName()); p.writeString("wear-engine-" + context.getPackageName()); } }, p -> null);
call(old, oldDescriptor, wasModern ? 6 : 3, p -> { if (wasModern) p.writeString(context.getPackageName()); }, p -> null);
// registerRpcLogListener does not accept null in the observed service.
// Its callback is invalidated by the generation guard and replaced on reconnect.
} catch (Exception e) { journal.event("disconnect.cleanup", e.getClass().getSimpleName()); }
});
remote = null; callbacks.clear(); journal.failPending("Bridge disconnected");
if (connection != null) { try { context.unbindService(connection); } catch (IllegalArgumentException ignored) {} connection = null; }
heartbeat = rpc = messages = link = auth = null; authorized = false; state = "disconnected";
}
void close() { closing = true; disconnectNow(); main.removeCallbacksAndMessages(null); worker.shutdown(); }
}
@@ -0,0 +1,6 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="48dp" android:height="48dp" android:viewportWidth="48" android:viewportHeight="48">
<path android:fillColor="#13283F" android:pathData="M0,0h48v48h-48z" />
<path android:fillColor="#83DDD4" android:pathData="M7,10h14v28h-14zM29,15h13v18h-13z" />
<path android:fillColor="#13283F" android:pathData="M10,14h8v18h-8zM32,18h7v12h-7z" />
<path android:fillColor="#FFFFFF" android:pathData="M21,22h8v4h-8z" />
</vector>
@@ -0,0 +1,4 @@
<data-extraction-rules>
<cloud-backup><exclude domain="root" path="." /></cloud-backup>
<device-transfer><exclude domain="root" path="." /></device-transfer>
</data-extraction-rules>
+196
查看文件
@@ -0,0 +1,196 @@
"""PC control for the RTOS phone bridge. Uses only Python's standard library."""
import argparse
import hashlib
import json
from pathlib import Path
import subprocess
import sys
import time
import urllib.error
import urllib.request
PACKAGE = 'com.sydxky.rtos.bridge'
class Bridge:
def __init__(self, serial=None, port=18765, adb='adb'):
self.adb = [adb] + (['-s', serial] if serial else [])
self.port = port
self.token = None
self.opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))
def shell(self, *args):
result = subprocess.run(self.adb + list(args), capture_output=True, text=True,
encoding='utf-8', errors='replace', timeout=45)
if result.returncode:
raise RuntimeError(result.stderr.strip() or result.stdout.strip())
return result.stdout.strip()
def prepare(self, launch=True):
if launch:
self.shell('shell', 'am', 'start', '-n', PACKAGE + '/.MainActivity')
self.shell('forward', f'tcp:{self.port}', 'tcp:18765')
for _ in range(20):
try:
token = self.shell('shell', 'run-as', PACKAGE, 'cat', 'files/bridge-token')
if len(token) != 43 or any(c not in 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_' for c in token):
raise RuntimeError('Bridge token not available; install and open the debug APK')
self.token = token
self.request('GET', '/status')
return
except (RuntimeError, OSError):
time.sleep(.3)
raise RuntimeError('Bridge unavailable. Unlock the phone and open RTOS 真机调试桥.')
def request(self, method, path, data=None, headers=None):
if data is not None and not isinstance(data, bytes):
data = json.dumps(data, ensure_ascii=False).encode('utf-8')
auth = {'Authorization': 'Bearer ' + self.token, 'Content-Type': 'application/json'}
auth.update(headers or {})
req = urllib.request.Request(f'http://127.0.0.1:{self.port}' + path, data=data, headers=auth, method=method)
try:
with self.opener.open(req, timeout=35) as response:
return json.load(response)
except urllib.error.HTTPError as error:
raise RuntimeError(f'Bridge HTTP {error.code}: {error.read().decode("utf-8", errors="replace")}') from None
def connect(self, app_id='test', license_value='test', service='com.heytap.health'):
self.request('POST', '/connect', {'appId': app_id, 'license': license_value, 'service': service})
for _ in range(75):
result = self.request('GET', '/status')
if result['state'] == 'bound':
return result
if result['state'] in ('failed', 'service_not_found', 'bind_rejected', 'null_binding', 'bind_timeout'):
hint = ' Open the paired health app, then retry connect.' if result['state'] == 'bind_rejected' else ''
raise RuntimeError('Wear Engine binding failed: ' + json.dumps(result, ensure_ascii=False) + hint)
time.sleep(.2)
raise TimeoutError('Service binding timed out. See events for details.')
def command(self, args, timeout=180):
job = self.request('POST', '/command', args)
started = time.monotonic()
while time.monotonic() - started < timeout:
result = self.request('GET', '/jobs/' + job['id'])
if result['state'] != 'pending':
return result
time.sleep(.35)
return {'id': job['id'], 'state': 'timeout', 'result': 'Watch operation may still complete. Inspect job/events before retrying.'}
def wait_link(self, timeout=45):
"""Read-only wait: a bound Binder can precede the paired watch link."""
if not 1 <= timeout <= 120:
raise ValueError('Link wait must be 1-120 seconds')
deadline = time.monotonic() + timeout
while True:
result = self.command({'command': 'link'}, min(5, max(.1, deadline - time.monotonic())))
if result.get('state') != 'success' or result.get('result', {}).get('connected') is True:
return result
remaining = deadline - time.monotonic()
if remaining <= 0:
return result
time.sleep(min(1, remaining))
def upload(self, filename):
path = Path(filename)
if not 0 < path.stat().st_size <= 32 * 1024 * 1024:
raise ValueError('File must be 1 byte to 32 MiB')
data = path.read_bytes()
# Use a simple unique name, regardless of Unicode or spaces in the local path.
name = hashlib.sha256(data).hexdigest()[:24] + '.pkg'
result = self.request('PUT', '/files/' + name, data,
{'X-SHA256': hashlib.sha256(data).hexdigest(), 'Content-Type': 'application/octet-stream'})
if result['sha256'] != hashlib.sha256(data).hexdigest():
raise RuntimeError('Phone upload integrity mismatch')
return name
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--serial', help='ADB phone serial; required when more than one device is attached')
parser.add_argument('--port', type=int, default=18765)
parser.add_argument('--adb', default='adb')
parser.add_argument('--timeout', type=int, default=180)
sub = parser.add_subparsers(dest='action', required=True)
setup = sub.add_parser('setup', help='Install the debug APK and start the bridge')
setup.add_argument('--apk', default=str(Path(__file__).parent / 'artifacts/RTOS-Phone-Bridge-0.2.0-debug.apk'))
connect = sub.add_parser('connect')
connect.add_argument('--app-id', default='test')
connect.add_argument('--config', help='Local JSON with appId, license and optional service; keep credentials out of Git')
for action in ('status', 'info', 'link', 'disconnect', 'cleanup', 'stop'):
sub.add_parser(action)
sub.add_parser('wait-link', help='Wait for the paired watch after Health starts').add_argument('--seconds', type=int, default=45)
for action in ('check', 'launch'):
sub.add_parser(action).add_argument('package')
for action in ('install', 'send-file'):
child = sub.add_parser(action)
child.add_argument('file')
if action == 'send-file':
child.add_argument('--remote', required=True)
sub.add_parser('message').add_argument('message')
logs = sub.add_parser('logs')
logs.add_argument('enabled', choices=['on', 'off'])
rpc = sub.add_parser('rpc')
rpc.add_argument('method')
rpc.add_argument('--params', default='{}')
events = sub.add_parser('events')
events.add_argument('--after', type=int, default=0)
events.add_argument('--follow', action='store_true')
args = parser.parse_args()
bridge = Bridge(args.serial, args.port, args.adb)
if args.action == 'setup':
if not Path(args.apk).is_file():
parser.error('Build APK with build.ps1 or pass --apk')
bridge.shell('install', '-r', args.apk)
if args.action == 'stop':
bridge.shell('shell', 'am', 'force-stop', PACKAGE)
bridge.shell('forward', '--remove', f'tcp:{args.port}')
print('Bridge stopped; ADB forward removed.')
return
bridge.prepare()
if args.action in ('setup', 'status'):
result = bridge.request('GET', '/status')
elif args.action == 'connect':
config = json.loads(Path(args.config).read_text(encoding='utf-8')) if args.config else {'appId': args.app_id}
result = bridge.connect(config.get('appId', 'test'), config.get('license', 'test'), config.get('service', 'com.heytap.health'))
elif args.action in ('disconnect', 'cleanup'):
result = bridge.request('POST', '/' + args.action, {})
elif args.action == 'wait-link':
result = bridge.wait_link(args.seconds)
if result.get('state') != 'success' or result.get('result', {}).get('connected') is not True:
print(json.dumps(result, ensure_ascii=False, indent=2))
return 2
elif args.action == 'events':
cursor = args.after
while True:
result = bridge.request('GET', '/events?after=' + str(cursor))
for row in result['events']:
print(json.dumps(row, ensure_ascii=False), flush=True)
cursor = row['seq']
if not args.follow:
return
time.sleep(1)
else:
command = {'command': args.action}
if args.action in ('check', 'launch'): command['package'] = args.package
elif args.action in ('install', 'send-file'):
command['file'] = bridge.upload(args.file)
if args.action == 'send-file': command['remote'] = args.remote
elif args.action == 'message': command['message'] = args.message
elif args.action == 'logs': command['enabled'] = args.enabled == 'on'
elif args.action == 'rpc': command.update(method=args.method, params=args.params)
result = bridge.command(command, args.timeout)
print(json.dumps(result, ensure_ascii=False, indent=2))
if 'state' in result and result['state'] in ('failed', 'timeout'):
sys.exit(2)
if __name__ == '__main__':
sys.stdout.reconfigure(encoding='utf-8')
sys.stderr.reconfigure(encoding='utf-8')
try:
sys.exit(main())
except KeyboardInterrupt:
sys.exit(130)
except (OSError, RuntimeError, ValueError, subprocess.SubprocessError) as error:
print(str(error), file=sys.stderr)
sys.exit(1)
+1
查看文件
@@ -0,0 +1 @@
plugins { id 'com.android.application' version '8.13.1' apply false }
+19
查看文件
@@ -0,0 +1,19 @@
param(
[string]$JavaHome = $env:JAVA_HOME,
[string]$AndroidSdk = "$env:LOCALAPPDATA\Android\Sdk"
)
$ErrorActionPreference = 'Stop'
if ([string]::IsNullOrWhiteSpace($JavaHome)) { throw 'Set JAVA_HOME or pass -JavaHome with a JDK 17 installation.' }
$env:JAVA_HOME = $JavaHome
$env:ANDROID_HOME = $AndroidSdk
if (!(Test-Path -LiteralPath (Join-Path $JavaHome 'bin\java.exe'))) { throw 'Pass -JavaHome with a JDK 17 installation.' }
Push-Location $PSScriptRoot
try {
& '.\gradlew.bat' --no-daemon assembleDebug lintDebug
if ($LASTEXITCODE -ne 0) { throw "Android build failed ($LASTEXITCODE)" }
$apk = Join-Path $PSScriptRoot 'app\build\outputs\apk\debug\app-debug.apk'
$dest = Join-Path $PSScriptRoot 'artifacts\RTOS-Phone-Bridge-0.2.0-debug.apk'
New-Item -ItemType Directory -Force -Path (Split-Path $dest) | Out-Null
Copy-Item -LiteralPath $apk -Destination $dest -Force
Get-FileHash -LiteralPath $dest -Algorithm SHA256
} finally { Pop-Location }
@@ -0,0 +1,8 @@
{
"steps": [
{"action": "assert-visible", "by": "text", "value": "点击次数:0"},
{"action": "click", "by": "text", "value": "点击验证"},
{"action": "assert-visible", "by": "text", "value": "点击次数:1"},
{"action": "screenshot"}
]
}
+2
查看文件
@@ -0,0 +1,2 @@
org.gradle.jvmargs=-Xmx1536m -Dfile.encoding=UTF-8
org.gradle.workers.max=2
二进制文件未显示。
+8
查看文件
@@ -0,0 +1,8 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://mirrors.cloud.tencent.com/gradle/gradle-8.13-bin.zip
networkTimeout=120000
networkRetries=3
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
+91
查看文件
@@ -0,0 +1,91 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%\bin\java.exe
if exist "%JAVA_EXE%" goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell
if %ERRORLEVEL% equ 0 goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
+7
查看文件
@@ -0,0 +1,7 @@
pluginManagement { repositories { google(); mavenCentral(); gradlePluginPortal() } }
dependencyResolutionManagement {
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
repositories { google(); mavenCentral() }
}
rootProject.name = 'RtosPhoneBridge'
include ':app'
+98
查看文件
@@ -0,0 +1,98 @@
"""Verify ui.py against both native Glyphix emulator profiles (not a physical S2).
Build deviceprobe QuickApps first. Supply a compatible vendor global/launcher
image using --seed (or initialize the probe image). Never attaches to an
existing Inspector or terminates another user's emulator.
"""
import argparse
import hashlib
import json
from pathlib import Path
import shutil
import socket
import subprocess
import sys
import time
PROJECT = Path(__file__).resolve().parents[1]
ROOT = PROJECT.parent
sys.path.insert(0, str(PROJECT))
from ui import Inspector
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--output', required=True, type=Path)
parser.add_argument('--seed', type=Path, default=ROOT / 'com.sydxky.rtos.deviceprobe/.glyphix-work/image/generic-watch-466x466',
help='Initialized vendor image containing global/, global.pkg and apps/emulator.launcher.pkg')
args = parser.parse_args()
output = args.output.resolve()
output.mkdir(parents=True, exist_ok=True)
results = []
for shape, device in [('round', '466x466'), ('rect', '390x450')]:
with socket.socket() as sock:
if sock.connect_ex(('127.0.0.1', 14201)) == 0:
raise RuntimeError('Inspector port in use; will not attach to another runtime')
folder = output / shape
image = folder / 'image'
image.mkdir(parents=True, exist_ok=True)
seed = args.seed.resolve()
shutil.copytree(seed / 'global', image / 'global', dirs_exist_ok=True)
shutil.copy2(seed / 'global.pkg', image / 'global.pkg')
(image / 'apps').mkdir(exist_ok=True)
shutil.copy2(seed / 'apps/emulator.launcher.pkg', image / 'apps/emulator.launcher.pkg')
name = 'com.sydxky.rtos.deviceprobe'
package = ROOT / name / '.glyphix-work/dist' / ('generic-watch-' + device + '-quickapp') / name / 'bundle.pkg'
shutil.copy2(package, image / 'apps' / (name + '.pkg'))
(image / 'pkgs.db').write_text(json.dumps({'apps': {p: {'uri': 'pkg://' + p} for p in (name, 'emulator.launcher')}, 'dials': {}}), encoding='utf-8')
command = [str(ROOT / 'temp/glyphix-v0.7.2-windows-x64/bin/glyphix-emu.exe'), '--config', 'pkgs.db', '--target', name, '--inspector']
command += ['--width', '624', '--height', '624', '--dpi', '326', '--font-size', '32', '--round', '--surface', 'surface/surface-466x466.json'] if shape == 'round' else ['--width', '390', '--height', '450', '--dpi', '321', '--font-size', '29']
command += ['--memory-profile', '8192', '--font-map', 'font-faces', '--font-family', 'sans-serif']
client = Inspector('http://127.0.0.1:14201')
item = {'profile': shape, 'evidence_scope': 'native_emulator_not_S2', 'package_sha256': hashlib.sha256(package.read_bytes()).hexdigest(), 'passed': False}
results.append(item)
with open(folder / 'stdout.log', 'w', encoding='utf-8') as out, open(folder / 'stderr.log', 'w', encoding='utf-8') as err:
proc = subprocess.Popen(command, cwd=image, stdin=subprocess.PIPE, stdout=out, stderr=err, creationflags=subprocess.CREATE_NO_WINDOW)
try:
for _ in range(70):
if proc.poll() is not None:
raise RuntimeError('Emulator exited before Inspector startup')
try:
client.request('/logs')
break
except OSError:
time.sleep(.3)
else:
raise TimeoutError('Inspector did not start')
time.sleep(1)
item['before'] = client.screenshot(folder / 'before.png')
item['initial_visible'] = client.exists(('text', '点击次数:0'))
client.click(('text', '点击验证'))
item['after_visible'] = client.exists(('text', '点击次数:1'))
item['after'] = client.screenshot(folder / 'after.png')
plan = json.loads((PROJECT / 'examples/probe-inspector.json').read_text(encoding='utf-8'))
plan['steps'][0]['value'] = '点击次数:1'
plan['steps'][2]['value'] = '点击次数:2'
planfile = folder / 'plan.json'
planfile.write_text(json.dumps(plan, ensure_ascii=False), encoding='utf-8')
run = subprocess.run([sys.executable, str(PROJECT / 'ui.py'), '--target', 'inspector', '--inspector', client.base, 'run', str(planfile), '--output', str(folder / 'plan-results')], capture_output=True, timeout=90)
item['plan_exit'] = run.returncode
item['passed'] = item['initial_visible'] and item['after_visible'] and run.returncode == 0
if run.returncode:
raise RuntimeError(run.stderr.decode('utf-8', 'replace') or 'UI plan failed')
except Exception as error:
item['error'] = type(error).__name__
raise
finally:
if proc.poll() is None:
proc.terminate()
proc.wait(timeout=10)
proc.stdin.close()
(output / 'results.json').write_text(json.dumps(results, ensure_ascii=False, indent=2), encoding='utf-8')
print(json.dumps(item, ensure_ascii=True), flush=True)
time.sleep(2)
return 0 if all(item['passed'] for item in results) else 1
if __name__ == '__main__':
sys.exit(main())
+117
查看文件
@@ -0,0 +1,117 @@
"""Exercise the PC client against a real local HTTP socket, without Android."""
import importlib.util
import json
from pathlib import Path
import tempfile
import threading
import unittest
from unittest.mock import patch
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
spec = importlib.util.spec_from_file_location('bridge', Path(__file__).resolve().parents[1] / 'bridge.py')
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
class Handler(BaseHTTPRequestHandler):
def log_message(self, *_): pass
def handle_request(self):
length = int(self.headers.get('Content-Length', 0))
data = self.rfile.read(length)
self.server.requests.append((self.command, self.path, dict(self.headers), data))
if self.path == '/reject':
status, result = 401, {'error': 'Unauthorized'}
elif self.command == 'PUT':
status, result = 200, {'file': self.path.split('/')[-1], 'sha256': self.headers['X-SHA256']}
elif self.path == '/command':
status, result = 202, {'id': 'test-job'}
elif self.path == '/jobs/test-job':
status, result = 200, self.server.job_result
else:
status, result = 200, {'state': 'bound'}
body = json.dumps(result).encode()
self.send_response(status)
self.send_header('Content-Length', str(len(body)))
self.end_headers()
self.wfile.write(body)
do_GET = do_POST = do_PUT = handle_request
class ClientTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.server = ThreadingHTTPServer(('127.0.0.1', 0), Handler)
cls.server.requests = []
threading.Thread(target=cls.server.serve_forever, daemon=True).start()
@classmethod
def tearDownClass(cls):
cls.server.shutdown()
cls.server.server_close()
def setUp(self):
self.client = module.Bridge(port=self.server.server_port)
self.client.token = 'test-token'
self.server.requests.clear()
def test_unicode_message_survives_http(self):
self.server.job_result = {'state': 'success', 'result': {'code': 200}}
self.client.command({'command': 'message', 'message': 'S2 真机 🙂'})
method, path, headers, body = self.server.requests[0]
self.assertEqual(json.loads(body)['message'], 'S2 真机 🙂')
self.assertEqual(headers['Authorization'], 'Bearer test-token')
self.assertEqual((method, path), ('POST', '/command'))
def test_watch_failure_is_preserved(self):
self.server.job_result = {'state': 'failed', 'result': {'code': 5005, 'msg': 'invalid package'}}
result = self.client.command({'command': 'install', 'file': 'test.pkg'})
self.assertEqual(result['state'], 'failed')
self.assertEqual(result['result']['code'], 5005)
def test_timeout_keeps_job_for_inspection(self):
result = self.client.command({'command': 'info'}, timeout=0)
self.assertEqual(result['state'], 'timeout')
self.assertEqual(result['id'], 'test-job')
def test_binary_upload_hash_and_safe_name(self):
with tempfile.TemporaryDirectory() as tmp:
file = Path(tmp) / '中文 package.pkg'
data = bytes(range(256)) * 32
file.write_bytes(data)
name = self.client.upload(file)
request = self.server.requests[0]
self.assertEqual(request[3], data)
self.assertRegex(name, r'^[a-f0-9]{24}\.pkg$')
self.assertEqual(request[2]['X-Sha256'], module.hashlib.sha256(data).hexdigest())
def test_rejected_request_does_not_leak_token(self):
with self.assertRaises(RuntimeError) as ctx:
self.client.request('GET', '/reject')
self.assertIn('401', str(ctx.exception))
self.assertNotIn('test-token', str(ctx.exception))
def test_empty_upload_rejected_before_network(self):
with tempfile.TemporaryDirectory() as tmp:
file = Path(tmp) / 'empty.pkg'
file.touch()
with self.assertRaises(ValueError): self.client.upload(file)
self.assertEqual(self.server.requests, [])
def test_wait_link_allows_health_to_reconnect(self):
offline = {'state': 'success', 'result': {'connected': False}}
online = {'state': 'success', 'result': {'connected': True}}
with patch.object(self.client, 'command', side_effect=[offline, online]) as command, patch.object(module.time, 'sleep'):
self.assertEqual(self.client.wait_link(5), online)
self.assertEqual(command.call_count, 2)
self.assertTrue(all(call.args[0] == {'command': 'link'} for call in command.call_args_list))
def test_wait_link_does_not_repeat_failed_calls(self):
failed = {'state': 'failed', 'result': 'disconnected'}
with patch.object(self.client, 'command', return_value=failed) as command:
self.assertEqual(self.client.wait_link(5), failed)
command.assert_called_once()
if __name__ == '__main__': unittest.main()
+118
查看文件
@@ -0,0 +1,118 @@
import json
import base64
import struct
from pathlib import Path
import sys
import tempfile
import threading
import unittest
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import urlsplit
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from ui import Inspector, Phone, save_png, imported_watch_capture, jpeg_info, health_screenshot
class UIHandler(BaseHTTPRequestHandler):
def log_message(self, *_): pass
def do_GET(self):
self.server.paths.append(self.path)
if self.path == '/snapshot.json':
value = {'frames': [{'snapshot': 'frame.png'}]}
body = json.dumps(value).encode()
else:
body = b'broken PNG'
self.send_response(200)
self.send_header('Content-Length', str(len(body)))
self.end_headers()
self.wfile.write(body)
def do_POST(self):
self.server.paths.append(self.path)
body = b'{}'
self.send_response(200)
self.send_header('Content-Length', str(len(body)))
self.end_headers()
self.wfile.write(body)
class UiTests(unittest.TestCase):
@staticmethod
def jpeg_header(width=480, height=464):
# Minimal marker stream exercises metadata parsing, not a JPEG decoder.
return b'\xff\xd8\xff\xc0' + struct.pack('>HBHHB', 8, 8, height, width, 0) + b'\xff\xd9'
def test_watch_jpeg_dimensions_and_truncation(self):
data = self.jpeg_header()
self.assertEqual((jpeg_info(data)['width'], jpeg_info(data)['height']), (480, 464))
with self.assertRaises(ValueError): jpeg_info(data[:-1])
def test_official_numbered_jpeg_is_exported_with_real_extension(self):
data = self.jpeg_header()
class HealthPhone:
queries = 0
find = staticmethod(Phone.find)
def unlocked(self): pass
def click(self, selector): pass
def tree(self):
return '<hierarchy><node resource-id="com.heytap.health:id/device_settings_tv_screen_shot" enabled="true" bounds="[0,0][10,10]"/></hierarchy>'
def run(self, *args, binary=False):
if binary:
self.path = args[-1]
return data
if 'content query' in args[-1]:
self.queries += 1
return '' if self.queries == 1 else 'Row: 0 _id=9, _data=/storage/emulated/0/Pictures/com.heytap.health/screenshots/watch_screen_shot (2).jpeg, width=480, height=464, date_modified=100'
return ''
phone = HealthPhone()
with tempfile.TemporaryDirectory() as tmp:
result = health_screenshot(phone, Path(tmp) / 'watch.png')
self.assertEqual(Path(result['file']).suffix, '.jpg')
self.assertEqual(Path(result['file']).read_bytes(), data)
self.assertTrue(phone.path.endswith('watch_screen_shot (2).jpeg'))
def test_failed_inspector_image_always_resumes_runtime(self):
server = ThreadingHTTPServer(('127.0.0.1', 0), UIHandler)
server.paths = []
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
try:
client = Inspector('http://127.0.0.1:' + str(server.server_port))
with tempfile.TemporaryDirectory() as tmp:
dest = Path(tmp) / 'capture.png'
with self.assertRaises(ValueError): client.screenshot(dest)
self.assertFalse(dest.exists())
self.assertEqual(server.paths[-1], '/control?pause=false')
finally:
server.shutdown(); server.server_close(); thread.join()
def test_phone_ambiguous_selector_is_rejected(self):
xml = '<hierarchy><node text="安装" bounds="[0,0][20,20]"/><node text="安装" bounds="[30,0][50,20]"/></hierarchy>'
with self.assertRaises(ValueError): Phone.find(xml, ('text', '安装'))
def test_phone_hidden_node_is_not_selected(self):
self.assertIsNone(Phone.find('<hierarchy><node text="隐藏" bounds="[0,0][0,0]"/></hierarchy>', ('text', '隐藏')))
self.assertIsNone(Phone.find('<hierarchy><node text="隐藏" visible-to-user="false" bounds="[0,0][20,20]"/></hierarchy>', ('text', '隐藏')))
def test_import_integrity_failure_does_not_write_capture(self):
class ImportedPhone:
def run(self, *args, binary=False):
return base64.b64decode('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aL1sAAAAASUVORK5CYII=') if binary else '{"sha256":"wrong"}'
with tempfile.TemporaryDirectory() as tmp:
dest = Path(tmp) / 'watch.png'
with self.assertRaises(ValueError): imported_watch_capture(ImportedPhone(), dest)
self.assertFalse(dest.exists())
def test_inspector_is_explicit_loopback(self):
for url in ('https://example.com', 'http://10.0.0.1', 'http://user:secret@localhost'):
with self.assertRaises(ValueError): Inspector(url)
def test_no_phone_image_fallback_on_capture_failure(self):
with tempfile.TemporaryDirectory() as tmp:
dest = Path(tmp) / 'watch.png'
with self.assertRaises(ValueError): save_png(dest, b'<html>failure</html>')
self.assertFalse(dest.exists())
if __name__ == '__main__': unittest.main()
+38
查看文件
@@ -0,0 +1,38 @@
"""Verification reports must preserve failure and omit device identifiers."""
import json
from pathlib import Path
import sys
import unittest
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from verify import safe_watch_info, watch_success
class VerificationTests(unittest.TestCase):
def test_nested_info_keeps_versions_and_omits_identifiers(self):
result = {'code': 200, 'values': json.dumps({
'model': 'S2', 'runtimeVersion': '0.7', 'deviceCode': 'private-device-id',
'mac': 'private-mac', 'license': 'private-license',
'firmwareVersion': {'serial': 'private-serial'}})}
self.assertEqual(safe_watch_info(result), {'model': 'S2', 'runtimeVersion': '0.7'})
def test_empty_callback_does_not_invent_a_model(self):
self.assertEqual(safe_watch_info({'code': 200, 'values': ''}), {})
def test_oww265_msg_envelope_is_redacted(self):
result = {'code': 200, 'values': '', 'msg': json.dumps({
'brand': 'OPPO', 'model': 'OWW265', 'masVersion': 2006005,
'runtimeVersion': '0.8.0-5', 'nucleusVersion': '0.8.0-229',
'mac': 'private-mac', 'uuid': 'private-uuid', 'vendorId': 1})}
self.assertEqual(safe_watch_info(result), {
'brand': 'OPPO', 'model': 'OWW265', 'masVersion': 2006005,
'runtimeVersion': '0.8.0-5', 'nucleusVersion': '0.8.0-229'})
def test_watch_error_is_not_success_even_with_success_state(self):
self.assertFalse(watch_success({'state': 'success', 'result': {'code': 4008}}))
self.assertFalse(watch_success({'state': 'timeout', 'result': {'code': 200}}))
self.assertTrue(watch_success({'state': 'success', 'result': {'code': 200}}))
if __name__ == '__main__':
unittest.main()
+421
查看文件
@@ -0,0 +1,421 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
==============================================================================
Licenses for included components:
------------------------------------------------------------------------------
Eclipse Public License 1.0
https://opensource.org/licenses/EPL-1.0
junit:junit
org.sonatype.aether:aether-api
org.sonatype.aether:aether-connector-wagon
org.sonatype.aether:aether-impl
org.sonatype.aether:aether-spi
org.sonatype.aether:aether-util
------------------------------------------------------------------------------
3-Clause BSD
https://opensource.org/licenses/BSD-3-Clause
com.google.code.findbugs:jsr305
org.hamcrest:hamcrest-core
BSD License
Copyright (c) 2000-2015 www.hamcrest.org
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list of
conditions and the following disclaimer. Redistributions in binary form must reproduce
the above copyright notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
Neither the name of Hamcrest nor the names of its contributors may be used to endorse
or promote products derived from this software without specific prior written
permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY
WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
DAMAGE.
com.esotericsoftware.kryo:kryo
com.esotericsoftware.minlog:minlog
Copyright (c) 2008-2018, Nathan Sweet All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
Neither the name of Esoteric Software nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
org.ow2.asm:asm
org.ow2.asm:asm-analysis
org.ow2.asm:asm-commons
org.ow2.asm:asm-tree
org.ow2.asm:asm-util
ASM: a very small and fast Java bytecode manipulation framework
Copyright (c) 2000-2011 INRIA, France Telecom
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holders nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
THE POSSIBILITY OF SUCH DAMAGE.
------------------------------------------------------------------------------
MIT
com.googlecode.plist:dd-plist
dd-plist - An open source library to parse and generate property lists
Copyright (C) 2016 Daniel Dreibrodt
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
org.bouncycastle:bcpg-jdk15on
org.bouncycastle:bcprov-jdk15on
Copyright (c) 2000 - 2019 The Legion of the Bouncy Castle Inc. (https://www.bouncycastle.org)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
org.slf4j:jcl-over-slf4j
org.slf4j:jul-to-slf4j
org.slf4j:log4j-over-slf4j
org.slf4j:slf4j-api
Copyright (c) 2004-2017 QOS.ch
All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
------------------------------------------------------------------------------
CDDL
https://opensource.org/licenses/CDDL-1.0
com.sun.xml.bind:jaxb-impl
------------------------------------------------------------------------------
LGPL 2.1
https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html
org.samba.jcifs:jcifs
org.jetbrains.intellij.deps:trove4j
------------------------------------------------------------------------------
License for the GNU Trove library included by the Kotlin embeddable compiler
------------------------------------------------------------------------------
The source code for GNU Trove is licensed under the Lesser GNU Public License (LGPL).
Copyright (c) 2001, Eric D. Friedman All Rights Reserved. This library is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
Two classes (HashFunctions and PrimeFinder) included in Trove are licensed under the following terms:
Copyright (c) 1999 CERN - European Organization for Nuclear Research. Permission to use, copy, modify, distribute and sell this software
and its documentation for any purpose is hereby granted without fee, provided that the above copyright notice appear in all copies and
that both that copyright notice and this permission notice appear in supporting documentation. CERN makes no representations about the
suitability of this software for any purpose. It is provided "as is" without expressed or implied warranty.
The source code of modified GNU Trove library is available at
https://github.com/JetBrains/intellij-deps-trove4j (with trove4j_changes.txt describing the changes)
------------------------------------------------------------------------------
Eclipse Distribution License 1.0
https://www.eclipse.org/org/documents/edl-v10.php
org.eclipse.jgit:org.eclipse.jgit
------------------------------------------------------------------------------
BSD-style
com.jcraft:jzlib
com.github.mwiede:jsch
Copyright (c) 2002-2015 Atsuhiko Yamanaka, JCraft,Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
3. The names of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
------------------------------------------------------------------------------
Eclipse Public License 2.0
https://www.eclipse.org/legal/epl-2.0/
org.junit.platform:junit-platform-launcher
------------------------------------------------------------------------------
Mozilla Public License 2.0
https://www.mozilla.org/en-US/MPL/2.0/
org.mozilla:rhino
+21
查看文件
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 chengchengking
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+397
查看文件
@@ -0,0 +1,397 @@
"""Explicit-target screenshot, UI inspection and test runner (Python standard library).
phone = Android phone via ADB; watch-health = official paired-watch screenshot;
watch-import = image selected in the phone APK; inspector = explicitly supplied
Glyphix Inspector endpoint, whose device identity must be verified separately.
"""
import argparse
from datetime import datetime, timezone, timedelta
import hashlib
import json
from pathlib import Path
import re
import struct
import subprocess
import sys
import time
import urllib.parse
import urllib.request
import xml.etree.ElementTree as ET
PACKAGE = 'com.sydxky.rtos.bridge'
HEALTH = 'com.heytap.health'
PNG = b'\x89PNG\r\n\x1a\n'
def png_info(data):
if len(data) < 33 or data[:8] != PNG or data[12:16] != b'IHDR':
raise ValueError('Capture did not return a PNG')
width, height = struct.unpack('>II', data[16:24])
if not 1 <= width <= 8192 or not 1 <= height <= 8192:
raise ValueError('Invalid capture dimensions')
return {'width': width, 'height': height, 'sha256': hashlib.sha256(data).hexdigest()}
def save_png(path, data):
info = png_info(data)
path = Path(path)
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(data)
return dict(info, file=str(path.resolve()))
def jpeg_info(data):
if not data.startswith(b'\xff\xd8') or not data.endswith(b'\xff\xd9'):
raise ValueError('Capture did not return a complete JPEG')
offset = 2
while offset + 4 <= len(data):
if data[offset] != 255:
raise ValueError('Invalid JPEG marker')
while offset < len(data) and data[offset] == 255:
offset += 1
marker = data[offset]
offset += 1
if marker in (0xDA, 0xD9):
break
size = int.from_bytes(data[offset:offset + 2], 'big')
if size < 2 or offset + size > len(data):
raise ValueError('Invalid JPEG segment')
if marker in (0xC0, 0xC1, 0xC2, 0xC3, 0xC5, 0xC6, 0xC7, 0xC9, 0xCA, 0xCB, 0xCD, 0xCE, 0xCF):
if size < 8:
break
height, width = struct.unpack('>HH', data[offset + 3:offset + 7])
if not 1 <= width <= 8192 or not 1 <= height <= 8192:
break
return {'width': width, 'height': height, 'format': 'JPEG', 'sha256': hashlib.sha256(data).hexdigest()}
offset += size
raise ValueError('JPEG dimensions not found')
def save_watch_image(path, data):
if data.startswith(PNG):
info, suffixes = png_info(data), ('.png',)
else:
info, suffixes = jpeg_info(data), ('.jpg', '.jpeg')
path = Path(path)
if path.suffix.lower() not in suffixes:
path = path.with_suffix(suffixes[0])
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(data)
return dict(info, file=str(path.resolve()))
class Phone:
scope = 'android_phone_ui'
def __init__(self, serial, adb='adb'):
if not serial:
raise ValueError('--serial is required for an ADB target')
self.adb = [adb, '-s', serial]
def run(self, *args, binary=False, timeout=35):
r = subprocess.run(self.adb + list(args), capture_output=True, timeout=timeout)
if r.returncode:
raise RuntimeError(r.stderr.decode('utf-8', 'replace').strip() or 'ADB operation failed')
return r.stdout if binary else r.stdout.decode('utf-8', 'replace').strip()
def unlocked(self):
policy = self.run('shell', 'dumpsys', 'window', 'policy')
if re.search(r'\bshowing=true|mIsShowing=true|mInputRestricted=true', policy):
raise RuntimeError('Unlock the phone locally, then retry. UI automation does not unlock credentials.')
def tree(self):
self.unlocked()
self.run('shell', 'uiautomator', 'dump', '/data/local/tmp/rtos-ui.xml')
root = ET.fromstring(self.run('shell', 'cat', '/data/local/tmp/rtos-ui.xml'))
for node in root.iter('node'):
if node.get('password') == 'true':
node.set('text', '[redacted]')
node.set('content-desc', '[redacted]')
return ET.tostring(root, encoding='unicode')
def screenshot(self, path):
self.unlocked()
return save_png(path, self.run('exec-out', 'screencap', '-p', binary=True))
@staticmethod
def find(tree, selector):
matches = []
if selector[0] not in ('id', 'text', 'description'):
raise ValueError('Phone UI selectors support id, text or description')
for node in ET.fromstring(tree).iter('node'):
key, value = selector
attribute = {'id': 'resource-id', 'text': 'text', 'description': 'content-desc'}[key]
bounds = list(map(int, re.findall(r'-?\d+', node.get('bounds', ''))))
visible = len(bounds) == 4 and bounds[2] > bounds[0] and bounds[3] > bounds[1] and node.get('visible-to-user') != 'false'
if node.get(attribute) == value and visible:
matches.append(node)
if len(matches) > 1:
raise ValueError('UI selector is ambiguous; use a unique resource id or visible text')
return matches[0] if matches else None
def click(self, selector):
node = self.find(self.tree(), selector)
if node is None or node.get('enabled') != 'true':
raise ValueError('Enabled UI element not found')
x1, y1, x2, y2 = map(int, re.findall(r'-?\d+', node.get('bounds', '')))
self.run('shell', 'input', 'tap', str((x1 + x2) // 2), str((y1 + y2) // 2))
def scroll(self, selector, dx, dy):
node = self.find(self.tree(), selector)
if node is None:
raise ValueError('UI element not found')
x1, y1, x2, y2 = map(int, re.findall(r'-?\d+', node.get('bounds', '')))
x, y = (x1 + x2) // 2, (y1 + y2) // 2
self.run('shell', 'input', 'swipe', str(x), str(y),
str(max(x1 + 1, min(x2 - 1, x + dx))),
str(max(y1 + 1, min(y2 - 1, y + dy))), '500')
def exists(self, selector):
return self.find(self.tree(), selector) is not None
class Inspector:
scope = 'glyphix_inspector_endpoint_identity_not_attested'
def __init__(self, url):
parsed = urllib.parse.urlsplit(url or '')
if parsed.scheme != 'http' or parsed.hostname not in ('127.0.0.1', 'localhost') or parsed.username or parsed.password:
raise ValueError('--inspector must be an explicit loopback HTTP URL; forward a device endpoint locally first')
self.base = url.rstrip('/')
self.opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))
def request(self, path, params=None, method='GET', binary=False):
suffix = '?' + urllib.parse.urlencode(params) if params else ''
req = urllib.request.Request(self.base + path + suffix, method=method)
with self.opener.open(req, timeout=15) as response:
data = response.read(8 * 1024 * 1024 + 1)
if len(data) > 8 * 1024 * 1024:
raise ValueError('Inspector response exceeds 8 MiB')
if binary:
return data
try:
return json.loads(data)
except (ValueError, UnicodeDecodeError):
return data.decode('utf-8', 'replace')
def snapshot(self, image=None):
try:
tree = self.request('/snapshot.json')
if image:
name = tree['frames'][-1]['snapshot']
if not isinstance(name, str) or not re.fullmatch(r'[A-Za-z0-9_.-]+', name):
raise ValueError('Invalid Inspector snapshot name')
result = save_png(image, self.request('/snapshot/' + name, binary=True))
Path(image).with_suffix('.tree.json').write_text(json.dumps(tree, ensure_ascii=False, indent=2), encoding='utf-8')
return result
return tree
finally:
# Snapshot pauses the runtime. Always resume, including image/JSON errors.
self.request('/control', {'pause': 'false'}, 'POST')
def tree(self):
return self.snapshot()
def screenshot(self, path):
return self.snapshot(path)
@staticmethod
def locator(selector):
key, value = selector
if key not in ('id', 'text', 'tag', 'class') or not value or len(value) > 200:
raise ValueError('Use id, text, tag or class with 1-200 characters')
if key == 'text':
# Escape regex syntax as literal text; never concatenate executable user code.
pattern = '^' + re.sub(r'([\\.^$*+?{}\[\]|()])', r'\\\1', value) + '$'
expression = 'getHasText(new RegExp(' + json.dumps(pattern, ensure_ascii=True) + '))'
else:
expression = {'id': 'getById', 'tag': 'getByTag', 'class': 'getByClass'}[key] + '(' + json.dumps(value, ensure_ascii=True) + ')'
return "require('@system.test').default." + expression
def action(self, selector, method):
# Public Locator methods return promises. Poll only our tagged completion event.
tag = 'RTOS_UI_' + __import__('uuid').uuid4().hex
script = '(' + self.locator(selector) + ').' + method + ".then(function(){console.log('" + tag + "_PASS')},function(){console.log('" + tag + "_FAIL')})"
self.request('/fn/eval', {'lang': 'js', 'script': script}, 'POST')
deadline = time.monotonic() + 15
while time.monotonic() < deadline:
for row in self.request('/logs'):
if row.get('tag') == 'eval':
continue
body = row.get('body', '')
if tag + '_FAIL' in body:
raise RuntimeError('Glyphix UI action failed')
if tag + '_PASS' in body:
return
time.sleep(.15)
raise TimeoutError('No Glyphix UI completion marker; inspect the endpoint and target')
def click(self, selector):
self.action(selector, 'click()')
def scroll(self, selector, dx, dy):
self.action(selector, 'scroll(' + str(int(dx)) + ',' + str(int(dy)) + ',0.5)')
def exists(self, selector):
try:
self.action(selector, 'wait()')
return True
except (RuntimeError, TimeoutError):
return False
def imported_watch_capture(phone, path):
metadata = json.loads(phone.run('shell', 'run-as', PACKAGE, 'cat', 'files/ui/watch-capture.json'))
data = phone.run('exec-out', 'run-as', PACKAGE, 'cat', 'files/ui/watch-capture.png', binary=True)
if png_info(data)['sha256'] != metadata['sha256']:
raise ValueError('Imported capture integrity mismatch')
result = save_png(path, data)
return dict(result, provenance=metadata)
def health_screenshot(phone, path):
"""Navigate the official UI. Do not call its non-exported activities or private services."""
phone.unlocked()
# Health may reuse an id or add numbered filenames. Track content as well
# as modification time; public images outside its directory are ignored.
def captures():
rows = phone.run('shell', 'content query --uri content://media/external/images/media --projection _id:_data:width:height:date_modified')
images = {}
for row in rows.splitlines():
match = re.search(r'_id=(\d+), _data=((?:/storage/emulated/0|/sdcard)/Pictures/com\.heytap\.health/screenshots/watch_screen_shot(?: \(\d+\))?\.(?:jpeg|jpg|png)), width=(\d+), height=(\d+), date_modified=(\d+)', row)
if not match:
continue
image_id, remote, width, height, modified = match.groups()
if not all(200 <= int(value) <= 1024 for value in (width, height)):
continue
# The content read subcommand is rejected on this P30PRO provider;
# ADB can read the exact public file without changing permissions.
try:
data = phone.run('exec-out', 'cat', remote, binary=True)
info = png_info(data) if data.startswith(PNG) else jpeg_info(data)
except (ValueError, RuntimeError):
continue # File may be mid-write while Health saves it.
images[image_id] = (modified, info['sha256'], data)
return images
before = captures()
phone.run('shell', 'am', 'start', '-n', HEALTH + '/.oobe.LaunchActivity')
device_selected = False
for _ in range(12):
tree = phone.tree()
button = ('id', HEALTH + ':id/device_settings_tv_screen_shot')
if phone.find(tree, button) is not None:
phone.click(button)
break
for selector in (('text', '暂不'), ('text', '手表截屏'), ('text', '更多功能')):
if phone.find(tree, selector) is not None:
phone.click(selector)
break
else:
selector = ('id', HEALTH + ':id/app_navigation_manager')
if not device_selected and phone.find(tree, selector) is not None:
phone.click(selector)
device_selected = True
elif device_selected:
# Use current display dimensions, avoiding the system navigation edge.
sizes = re.findall(r'(\d+)x(\d+)', phone.run('shell', 'wm', 'size'))
w, h = map(int, sizes[-1])
phone.run('shell', 'input', 'swipe', str(w // 2), str(h * 4 // 5), str(w // 2), str(h // 3), '500')
else:
raise RuntimeError('Open the paired device page in the health app, then retry')
time.sleep(.6)
else:
raise RuntimeError('Official watch screenshot control not found; no screenshot was captured')
deadline = time.monotonic() + 50
while time.monotonic() < deadline:
for image_id, (modified, sha, data) in captures().items():
if image_id not in before or (modified, sha) != before[image_id][:2]:
return dict(save_watch_image(path, data), provenance='official_health_ui_watch_screenshot')
time.sleep(1)
raise TimeoutError('No new watch screenshot image was exported. In the APK, select the official screenshot and use watch-import.')
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--target', required=True, choices=['phone', 'watch-health', 'watch-import', 'inspector'])
parser.add_argument('--serial')
parser.add_argument('--adb', default='adb')
parser.add_argument('--inspector', help='Explicit locally forwarded Glyphix Inspector endpoint')
sub = parser.add_subparsers(dest='command', required=True)
sub.add_parser('capabilities')
sub.add_parser('screenshot').add_argument('--output', type=Path, required=True)
sub.add_parser('tree').add_argument('--output', type=Path, required=True)
for name in ('click', 'scroll', 'assert-visible'):
p = sub.add_parser(name)
p.add_argument('--by', required=True, choices=['id', 'text', 'description', 'tag', 'class'])
p.add_argument('--value', required=True)
if name == 'scroll':
p.add_argument('--dx', type=int, default=0)
p.add_argument('--dy', type=int, required=True)
p = sub.add_parser('run')
p.add_argument('plan', type=Path)
p.add_argument('--output', type=Path, required=True)
args = parser.parse_args()
result = {'time': datetime.now(timezone(timedelta(hours=8))).isoformat(), 'target': args.target}
if args.command == 'capabilities':
result.update(screenshot_implemented=True, ui_tree_implemented=args.target in ('phone', 'inspector'),
control_implemented=args.target in ('phone', 'inspector'),
availability='conditional_on_selected_backend_and_target_connection',
note='Inspector requires a reachable runtime endpoint; Wear Engine 263 alone does not expose this endpoint.')
print(json.dumps(result, ensure_ascii=False, indent=2))
return
backend = Inspector(args.inspector) if args.target == 'inspector' else Phone(args.serial, args.adb)
if args.target in ('watch-health', 'watch-import'):
if args.command != 'screenshot':
raise ValueError('This watch backend supports screenshot only. General watch control requires a confirmed Inspector endpoint.')
result.update((health_screenshot if args.target == 'watch-health' else imported_watch_capture)(backend, args.output))
elif args.command == 'screenshot':
result.update(backend.screenshot(args.output), evidence_scope=backend.scope)
elif args.command == 'tree':
tree = backend.tree()
args.output.parent.mkdir(parents=True, exist_ok=True)
args.output.write_text(tree if isinstance(tree, str) else json.dumps(tree, ensure_ascii=False, indent=2), encoding='utf-8')
result.update(file=str(args.output.resolve()), evidence_scope=backend.scope)
elif args.command == 'run':
plan = json.loads(args.plan.read_text(encoding='utf-8'))
steps = plan.get('steps', [])
if not 1 <= len(steps) <= 50:
raise ValueError('Test plan must contain 1-50 steps')
args.output.mkdir(parents=True, exist_ok=True)
result.update(evidence_scope=backend.scope, steps=[], passed=True)
for index, step in enumerate(steps):
entry = {'index': index, 'action': step.get('action'), 'passed': False}
try:
selector = (step.get('by'), step.get('value'))
if step['action'] == 'click': backend.click(selector)
elif step['action'] == 'scroll': backend.scroll(selector, max(-2000, min(2000, int(step.get('dx', 0)))), max(-2000, min(2000, int(step.get('dy', 0)))))
elif step['action'] == 'assert-visible':
if not backend.exists(selector): raise AssertionError('UI element not visible')
elif step['action'] == 'screenshot': entry['capture'] = backend.screenshot(args.output / (str(index) + '.png'))
else: raise ValueError('Unsupported test action')
entry['passed'] = True
except Exception as error:
entry['error'] = type(error).__name__
result['passed'] = False
result['steps'].append(entry)
if not entry['passed']: break
(args.output / 'report.json').write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding='utf-8')
else:
selector = (args.by, args.value)
if args.command == 'click': backend.click(selector)
elif args.command == 'scroll': backend.scroll(selector, args.dx, args.dy)
elif not backend.exists(selector): raise AssertionError('UI element not visible')
result.update(passed=True, evidence_scope=backend.scope)
print(json.dumps(result, ensure_ascii=False, indent=2))
if result.get('passed') is False: return 2
return 0
if __name__ == '__main__':
sys.stdout.reconfigure(encoding='utf-8')
sys.stderr.reconfigure(encoding='utf-8')
try:
sys.exit(main())
except (OSError, ValueError, RuntimeError, AssertionError, subprocess.SubprocessError) as error:
print(str(error), file=sys.stderr)
sys.exit(1)
+136
查看文件
@@ -0,0 +1,136 @@
"""Verify the actual phone/watch chain and save a report without bearer tokens or raw watch logs."""
import argparse
import hashlib
import json
from pathlib import Path
import sys
import time
import urllib.error
import urllib.request
from datetime import datetime, timezone, timedelta
from bridge import Bridge
def safe_watch_info(result):
"""Keep explicit model/version fields even when the service nests values as JSON."""
allowed = {'brand', 'model', 'deviceModel', 'device_model', 'version', 'runtime',
'runtimeVersion', 'runtime_version', 'nucleus', 'nucleusVersion',
'nucleus_version', 'firmwareVersion', 'firmware_version', 'osVersion',
'osVersionName', 'masVersion'}
safe = {}
pending = [result]
for _ in range(12):
if not pending:
break
result = pending.pop(0)
if isinstance(result, str):
try:
result = json.loads(result)
except (ValueError, TypeError):
continue
if not isinstance(result, dict):
continue
for key, value in result.items():
if key in allowed and isinstance(value, (str, int, float)):
safe[key] = value
# OWW265 puts its JSON object in msg while values is an empty string.
# Only traverse these two envelopes and retain the same explicit fields.
pending.extend(result.get(key) for key in ('values', 'msg') if key in result)
return safe
def watch_success(job):
result = job.get('result')
return job.get('state') == 'success' and (not isinstance(result, dict) or result.get('code', 200) == 200)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--serial', required=True)
parser.add_argument('--probe', type=Path, help='Built com.sydxky.rtos.deviceprobe bundle.pkg; installs this package on the watch')
parser.add_argument('--output', type=Path, required=True)
parser.add_argument('--config', type=Path, help='Local appId/license JSON; never copied to report')
parser.add_argument('--ready-wait', type=int, default=30, help='Seconds to wait for the probe ready log (1-300)')
args = parser.parse_args()
if not 1 <= args.ready_wait <= 300:
parser.error('--ready-wait must be 1-300 seconds')
report = {'time': datetime.now(timezone(timedelta(hours=8))).isoformat(), 'steps': []}
bridge = Bridge(args.serial)
def record(name, passed, evidence):
report['steps'].append({'name': name, 'passed': bool(passed), 'evidence': evidence})
print(f'{name}: {"PASS" if passed else "FAIL"}', flush=True)
try:
bridge.prepare()
phone = bridge.shell('shell', 'getprop', 'ro.product.model')
api = bridge.shell('shell', 'getprop', 'ro.build.version.sdk')
report['phone'] = {'model': phone, 'androidApi': api}
record('phone_api', True, bridge.request('GET', '/status'))
for name, headers in [('missing_token', {}), ('browser_origin', {'Authorization': 'Bearer ' + bridge.token, 'Origin': 'http://example.invalid'})]:
request = urllib.request.Request('http://127.0.0.1:18765/status', headers=headers)
try:
with bridge.opener.open(request, timeout=5) as response: code = response.status
except urllib.error.HTTPError as error: code = error.code
record(name, code == 401, {'http': code})
config = json.loads(args.config.read_text(encoding='utf-8')) if args.config else {}
try:
status = bridge.connect(config.get('appId', 'test'), config.get('license', 'test'), config.get('service', 'com.heytap.health'))
except Exception:
status = bridge.request('GET', '/status')
record('wear_engine_binding', False, {'state': status.get('state')})
raise
record('wear_engine_binding', status['state'] == 'bound', status)
link = bridge.wait_link(45)
connected = watch_success(link) and link.get('result', {}).get('connected') is True
record('watch_connected', connected, link)
if not connected:
raise RuntimeError('Watch is offline; wake it before testing installation')
info = bridge.command({'command': 'info'}, 30)
# Only retain software/model fields; do not publish device identifiers from the callback.
record('watch_info_callback', watch_success(info), {'state': info['state'], 'result': safe_watch_info(info.get('result'))})
if args.probe:
report['probe_sha256'] = hashlib.sha256(args.probe.read_bytes()).hexdigest()
cursor = max((row['seq'] for row in bridge.request('GET', '/events?after=0')['events']), default=0)
logs = bridge.command({'command': 'logs', 'enabled': True}, 30)
record('rpc_logs_enable', watch_success(logs), logs)
try:
upload = bridge.upload(args.probe)
install = bridge.command({'command': 'install', 'file': upload})
record('watch_install_callback', watch_success(install), install)
if watch_success(install):
launch = bridge.command({'command': 'launch', 'package': 'com.sydxky.rtos.deviceprobe'}, 30)
record('watch_launch_callback', watch_success(launch), launch)
markers = []
deadline = time.monotonic() + args.ready_wait
while time.monotonic() < deadline:
rows = bridge.request('GET', '/events?after=' + str(cursor))['events']
for row in rows:
cursor = row['seq']
if row['type'] == 'watch.log' and 'RTOS_DEVICE_PROBE_' in str(row['data']):
# The marker carries no user content. Omit the rest of the log envelope.
text = str(row['data'])
for marker in ('RTOS_DEVICE_PROBE_APP_CREATE_V1', 'RTOS_DEVICE_PROBE_APP_SHOW_V1', 'RTOS_DEVICE_PROBE_READY_V1'):
if marker in text and marker not in markers: markers.append(marker)
if 'RTOS_DEVICE_PROBE_READY_V1' in markers: break
time.sleep(.5)
record('watch_page_ready_log', 'RTOS_DEVICE_PROBE_READY_V1' in markers, markers)
finally:
off = bridge.command({'command': 'logs', 'enabled': False}, 20)
record('rpc_logs_disable', watch_success(off), off)
report['passed'] = all(step['passed'] for step in report['steps'])
except Exception as error:
report['passed'] = False
# Never print config, token or raw transport payloads here.
report['error'] = type(error).__name__
print('Verification incomplete: ' + type(error).__name__, file=sys.stderr)
finally:
args.output.parent.mkdir(parents=True, exist_ok=True)
args.output.write_text(json.dumps(report, ensure_ascii=False, indent=2) + '\n', encoding='utf-8')
return 0 if report['passed'] else 2
if __name__ == '__main__':
sys.stdout.reconfigure(encoding='utf-8')
sys.stderr.reconfigure(encoding='utf-8')
sys.exit(main())
+421
查看文件
@@ -0,0 +1,421 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
==============================================================================
Licenses for included components:
------------------------------------------------------------------------------
Eclipse Public License 1.0
https://opensource.org/licenses/EPL-1.0
junit:junit
org.sonatype.aether:aether-api
org.sonatype.aether:aether-connector-wagon
org.sonatype.aether:aether-impl
org.sonatype.aether:aether-spi
org.sonatype.aether:aether-util
------------------------------------------------------------------------------
3-Clause BSD
https://opensource.org/licenses/BSD-3-Clause
com.google.code.findbugs:jsr305
org.hamcrest:hamcrest-core
BSD License
Copyright (c) 2000-2015 www.hamcrest.org
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list of
conditions and the following disclaimer. Redistributions in binary form must reproduce
the above copyright notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
Neither the name of Hamcrest nor the names of its contributors may be used to endorse
or promote products derived from this software without specific prior written
permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY
WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
DAMAGE.
com.esotericsoftware.kryo:kryo
com.esotericsoftware.minlog:minlog
Copyright (c) 2008-2018, Nathan Sweet All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
Neither the name of Esoteric Software nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
org.ow2.asm:asm
org.ow2.asm:asm-analysis
org.ow2.asm:asm-commons
org.ow2.asm:asm-tree
org.ow2.asm:asm-util
ASM: a very small and fast Java bytecode manipulation framework
Copyright (c) 2000-2011 INRIA, France Telecom
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holders nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
THE POSSIBILITY OF SUCH DAMAGE.
------------------------------------------------------------------------------
MIT
com.googlecode.plist:dd-plist
dd-plist - An open source library to parse and generate property lists
Copyright (C) 2016 Daniel Dreibrodt
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
org.bouncycastle:bcpg-jdk15on
org.bouncycastle:bcprov-jdk15on
Copyright (c) 2000 - 2019 The Legion of the Bouncy Castle Inc. (https://www.bouncycastle.org)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
org.slf4j:jcl-over-slf4j
org.slf4j:jul-to-slf4j
org.slf4j:log4j-over-slf4j
org.slf4j:slf4j-api
Copyright (c) 2004-2017 QOS.ch
All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
------------------------------------------------------------------------------
CDDL
https://opensource.org/licenses/CDDL-1.0
com.sun.xml.bind:jaxb-impl
------------------------------------------------------------------------------
LGPL 2.1
https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html
org.samba.jcifs:jcifs
org.jetbrains.intellij.deps:trove4j
------------------------------------------------------------------------------
License for the GNU Trove library included by the Kotlin embeddable compiler
------------------------------------------------------------------------------
The source code for GNU Trove is licensed under the Lesser GNU Public License (LGPL).
Copyright (c) 2001, Eric D. Friedman All Rights Reserved. This library is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
Two classes (HashFunctions and PrimeFinder) included in Trove are licensed under the following terms:
Copyright (c) 1999 CERN - European Organization for Nuclear Research. Permission to use, copy, modify, distribute and sell this software
and its documentation for any purpose is hereby granted without fee, provided that the above copyright notice appear in all copies and
that both that copyright notice and this permission notice appear in supporting documentation. CERN makes no representations about the
suitability of this software for any purpose. It is provided "as is" without expressed or implied warranty.
The source code of modified GNU Trove library is available at
https://github.com/JetBrains/intellij-deps-trove4j (with trove4j_changes.txt describing the changes)
------------------------------------------------------------------------------
Eclipse Distribution License 1.0
https://www.eclipse.org/org/documents/edl-v10.php
org.eclipse.jgit:org.eclipse.jgit
------------------------------------------------------------------------------
BSD-style
com.jcraft:jzlib
com.github.mwiede:jsch
Copyright (c) 2002-2015 Atsuhiko Yamanaka, JCraft,Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
3. The names of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
------------------------------------------------------------------------------
Eclipse Public License 2.0
https://www.eclipse.org/legal/epl-2.0/
org.junit.platform:junit-platform-launcher
------------------------------------------------------------------------------
Mozilla Public License 2.0
https://www.mozilla.org/en-US/MPL/2.0/
org.mozilla:rhino
+21
查看文件
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 chengchengking
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.