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

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

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

+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())