feat: complete U30 Air power, LED and PD dock support

Fix charging-aware LED behavior, retain battery state across shutdown and use the shared LAN gateway. Add UMP9620 TCPM support with independent USB data and power roles, retaining manual host selection for powered docks.

Add native Apple Silicon installer builds and package them alongside Windows with source fingerprint checks, refreshed guides and regression coverage. Record hardware validation and the remaining automatic role-switch limitation.
This commit is contained in:
kanoqwq committed 2026-10-16 04:18:26 +08:00
1 parent 7ad5774368
commit 2af101f830
76 files changed
+2567 -205

No files matched your search

+45
View File
@@ -0,0 +1,45 @@
name: Apple Silicon installer
on:
workflow_dispatch:
push:
branches: ['build/macos-*']
permissions:
contents: read
jobs:
macos:
runs-on: macos-15
timeout-minutes: 45
env:
MACOSX_DEPLOYMENT_TARGET: '11.0'
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: '3.12'
architecture: arm64
- uses: actions/setup-node@v4
with:
node-version: '22'
cache: npm
cache-dependency-path: installer/ui/package-lock.json
- name: Native ARM toolchain
run: |
test "$(uname -m)" = arm64
rustup toolchain install 1.90.0 --profile minimal
python -m pip install pyinstaller paramiko lz4
- name: Installer tests (no device writes)
run: python -m unittest discover -s installer/tests -v
- name: Build native portable installer
run: python installer/build.py
- name: Frozen ARM64 backend and ADB smoke
run: python installer/tests/macos_frozen_smoke.py
- name: Preserve executable permissions and framework links
run: tar -czf openwrt-installer-macos-arm64.tar.gz -C installer/artifacts/macos-arm64 .
- uses: actions/upload-artifact@v4
with:
name: openwrt-installer-macos-arm64
path: openwrt-installer-macos-arm64.tar.gz
if-no-files-found: error
+2
View File
@@ -14,6 +14,8 @@ permissions:
jobs:
windows:
runs-on: windows-latest
env:
PYTHONUTF8: '1'
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
+6 -4
View File
@@ -110,16 +110,18 @@ else
fi
log "stage=device $DEVICE order=$MODULE_ORDER"
# The USB network. Its subnet goes with the kind of device, so that an F50 and a U30 Air on one computer do not
# collide: F50 192.168.77.1, U30 Air 192.168.78.1 (the system's lan.conf overrides it after switch_root). The
# All boards share the default USB/LAN subnet 192.168.77.1. The
# gadget's MAC addresses and USB serial number go with the device's serial number: two devices on one computer
# used to have the same ones, and macOS then gave the second one no network interface at all.
case $DEVICE in u30air) NET=192.168.78 ;; *) NET=192.168.77 ;; esac
NET=192.168.77
# (a mainline kernel forces its own command line: the bootloader's is still in the device tree)
SERIALNO=$(cat /proc/cmdline /proc/device-tree/chosen/bootargs 2>/dev/null | tr '\0' ' ' |
sed -n 's/.*androidboot.serialno=\([^ ]*\).*/\1/p' | head -n1)
h=$(echo "$SERIALNO" | md5sum)
MAC=02:50:$(echo "$h" | cut -c1-2):$(echo "$h" | cut -c3-4):${NET##*.}
# Preserve existing USB identities when changing the default subnet.
MAC_TAG=77
[ "$DEVICE" != u30air ] || MAC_TAG=78
MAC=02:50:$(echo "$h" | cut -c1-2):$(echo "$h" | cut -c3-4):$MAC_TAG
load_vendor_modules() {
loaded=0
+2 -2
View File
@@ -60,7 +60,7 @@ slot, partition geometry and the on-device token must still match. New records
also save a `package-manifest.json` beside `transaction.json` for portability.
`--probe --serial SERIAL` checks the connected Android's model, encryption,
storage and binary DTB/A/B reads without staging files or writing partitions.
`--size 10` selects 10 GiB. `--host 192.168.78.1` selects U30Air for updates.
`--size 10` selects 10 GiB. `--host 192.168.77.1` selects U30Air for updates.
The installer never changes the computer's network or firewall settings.
Hotspot keys use visible input. Android image mounting resolves BusyBox's
`/dev/loopN` to Android's real `/dev/block/loopN` before attachment. Reboot
@@ -100,7 +100,7 @@ to the full partition by default. The initial 2 GiB image is not the installed c
The first offline boot may take several minutes or longer, then reboots once into OpenWrt; keep power connected.
Offline operations print a two-second stage/elapsed heartbeat; copying also
reports bytes. Progress is exposed during that boot at
`http://192.168.77.1:8089/progress.txt` (U30Air: `192.168.78.1`).
`http://192.168.77.1:8089/progress.txt` (U30Air: `192.168.77.1`).
USB networking must be enabled to view it. No permanent polling service is added.
FBE/FDE or `--format-userdata` uses two stages. **Android userdata is erased.**
+2 -2
View File
@@ -97,7 +97,7 @@ python3 OpenWrt-Installer.py --check
**缩容安装完成后会自动重启一次,再进入 OpenWrt。**
离线阶段可通过 `http://192.168.77.1:8089/progress.txt` 查看进度;
U30Air 为 `http://192.168.78.1:8089/progress.txt`。需电脑 USB 网卡启用且可访问设备。
U30Air 为 `http://192.168.77.1:8089/progress.txt`。需电脑 USB 网卡启用且可访问设备。
看不到进度页不代表可以中断安装,应以安装器输出和设备实际阶段为准。
### 加密 userdata,或主动选择格式化
@@ -138,7 +138,7 @@ python3 OpenWrt-Installer.py --resume --transaction "/path/to/transaction.json"
启动后沿用原有默认启动策略;永久默认启动需在 OpenWrt 中另行设置。
- **回 Android**:在网页系统切换入口选择 Android,再按提示重启。
管理地址通常是 `http://192.168.77.1`,U30Air 为 `http://192.168.78.1`。
管理地址通常是 `http://192.168.77.1`,U30Air 为 `http://192.168.77.1`。
热点名称/密码以安装输出为准,登录后设置自己的管理密码。更新需填写当前实际密码。
包提供容器所需的内核支持,没有预装 Docker,用户可按需安装。
+3 -2
View File
@@ -249,7 +249,8 @@ def settings(args, image_mib, mode, kernel):
class Android:
def __init__(self,args):
self.args=args
self.adb=args.adb or shutil.which('adb') or str(package_root()/'tools/adb.exe')
bundled=package_root()/('tools/adb.exe' if os.name=='nt' else 'tools/macos/adb')
self.adb=args.adb or (str(bundled) if bundled.is_file() else shutil.which('adb')) or str(bundled)
listing=self.call('devices').decode(errors='replace')
serials=[l.split()[0] for l in listing.splitlines() if len(l.split())==2 and l.split()[1]=='device']
if args.serial: self.serial=args.serial
@@ -681,7 +682,7 @@ def install(args,root,manifest):
a.run('printf "PART_MIB='+str(size)+'\\nDATA_MIB='+str(target//2048)+'\\nGROW_FS='+str(int(getattr(args,'grow_fs',True)))+'\\nFORMAT_DATA=0\\n" > /data/mu300linux/part-install.conf\nsync')
identity=':'.join(map(str,(s['CID'],s['NODE'],s['START'],s['SIZE'],target)))
a.flash(boot(root,m,'install-part',live,a.slot,identity=identity),m.boot_control(live,a.slot))
print('Offline shrink/install starts after reboot; progress at http://192.168.77.1:8089/progress.txt (U30Air: .78.1). / 重启后开始离线安装。')
print('Offline shrink/install starts after reboot; progress at http://192.168.77.1:8089/progress.txt. / 重启后开始离线安装。')
print('First boot may take several minutes or longer; do not interrupt power. After installation it reboots once into OpenWrt. / 首次开机缩容安装通常需数分钟,数据多或闪存慢时更久;完成后自动重启一次进入 OpenWrt,请勿中断。')
a.reboot()
return Outcome('pending','Payload verified; offline shrink/install is starting / 载荷校验通过,设备将离线缩容并安装。',
+27
View File
@@ -0,0 +1,27 @@
# U30 Air 灯控适配与后续修正(2026-10-16)
## 约定行为
- 网络灯:4G 蓝色,5G 白色,无服务红色。
- Wi-Fi 灯:5 GHz 白色,2.4 GHz 蓝色。
- 电池灯:充电时蓝色硬件呼吸,充满后白色;未充电且电量低于或等于 15% 时红色闪烁。
- 外部供电期间,按用户启用设置保持三组灯工作;拔电后重新开始熄灯倒计时。用户主动关闭某组灯的设置仍然有效。
- 电池灯亮度可在网页调整;网络灯和 Wi-Fi 灯是开关型硬件,不提供无效的亮度选项。
## 本次后续修正
此前呼吸曲线为 1250/250/1250/750 ms(渐亮/峰值保持/渐暗/暗处保持),周期 3.5 秒。现改为 625/750/625/250 ms,周期 2.25 秒:加快节奏、延长最亮阶段,提高一轮内的平均亮度。默认峰值保持硬件允许的 255,不提升 PMIC 电流或超出额定亮度。
拔电时,充电器 online 已更新为 0,但电量计 status 可能短暂仍为 Charging/Full;现以实际外部供电状态为准,避免继续显示充电呼吸。
旧脚本没有把电源快照、状态文件及灯硬件写入放在同一事务内,存在电源事件和超时熄灯交错执行的机会。现使用已有 flock 依赖串行化 U30 Air 的灯控操作,取得锁后才读取供电状态。后台温度告警不持有该锁,避免长期阻塞。未增加轮询或软件呼吸任务。
## 验证
- 25 项灯控、网页设置、机型识别相关测试通过,包含拔电后电量计状态滞后、超时后再次收到电源事件、事件等待锁时发生拔电等情况。
- 已热部署到连接的 U30 Air,无需重启。
- 实机硬件曲线回读为 `0 625 255 750 0 625 0 250`;PMIC 峰值寄存器为 `0xffff`,曲线寄存器为 `0x0505` / `0x0206`。
- 通过临时 LED 测试输入模拟“已拔电但电量计仍报 Charging”,充电呼吸立即清除。模拟计时到期后,三组灯均回读 0,PMIC RGB 控制寄存器回读 0;随后恢复真实电源输入和正常灯控。
- 模拟测试没有修改充电器、网络、AT、NV 或分区配置。实际拔插的长期稳定性仍需日常使用观察。
当前 U30 Air 管理地址为 `192.168.77.1`。这些源码和热部署改动尚未重打安装包。
+34
View File
@@ -0,0 +1,34 @@
# U30 Air PD 扩展坞:USB 主机与充电分离
## 故障与原因
原厂 Android 能通过带 USB-C PD 充电口的扩展坞同时充电与连接 USB 外设。
此前主线内核缺少 UMP9620 PD 控制器驱动,只有 VBUS 检测、充电类型识别和手动 USB 角色控制。
手动主机模式把 USB 数据角色和 OTG 升压供电绑定起来,无法完成扩展坞所需的 PD 数据/供电角色协商。
## 修改
- 将原厂 GPL 驱动中的 UMP9620 寄存器、时钟与校准操作接入主线 TCPM,使用内核既有 PD 状态机。
- 硬件完成 Type-C DRP 检测;IRQ、VBUS 事件驱动状态更新,无周期轮询或用户态反复切换角色。
- DWC3 数据角色与充电器供电角色独立:主机模式可以保持受电,只有成为供电端才开启 OTG 升压。
- 为 BQ256xx 板级充电器注册真实的 OTG regulator,并在 PD 合约生效后交由协商电流管理输入限制。
- 仅声明 5 V:受电上限 2 A,供电声明 500 mA;未移植原厂 PPS/高压 PDO。
- U30 Air 的 mu300-usb 优先使用内核 Type-C data_role,请求数据角色切换时不直接操作充电器寄存器;旧内核保持原兼容路径。
- 处理驱动加载前已插线的初始状态;TCPM 在 .remove 中先注销,避免 devres 提前释放异步创建的 PD 对象。
- 接收中断按原厂顺序读取单帧并清理 FIFO,避免把帧后残留字当成下一条 PD 消息;保留重复 TX 完成保护。
- 仅绑定具有 use_pdhub_c2c 的 UMP9620 电池板;其他机型不会因启用内核选项而套用该硬件控制。
## 验证进度
- 6.18.54 与 7.2.8 正式版 Image、全套配套模块均已编译完成。
- U30 Air 已运行测试内核,修正版控制器以匹配 BTF 的模块热加载。
- 电脑 USB 连接识别为 USB device + power sink,管理网络、热点和蜂窝保持运行。
- 修正资源释放顺序后再次卸载/加载,无新增内核 WARN。
- Linux 下 26 项 USB 管理与 PD 回调测试通过,包括主机受电、主机供电、设备受电、错误返回、重复 TX 完成保护、接收帧边界与错误清理。
- 用户确认:扩展坞接上充电器后,手动切主机模式即可使用;接受保留手动切换。
- 对应内核日志确认 USB host + power sink,RTL8153 网卡成功枚举并进入 LAN,链路 carrier on。
- 自动切换为主机未通过,因此不宣称实现;PD 接收清理的收尾修正后,还未再次验证同一扩展坞。
正式版内核与 203 个配套模块文件已同步写入设备,镜像回读校验通过。部署期间保留完整旧内核和配套模块,启动后的管理检查通过才解除自动回退。
正式重启检查:U30 Air 已启动 7.2.8 #33,内置 ump9620-tcpm 驱动绑定成功,不再依赖临时测试模块。电脑 USB 数据角色为 device、供电角色为 sink;192.168.77.1 管理连接正常,5 GHz/80 MHz 热点已启动,蜂窝 WAN 已获取 IPv4 与 DNS。根分区以读写方式挂载,无新增 BTF/驱动 WARN;自动回退已确认解除。
+93 -87
View File
@@ -2,192 +2,198 @@
## 中文
安装器作者:**Minikano**。侧栏解压提示上方显示作者、Q群0 `376737485`、Q群2 `1016263950`、Q群3 `950666902`、Q群4 `262019320`;点击群号按钮即可复制纯数字。项目仓库:E5 <https://github.com/sprd-linux-devs/e5-linux>(Enceka、Minikano),MU300 <https://github.com/dikeckaan/mu300-linux>(dikeckaan、Minikano)。两处都标注 Minikano 为共同作者;点击侧栏或赞赏弹窗中的仓库入口,用系统浏览器打开对应项目。
完整解压安装包,双击根目录的 **OpenWrt-Installer.exe**。保留全部子目录,不要只复制 EXE。Windows 无需另装 Python、Node 或 Rust;如果提示缺少 WebView2,请按提示安装后重新打开。
每次启动都会显示可关闭的赞赏提示,本安装器接受自愿打赏,关闭后即可继续使用;需要的新手引导会随后出现。侧栏带爱心的“赞赏支持作者”文字按钮可随时重新打开。弹窗和侧栏都有 GitHub 图标与仓库入口,欢迎前往 GitHub 给项目点一个 Star,支持持续维护与更新。赞赏码优先从 <https://api.kanokano.cn/pay/zsm.png> 加载;网络出错或等待超过 5 秒后使用内置图片。该提示不会发起设备操作。
安装前备份重要文件,确认安装包适用于你的机型,并保持设备稳定供电。在 Android 中开启 USB 调试,允许这台电脑调试,并准备好 Magisk/root。
完整解压 ZIP 后,双击根目录 **OpenWrt-Installer.exe**。请保留旁边的 `tools/`、`files/` 或 `payload/`、`desktop/`、`scripts/` 等目录。Windows 用户无需安装 Python、Node 或 Rust。程序使用系统 Microsoft Edge WebView2 Evergreen Runtime;缺失时会显示原生提示和安装地址:<https://developer.microsoft.com/microsoft-edge/webview2/>。不包含独立浏览器,不安装 Docker。
Apple Silicon Mac(M1 及更新芯片)完整解压后,打开根目录的 **OpenWrt-Installer.app**。无需另装 Python、ADB 或 Rosetta;请将 app 与 tools、payload 等目录放在一起,不要单独拖入“应用程序”。如果系统将 app 隔离运行、要求选择安装包,请选择包含 payload 与 desktop 的解压根目录。此版本采用临时签名,未做 Apple 公证;首次启动若被系统拦截,可在“系统设置 → 隐私与安全性”中核对来源并允许打开。
`OpenWrt-Installer.py` 是兼容的命令行入口,需要 Python 及相应模块。Windows 的 `launchers/*.cmd` 优先使用随包解释器运行 CLI,普通用户应从根目录 EXE 开始。Magisk 用户仍可直接刷入同一个 ZIP;根目录 `module.prop`、`customize.sh` 和 Magisk 必需文件保留原用途。桌面依赖不会进入设备系统镜像。整个包只有一份系统载荷。
Linux、Intel Mac 或需要命令行操作时,可使用 **OpenWrt-Installer.py**,需另行安装 Python 和依赖。使用 Magisk 安装时,直接选择完整 ZIP;这会部署到 TF 卡并清空选定目标,请先备份卡内数据。
### 选择用途
- **安装 OpenWrt**:TF 卡或独立内置分区。先校验包,再明确选择 USB 设备并检查。即使连接多台设备,后续 ADB 操作也只发送到所选序列号。最终确认前会再次检查实际机型、槽位、闪存身份和计划。
- **更新 OpenWrt**:从运行中的 OpenWrt 通过 SSH 上传,输入设备管理地址及 root 密码。密码仅在本次进程内存中使用,不写入事务或日志。保留设置、已有容量及本机固件;设备端升级互斥和校验继续有效,不要求 SFTP。请先手动连接设备网络。
- **继续未完成的安装**:选择本机事务,使用原包或兼容修复版。按真实机型、系统/启动载荷和文件系统工具哈希验证,不按目录名判断;可以移动或重命名包。载荷不一致会明确列出差异。
- **临时启动已安装的 OpenWrt**:检查启动签名及启动链后,只修改 misc 试启动信息。与“设为默认启动”不同,不修改默认值,不为探测安装状态挂载或写入 OpenWrt 根分区。现有设备端默认启动管理入口继续可用。
- **高级选项**:重装已有内置分区会替换其中的 OpenWrt 与设置,保留 Android;userdata 镜像属于**实验性功能,可能损坏 Android F2FS 文件系统**。镜像大小受真实可用空间、Android 预留及上传/生成临时空间限制。
- **安装 OpenWrt**:首次安装到 TF 卡或独立内置分区。校验安装包,选择设备并检查,然后核对安装计划。
- **更新 OpenWrt**:保留已有设置和容量更新系统。设备需运行 OpenWrt,电脑需连接它的网络,并提供管理地址和 SSH root 密码。
- **继续未完成的安装**:选择原安装记录,接着完成中断的安装或 Android 重置后的续装。
- **临时启动已安装的 OpenWrt**:从 Android 切换到已安装的 OpenWrt,仅本次启动生效,不会设为默认系统。完成后按提示重启。
- **高级选项**:重装已有内置分区,或使用 userdata 镜像。重装会替换原 OpenWrt 系统和设置,保留 Android。**userdata 镜像是实验性功能,可能损坏 Android F2FS 文件系统**,建议优先选择 TF 卡或独立内置分区。
连接多台设备时,请核对型号和序列号末四位,明确选择本次要操作的设备。
### TF 卡
按仓库原有规则选择第一分区;只有确实没有分区时才选择整卡。不会重划 TF 卡,也没有 32 GiB 上限。请核对计划中的准确块设备与容量。安装前校验载荷、提取本机固件、释放 Android 对目标卡的挂载;释放失败就停止。所选目标会被格式化并使用其容量,其他分区不参与。原 Magisk TF 部署入口保留。
插入已备份、可以清空的 TF 卡。安装计划会显示目标分区和容量,请确认后再开始。
优先安装到卡的第一分区;没有分区时使用整卡。所选目标会被格式化,其他分区保留。不重新划分 TF 卡,没有 32 GiB 容量上限。
若提示 TF 卡无法释放挂载,请停止使用卡内文件的 Android 应用,再重试;不要跳过提示强行格式化。
### 独立内置分区
检查设备不会替换你已选择的安装方式;“推荐”只作提示。重装已有内置分区不要求插 TF 卡,也不会校验 TF 卡容量。只有选择 TF 卡安装时才要求卡及其目标分区有效。最终计划会明确列出安装方式、写入目标和数据影响;返回修改时会保留所选方式及原页面。
选择需要分给 OpenWrt 的容量。安装器优先使用已有未分配空间;不足时才需要缩小 Android 用户数据分区。最终计划会列出 Android 保留空间、OpenWrt 分配空间,以及是否会清空数据。
优先使用已验证 GPT 未分配区域,足够时不缩容或清空 userdata。没有合适区域时使用既有离线缩容逻辑。计划显示 Android 保留空间、OpenWrt 分配大小及数据影响。
**“使用全部已分配的 OpenWrt 分区容量”建议保持开启**:例如分配 10 GiB,安装完成后便使用这 10 GiB,不会额外占用 Android 的剩余空间。
“使用全部已分配的 OpenWrt 分区容量”默认开启,意思是扩满选定大小的 OpenWrt 分区,**不是占用设备所有剩余空间**。设备端写入后检查文件系统块数,进入 OpenWrt 后再次读取 ext4 超级块验证实际容量。验证没通过不会显示安装成功。
首次启动会进行离线分区准备,可能需要数分钟,完成后设备会自动重启一次。数据较多时可能更久,请保持供电,不要因暂时没有画面而强制重启。
首次启动会进行离线分区准备,可能需要数分钟,完成后设备会自动重启一次。数据较多或存储较慢时可能更久,请一直供电。检查、缩容、格式化、扩容显示阶段与耗时,不显示虚构百分比。
已有内置 OpenWrt、只想重新安装时,在高级选项中选择“重装已有内置分区”,无需插入 TF 卡。
### 加密 userdata:重置后自动续装
检测到 FBE/FDE 或映射加密 data,且必须缩容时,计划会明确说明 Android 用户数据全部清空。仅在最终确认后继续。安装器将事务与必要备份先写入电脑,再准备 initramfs 交接。第一阶段依靠启动镜像中的请求及准备标记,系统载荷留在电脑,不依赖即将被清空的 `/data` 文件。
如果加密的 Android 用户数据分区必须缩容,**Android 应用、账号、照片和内部存储会全部清空**。请先自行备份个人数据,并仔细核对安装计划中的重置提示。
1. 保持设备供电,等待离线分区准备和原厂 recovery 清空数据。
2. 设备回到 Android 后完成初始设置。
3. 开启开发者选项、USB 调试,在设备上允许这台电脑调试。
4. 若 root 不存在,安装或恢复 Magisk;若出现 root 请求,请允许。已经可用的 root 会被直接接受,不要求重复安装。
5. 安装器验证同一设备、实际 `su` 权限、原槽位、分区几何与准备标记,然后继续传输安装。
1. 保持安装器运行及设备供电,等待分区准备和恢复出厂完成。设备可能重启多次。
2. 进入 Android 后,完成初始设置。
3. 开启开发者选项和 USB 调试,在设备上允许这台电脑调试。
4. 打开 Magisk 检查 root。只有 root 丢失时才需安装或恢复 Magisk;出现 root 授权请求时请允许。
5. 安装器检测到原设备且 root 可用后,会继续安装。
这些等待**没有总超时**。预期重启或 USB 消失属于等待状态,不是 EOF 失败。无 ADB 时电脑无法区分“Android 仍在开机”和“尚未开启调试”;界面同时给出初始化、开启调试与允许授权的具体步骤。未加密 userdata 保留离线保数据缩容,不默认清空。
完成初始设置和授权没有固定时限。等待中请按页面指引操作,不要重新创建首次安装任务。若已关闭安装器,重新打开后选择“继续未完成的安装”。
未加密的用户数据分区可以保留数据进行离线缩容;是否需要清空,以最终安装计划为准。
### 更新与自动重启
更新提交后,设备会自动重启以应用更新,网络会暂时断开。页面与通知会显示“更新已提交,设备将自动重启”;请保持供电。安装器确认同一设备的启动标识确实变化,再校验实际容量,最后显示“OpenWrt 已更新并通过校验”。重启前旧系统仍能响应 SSH 时不会提前显示完成。点击“我已进入 OpenWrt”也仍会核验真实重启;地址或密码变化时可在此处修正。完成、失败和暂停后阶段计时停止;这些时间保存在记录中,重新打开后仍可查看,重试开始新的执行计时。旧更新记录若未保存重启前证据,不能自动认定更新完成,应保留记录人工复核。
将电脑连接到目标 OpenWrt 的 USB 网络或热点,选择“更新 OpenWrt”,填写当前管理地址和 SSH root 密码。重要配置和文件仍建议提前备份。
重启期间的 SSH 断开、连接被拒绝、连接超时或 USB 网卡暂时消失,均属于正常的“设备正在重启,等待重新连接”,不会显示连接错误或要求重新更新,也没有固定等待总时限。详细原因仅记入 DEBUG 日志;认证失败或地址确实对应另一台设备时,才提示修正密码/目标。管理地址与密码输入框始终保留,设备开机后可手动确认并重试校验。
更新提交后设备会自动重启,期间网络暂时断开。保持供电,等待安装器重新连接并校验。**不要因为重启期间连接不上而重新执行更新。**
若设备已经开机却一直等待,请核对电脑连接的设备网络、管理地址和密码,然后点击“我已进入 OpenWrt,开始校验”。地址或密码改过时,填写实际值。
### 暂停、关闭与失败恢复
事务默认位于 `%LOCALAPPDATA%\OpenWrt-Installer\transactions\<transaction-id>\`。通过“打开事务目录”查看,通过“导出事务与备份”生成 ZIP。备份含设备身份和可能含无线配置的旧后端记录,请妥善保管,不要公开上传。DEBUG 日志记录命令边界、脱敏后的 CLI 输出、校验结果及具体异常堆栈;密码、无线密钥与完整设备标识在写入日志前脱敏,不读取短信正文。
需要退出时,点击“在安全边界暂停”,等待页面显示已暂停后再关闭。正在进行的写入需要先完成;设备已开始离线准备时,即使电脑上的任务已暂停,也请继续为设备供电。
“在安全边界暂停”会等待正在进行的存储操作结束,不会直接杀进程。任务执行中关闭窗口会被阻止并提示先暂停。暂停后可以关闭、重启电脑或移动包;重新打开 EXE,选择“继续未完成的安装”。若已提交离线准备,暂停不会撤销设备已收到的启动请求,仍须保持设备供电。完成页保持显示,不会自动关闭。
重新打开安装器,选择“继续未完成的安装”,使用原记录继续。不要因断线或报错重新发起首次分区安装。安装包可以整体移动或重命名;换用修复版时,若提示不兼容,请保留原包和记录,按提示处理。
意外断线时保留完整事务和备份,从原记录复核并继续;不要重新创建一次首次分区任务。已经确认完成的操作有独立检查点,不重复执行。若在写分区表或启动信息中断,且无法凭回读证明完成,会停止并要求用备份恢复,而不会猜测并盲写。设备端旧标记本身不能替代缺失的电脑身份、布局、哈希及备份证据。
安装记录和备份自动保存在电脑上。点击“打开事务目录”查看,或用“导出事务与备份”保存完整 ZIP。**这些备份不能替代安装前对照片等个人文件的备份。** 换电脑续装时,先解压导出的 ZIP,再用“导入恢复目录”选择包含 `transaction.json` 的完整目录。请妥善保管备份,不要公开上传。
从另一台电脑恢复:先解压导出的事务 ZIP,使用“导入恢复目录”选择含 `transaction.json` 的完整目录。仅有孤立 JSON、缺少备份或标记不匹配时不能保证自动恢复。修复版包必须保留相同的机型、布局、关键系统/启动载荷与工具;仅改 GUI、提示、上传逻辑允许续装。损坏或不同版本系统载荷需另行评估,不会自动接受。
出错时展开“详细日志”,点击“复制诊断信息给开发者”,并说明机型、安装方式和出错前的操作。日志也可以导出。若提示需要从备份恢复,请保留设备现状和完整备份,联系开发者协助。
安装完成后手动连接设备 USB 网络或热点。默认管理地址:E5/M8/T551M 为 `http://192.168.9.1`;MU300/F50/V50 为 `http://192.168.77.1`;U30Air 为 `http://192.168.78.1`。GUI 会验证同一闪存 CID 后再报告结果。修改过设备地址或 SSH 密码时,请在对应维护页面提供实际值。安装器不启停电脑网卡、不改路由、不自动连接热点。请在首启后修改管理员和无线密码。
文件传输显示 100% 后,可能仍需提取固件、安装或校验,请以当前阶段说明为准。检查、格式化和扩容期间没有百分比时,请保持供电并等待。
窗口顶部、步骤导航和底部操作按钮保持固定;安装内容、续装列表和展开的日志各自滚动。侧栏底部可打开事务目录。操作结果、错误与阶段变化统一通过右上角通知提示;错误通知可以手动关闭,详细信息仍可在日志或对应事务页面查阅。通知不会覆盖底部最终确认按钮。数据影响、等待操作指引和完成结果会持续显示在页面中。界面动效会遵循 Windows 的“动画效果/减少动态效果”设置。
需要手动重启时,页面会提示“请现在手动重启设备”;已在重启或已进入 OpenWrt 时,不必重复重启。进入 OpenWrt 后,将电脑连接到目标设备的 USB 网络或热点,核对管理地址和 SSH root 密码,再点击“我已进入 OpenWrt,开始校验”。连接了多台 OpenWrt 时,注意默认地址冲突,确认电脑访问的是目标设备。
开始或继续安装后,底部“详细日志 · DEBUG”自动展开,可随时收起;日志列表限制高度,不会推走操作按钮。出错时可一键“复制诊断信息给开发者”,也可复制或导出日志。分享内容来自电脑上持久保存的日志,不局限于界面最近显示的 500 条;完整轮转日志随事务备份导出。旧版记录没有保存的调试细节无法凭空恢复,使用新版重试后会开始记录。备份及传输显示真实字节数、速度和进度条;写入、检查、缩容或扩容缺少可信百分比时,显示活动进度条、阶段及耗时,不生成虚假百分比。等待用户操作时,进度条停止活动并显示下一步指引。
启动链备份逐项 `dd` 到设备 `/data/local/tmp/` 下的独立临时目录,再通过 `adb pull` 拉到电脑;源分区、临时文件、电脑文件的 SHA-256 必须一致。每项完成后删除设备临时文件,全部完成后删除临时目录。不使用 Base64 或压缩流备份;临时空间不足时会明确停止。备份只读取启动相关源分区,不向源分区写入。
文件传输的 100% 仅代表当前文件已传完。后续提取、音频或蓝牙固件转换会切换到独立阶段和活动进度条,并在日志中显示转换器文件名、输出及耗时。电脑端转换支持安全暂停,单个转换器超过 120 秒会明确报错;Android 初始化和授权等待仍没有此时限。
详细日志按最新记录在上、较早记录在下显示;一条异常内的堆栈顺序保持不变。复制及导出的持久化诊断仍按发生时间排列,方便开发者分析。
阶段 4 需要手动重启时,页面顶部会明确显示“请现在手动重启设备”。使用设备正常重启功能;已经重启或进入 OpenWrt 时不要重复重启。自动重启流程会显示已发送请求。进入 OpenWrt 后,将电脑连接到这台设备的 USB 网络或热点,核对管理地址和 SSH root 密码,点击“我已进入 OpenWrt,开始校验”。多台 OpenWrt 的默认地址可能冲突,请连接目标设备的网络并填写它可访问的地址;安装器不会自动改网卡或路由。地址对应另一台设备、连接失败或认证失败时,可以直接修正地址/密码并重试,不必重新安装。手动确认会立即请求最终身份及容量校验,通过后显示完成;不会跳过校验或重新执行分区写入。所选地址与启动确认保存在原记录中,密码只在内存使用,重启安装器后需重新填写。
看到完成页面后,按显示的管理地址访问设备,检查服务并修改管理员与无线密码。E5/M8/T551M 默认地址为 `http://192.168.9.1`,MU300/F50/V50/U30Air 为 `http://192.168.77.1`;修改过地址时使用实际值。保留安装记录和备份,以便后续恢复。
### 连接与常见问题
#### 第一次使用,从哪里开始?
首次打开且没有安装记录时会显示三个步骤的新手引导,可以跳过;首页可随时重看。窗口右上角“帮助与使用指南”或 F1 打开可搜索的离线指南。安装中查看帮助不会暂停、重新开始或取消任务;关闭帮助会回到原来的安装页面。界面语言决定指南语言。所有引导都只作说明,不会连接、格式化或写入设备。
完整解压后打开根目录 EXE,先看新手引导,再按用途选择操作。首页可以重看引导;右上角“帮助与使用指南”或 F1 可打开本指南。
#### 没有发现设备,或者同时连接了多台设备?
刷新设备不依赖安装包校验;没有设备时也可以反复刷新。进入安装、临时启动或高级选项时会先自动刷新一次。枚举连接不读取分区或请求 root,检查设备和安装前仍须校验安装包。确认 USB 线支持数据传输、设备供电正常;必要时更换线缆或 USB 口,并在 Windows 设备管理器检查设备及其 USB 驱动。Android 中开启开发者选项和 USB 调试。多台设备会列在下拉列表中,请核对型号和序列号末四位,明确选择目标后检查;后续操作绑定所选设备,不会任选另一台。
确认 USB 线支持数据传输,Android 已开启 USB 调试,然后点击“刷新设备”。仍无设备时,尝试更换线缆或 USB 口,并在 Windows 设备管理器中检查 USB 驱动。多台设备会显示在设备列表中,请核对型号和序列号末四位后选择。
#### 显示“等待调试授权”或“离线”?
解锁 Android,查看是否出现“允许 USB 调试”提示并允许此电脑。没有提示时确认 USB 调试已开启,再重新插拔数据线并刷新。离线时先确认设备是否正在预期重启;等待它开机后重新连接。已有安装进行中时保留原记录,不要另开一个分区任务。
解锁 Android,允许“USB 调试”请求。没有弹窗时,确认 USB 调试已开启,再重新插拔数据线并刷新。设备正在重启时先等待开机;已有安装任务时保留原记录。
#### 已经安装 Magisk,为什么还在等待 root?
安装了 Magisk 应用不等于 `su` 已可用。打开 Magisk 确认 root 环境,留意并允许 root 授权请求;若 root 环境在重置后丢失,再恢复 Magisk。工作正常的 root 会直接使用,不会要求重复安装。完成初始化和授权没有固定的几分钟时限。
打开 Magisk,确认 root 环境正常,并允许 Shell 的 root 请求。只有 Magisk 应用、没有可用 root 时,需要恢复 root 环境;重置后也可能需要重新授权。
#### 续装一定要手动创建“事务”吗?
#### 安装记录丢失了怎么办?
不需要。安装记录由程序自动保存在电脑,里面保存设备身份、分区计划、载荷哈希、备份和已完成阶段。关掉程序、重启电脑或移动安装包后,从“继续未完成的安装”读取原记录即可。换电脑前导出完整事务与备份;在另一台电脑解压并导入完整目录。**电脑记录和导出备份都丢失时,当前版本不能仅凭设备自动重建续装记录。** 不要用新建首次分区任务代替丢失的记录。已经装好后进行更新或临时启动,不需要上一次安装的记录。
先检查原电脑上的事务目录,以及是否导出过完整备份。**电脑记录和导出备份都丢失时,当前版本无法仅凭设备自动重建续装记录。** 请保留设备现状,联系开发者,不要新建分区任务代替原记录。已经安装好的 OpenWrt,日常更新或临时启动不需要上一次安装的记录。
#### 什么时候会清空数据?等待时能关闭吗?
#### 什么时候会清空数据?
以最终安装计划为准。TF 安装格式化选定目标;重装替换已有 OpenWrt;必须缩容的加密 userdata 会明确提示 Android 重置。未加密 userdata 保留原有保数据缩容路径,足够的未分配空间优先使用。先读清楚计划,再作一次最终确认。写入中保持供电;需要退出时点击“在安全边界暂停”,等任务实际暂停后关闭。暂停不能撤销已提交给设备的离线启动请求。
TF 安装清空选定卡分区;重装替换已有 OpenWrt 及其设置;加密 userdata 必须缩容时会清空 Android。请以最终安装计划为准,确认备份后再开始。
## English
Installer author: **Minikano**. Above the sidebar extraction reminder are QQ groups 0 (`376737485`), 2 (`1016263950`), 3 (`950666902`) and 4 (`262019320`). Click a group to copy only its number. Project repositories: E5 <https://github.com/sprd-linux-devs/e5-linux> (Enceka and Minikano), and MU300 <https://github.com/dikeckaan/mu300-linux> (dikeckaan and Minikano). Minikano is credited as a co-author of both. Sidebar and support-dialog links open the selected project in the system browser.
Extract the complete package and run **OpenWrt-Installer.exe** at its root. Keep all adjacent folders. Windows users do not need to install Python, Node or Rust. If prompted to install WebView2, follow the instructions and reopen the installer.
A dismissible support notice appears on every application launch: this installer accepts voluntary donations. Close it to continue; onboarding follows when needed. Reopen it using the labeled “Support the author” sidebar button. Both the dialog and sidebar include a GitHub icon and repository link; a Star on GitHub is welcome to support ongoing maintenance and updates. The donation code first loads from <https://api.kanokano.cn/pay/zsm.png>, falling back to the bundled image on network error or after five seconds. This dialog never starts a device operation.
Back up important files, check that the package matches your model and keep the device powered. Enable USB debugging in Android, authorize this computer and have Magisk/root ready.
Extract the complete ZIP and run **OpenWrt-Installer.exe** at its root. Keep all adjacent folders. Windows users need no separate Python, Node or Rust. The application uses the system **Microsoft Edge WebView2 Evergreen Runtime**. If missing, a native dialog provides <https://developer.microsoft.com/microsoft-edge/webview2/>. No standalone browser or Docker is included.
On Apple Silicon Macs (M1 or newer), extract everything and open **OpenWrt-Installer.app** at the package root. Python, ADB and Rosetta are not required. Keep the app beside tools, payload and desktop; do not move it into Applications alone. If macOS translocates the app and a folder picker appears, select the extracted package root containing payload and desktop. This build is ad-hoc signed and not Apple-notarized. If macOS blocks the first launch, review the source and allow opening in System Settings → Privacy & Security.
**OpenWrt-Installer.py** remains the Python CLI. Windows command launchers prefer the bundled interpreter. Magisk can still install the same ZIP through its original root entry files. Desktop code and dependencies stay outside device payloads, and there is only one system payload in the package.
For Linux, Intel Macs or command-line use, run **OpenWrt-Installer.py** with Python and its dependencies installed. To install through Magisk, select the complete ZIP. This installs to the TF card and erases the selected target, so back up the card first.
### Choose your purpose
- **Install OpenWrt**: use a TF card or an independent internal partition. Verify the package, explicitly select a USB device, inspect it, then review the final plan. All later ADB operations are serial bound, including when multiple devices are connected.
- **Update OpenWrt**: provide the management host and SSH root password. Passwords stay in process memory. Existing update locks, checksum checks, SSH compatibility, settings, capacity and local firmware are retained. SFTP is not required. Connect to the device network manually.
- **Continue an unfinished installation**: select a saved transaction. Moving/renaming the package is supported. A repair release is accepted when the model, layout, system/boot payloads and filesystem tools are compatible; incompatibilities name the changed fields or files.
- **Boot installed OpenWrt once**: validate the boot signature/chain and change only the trial information in misc. Do not mount or write the OpenWrt root or change its default boot setting. Existing on-device default-boot controls remain available.
- **Advanced options**: reinstall replaces an existing internal OpenWrt partition and its settings while keeping Android. **Userdata image installation is experimental and may damage Android F2FS**. Image size is constrained by actual free space, Android reserve, uploads and temporary image preparation.
- **Install OpenWrt**: install to a TF card or an independent internal partition. Verify the package, select and inspect the device, then review the plan.
- **Update OpenWrt**: update while keeping settings and capacity. OpenWrt must be running, and the computer must be connected to its network. Enter its management address and SSH root password.
- **Continue an unfinished installation**: select the original record to resume an interrupted installation or continue after an Android reset.
- **Boot installed OpenWrt once**: switch from Android to the installed OpenWrt for one boot, without changing the default system. Restart when prompted.
- **Advanced options**: reinstall an existing internal partition or use a userdata image. Reinstallation replaces OpenWrt and its settings while keeping Android. **Userdata image installation is experimental and may damage Android F2FS.** Prefer a TF card or an independent internal partition.
With multiple devices connected, check the model and last four serial characters and select the intended device.
### Storage and capacity
Inspecting a device never changes your selected installation method; recommendation badges are advisory. Reinstalling an existing internal partition needs no TF card and does not validate card capacity. A valid card/target is required only for TF installation. The final plan names the method, write target and data impact. Returning to edit preserves the chosen method and original page.
For TF installation, insert a backed-up card that can be erased. Check the target partition and capacity in the plan. The first partition is used when present; otherwise the whole card is used. The selected target is formatted, other partitions are kept, and the card is not repartitioned. There is no 32 GiB limit. If Android cannot release the card, close apps using it and retry.
TF installation follows the existing first-partition preference, using the raw card only when it has no partitions. It does not repartition cards or impose a 32 GiB ceiling. Check the exact target and capacity. The payload and local firmware are prepared before releasing Android mounts and formatting. A release failure stops installation. Magisk TF installation remains supported.
For internal installation, choose the capacity to allocate to OpenWrt. Available unallocated space is used first; Android userdata is resized only when needed. The plan shows retained Android space, OpenWrt capacity and whether data will be erased.
Internal installation first checks validated GPT gaps. A sufficient gap avoids shrinking/resetting userdata. Otherwise the existing offline resize is used. The plan displays retained Android space, allocated OpenWrt space and data impact. **Use all allocated OpenWrt partition capacity** is enabled by default: it fills the chosen allocation, not all remaining device storage. Device-side block-count checks and final ext4 superblock verification prevent a 10 GiB partition with an unexpanded 2 GiB filesystem from being reported as success.
Leave **Use all allocated OpenWrt partition capacity** enabled to fill the chosen allocation. For example, allocating 10 GiB gives OpenWrt that 10 GiB without taking additional space from Android.
The first boot performs offline partition preparation. This may take several minutes; the device reboots automatically once it finishes. Keep power connected. Checks, formatting, shrink and growth use phase/elapsed indicators without invented percentages. Transfer progress uses actual acknowledged bytes and elapsed speed.
The first boot performs offline partition preparation. This may take several minutes or longer with more data, then the device restarts automatically. Keep power connected and do not force a restart because the screen is temporarily blank.
To replace an existing internal OpenWrt installation, choose Reinstall internal partition under Advanced options. No TF card is needed.
### Encrypted userdata and reset
When encrypted userdata must be resized, the final plan explicitly warns that all Android apps, accounts, photos and internal storage are erased. Back up personal data before confirming. The installer saves its computer transaction and essential backups before preparing initramfs. Stage-one handoff lives in the boot request and verified preparation marker; the system payload remains on the computer and is not lost with `/data`.
If encrypted Android userdata must be resized, **all Android apps, accounts, photos and internal storage will be erased**. Back up personal files first and review the reset warning in the installation plan.
Wait for offline preparation and stock recovery to finish. Complete Android setup, enable developer options and USB debugging, then authorize this computer. Restore/install Magisk only when root is unavailable, and allow the root request. Working root is accepted immediately. The installer rechecks the same hardware identity, original slot, partition geometry and preparation marker before continuing.
1. Keep the installer running and the device powered while partition preparation and factory reset finish. The device may restart more than once.
2. Complete Android initial setup.
3. Enable developer options and USB debugging, then authorize this computer.
4. Check root in Magisk. Restore or install Magisk only if root is unavailable, and allow any root request.
5. Installation continues when the original device reconnects with working root.
There is **no overall deadline** for user setup or authorization. Expected reboots and missing USB are waiting states. Without ADB the computer cannot distinguish Android still booting from USB debugging not yet enabled; the UI provides both instructions. Unencrypted userdata retains its preserving offline-shrink path.
Setup and authorization have no fixed deadline. Follow the waiting instructions and do not create a new first-install task. If you closed the installer, reopen it and choose Continue an unfinished installation.
Unencrypted userdata can be resized while preserving data. The final plan states whether a reset is needed.
### Updates and automatic restart
After submission the device automatically restarts to apply the update, briefly disconnecting its network. The page and notification show “Update submitted; device restarting.” Keep power connected. Completion requires the same device’s boot identifier to change, followed by actual-capacity verification; an SSH response from the old runtime before reboot cannot complete the update. Explicit boot confirmation retains this check. Correct changed addresses/passwords in the verification form. Phase clocks stop on completion, failure and pause, persist across application restart, and begin a new execution segment on retry. Older update records without pre-reboot evidence require manual review and are not automatically accepted as complete.
Connect the computer to the intended OpenWrt device’s USB network or hotspot. Choose Update OpenWrt and enter its current management address and SSH root password. Back up important configuration and files first.
SSH EOF, refused connections, timeouts and a temporarily absent USB network during reboot are normal reconnection waits. They do not generate connection-error warnings, request another update or impose a fixed overall deadline. Transport details remain in DEBUG diagnostics. Authentication failure or a confirmed different device still asks for corrected credentials/target. The editable management endpoint and explicit verification button remain available.
After submission, the device restarts automatically and the network disconnects briefly. Keep it powered and wait for reconnection and verification. **Do not start another update because the device is unreachable during restart.**
If the device has started but the installer keeps waiting, check the connected network, address and password, then select OpenWrt is running — verify now. Use the actual address and password if they have changed.
### Recovery and results
Transactions live in `%LOCALAPPDATA%\OpenWrt-Installer\transactions\<transaction-id>\`. Open this directory or export the full transaction/backup ZIP from the application. Backups include private hardware identity and may contain wireless settings in legacy records; do not publish them. DEBUG logs include command boundaries, sanitized CLI output, verification results and exception tracebacks. Passwords, wireless keys and complete hardware identifiers are redacted before logging; installation does not read SMS bodies.
To exit, select Pause at a safe boundary and wait until the task is paused before closing. An active write must finish first. Keep the device powered if offline preparation has already started, even while the computer task is paused.
Pause takes effect at a safe boundary. A partition or boot write is not killed. Closing an active window is blocked until a safe pause. Pausing cannot undo an already submitted offline boot request: keep the device powered. After closing the application, restarting the computer or moving the package, reopen it and choose **Continue an unfinished installation**. The completed page stays open.
Reopen the installer, choose Continue an unfinished installation and select the original record. Do not start partitioning again after a disconnect or error. You can move or rename the complete package folder. If a repair release is rejected as incompatible, keep the original package and record and follow the message.
After an unexpected disconnect, use the saved record instead of creating another first-install transaction. Completed effects have checkpoints. An uncertain GPT/boot write that cannot be proved complete stops for backup-based recovery; it is not guessed or blindly replayed. A device marker alone cannot replace missing host identity, geometry, payload hashes and backup evidence.
Records and backups are saved automatically on the computer. Use Open transaction folder to find them or Export transaction and backups to save a complete ZIP. **These backups do not replace a personal backup of photos and other files.** To resume on another computer, extract the exported ZIP and import the complete directory containing `transaction.json`. Keep backups private.
To move recovery to another computer, extract the exported transaction ZIP and import the complete folder containing `transaction.json`. An isolated JSON or insufficient backups may not be recoverable automatically. Compatible repair releases may change UI/prompts/upload logic while keeping model, root layout, critical system/boot payloads and tools unchanged.
On failure, expand Detailed logs and choose Copy diagnostics for the developer. Include the model, installation method and what you did before the error. You can also export the log. If backup recovery is required, preserve the device and full backup and contact the developer.
Connect to USB networking or the device hotspot manually. Default management addresses: E5/M8/T551M `http://192.168.9.1`; MU300/F50/V50 `http://192.168.77.1`; U30Air `http://192.168.78.1`. Final verification checks the eMMC CID before reporting success. Supply actual management details when previously changed. The installer does not modify adapters/routes or join hotspots. Change administrator and wireless passwords after first boot.
A file reaching 100% may still be followed by firmware preparation, installation or verification. Follow the current phase. Keep the device powered while checking, formatting or resizing, even when no percentage is shown.
The header, step navigation and bottom actions stay fixed. Installation content, recovery records and expanded logs scroll independently. The transaction-folder shortcut stays at the bottom of the sidebar. Results, errors and phase changes share the notification area at the upper right, away from the final confirmation buttons. Dismiss error notifications manually; consult the log or transaction page for details. Data-impact warnings, waiting instructions and completed results remain on the page. Interface motion follows the Windows animation/reduced-motion preference.
When asked to restart manually, use the device’s normal restart control. Do not restart again if it is already restarting or running OpenWrt. Connect the computer to the intended device’s USB network or hotspot, check the management address and SSH root password, then select OpenWrt is running — verify now. With several routers connected, check for conflicting default addresses and make sure you are reaching the intended device.
Detailed logs · DEBUG opens automatically when starting or continuing and can be collapsed at any time. Its bounded list keeps the action buttons visible. On failure, use Copy diagnostics for the developer; the log also supports copying and export. Sharing reads persisted diagnostics rather than only the last 500 UI entries; full rotated logs are included in backup export. Missing debug details from an older release cannot be reconstructed; retrying with this release begins recording them. Backup and transfer bars show measured bytes, speed and progress. Writing, checking, shrink and growth without a reliable percentage show an activity bar, phase and elapsed time. Waiting pauses bar activity and provides the next action.
Boot-chain backups use device-side `dd` into a private temporary directory under `/data/local/tmp/`, then `adb pull` to the computer. Source, temporary and computer SHA-256 checksums must match. Device temporary files are removed after each item, and the directory is removed when finished. Backup does not use Base64 or compressed streams and stops clearly if temporary space is insufficient. Source partitions are read without writing to them.
A transfer reaching 100% means only that file finished. Firmware extraction and audio/Bluetooth conversion have separate phases and activity bars, with converter names, output and elapsed time in the log. Host conversion can be safely paused and has a 120-second per-converter timeout. Android setup and authorization waits retain no overall deadline.
The detailed log displays newest entries first while preserving line order within each traceback. Copied/exported persistent diagnostics retain chronological order for investigation.
At phase 4, a manual restart requirement appears prominently as “Restart the device now.” Use the device’s normal restart control; do not restart again if OpenWrt is already starting or running. Automatic paths identify the requested restart instead. Once OpenWrt starts, connect this computer to that device’s USB network or hotspot, check its management address and SSH root password, and select “OpenWrt is running — verify now.” Multiple routers can have conflicting default addresses: use the target network and a reachable address. The installer never changes adapters or routes. Wrong-device, connection and authentication errors allow correcting the endpoint/password and retrying without reinstalling. Confirmation requests final device identity and capacity checks; it neither bypasses verification nor repeats partition writes. The endpoint and boot confirmation persist in the original record; passwords remain in memory and must be reentered after restarting the installer.
After completion, open the management address shown, check services and change administrator and wireless passwords. Default addresses are `http://192.168.9.1` for E5/M8/T551M and `http://192.168.77.1` for MU300/F50/V50/U30Air. Use the actual address if changed. Keep the installation record and backups for recovery.
### Connection and troubleshooting
#### Where should a beginner start?
The three-step getting-started guide appears on first launch when no installation records exist. You can skip it and replay it from the home page. Open the searchable offline manual with Help and user guide at the upper right, or F1. Reading help during installation does not pause, restart or cancel the task. Closing help returns to the original installation page. The interface language selects the manual language. The guide itself does not connect to, format or write a device.
Extract the complete package and open the root EXE. Read Getting started, then choose your purpose. Replay the introduction from the home page, or open this manual with Help and user guide or F1.
#### No devices, or several devices connected?
Refreshing devices does not require package verification, and an empty list can be refreshed repeatedly. Entering Install, one-time boot or Advanced options refreshes once automatically. Enumeration does not read partitions or request root; verify the package before device inspection or installation. Use a data-capable USB cable, keep power connected and try another cable or USB port if necessary. Check the device and USB driver in Windows Device Manager. Enable Android developer options and USB debugging. With multiple devices, check the model and last four serial characters in the list, explicitly select your target and inspect it. Later operations remain bound to that device.
Use a data-capable USB cable, enable Android USB debugging and select Refresh devices. If the list stays empty, try another cable or USB port and check the USB driver in Windows Device Manager. With multiple devices, check the model and last four serial characters before selecting one.
#### Awaiting debugging authorization, or offline?
Unlock Android and allow this computer in the USB debugging prompt. If no prompt appears, verify USB debugging, reconnect the cable and refresh. An offline device may be in an expected reboot; let it finish starting and reconnect. Keep an existing installation record instead of creating another partitioning task.
Unlock Android and allow the USB debugging request. If no prompt appears, confirm debugging is enabled, reconnect the cable and refresh. Wait for startup if the device is restarting. Keep the original record for an installation already in progress.
#### Magisk is installed, but root is still pending?
Having the Magisk app installed does not prove that `su` works. Check the root environment in Magisk and grant any root request. Restore Magisk if the root environment was lost after a reset. Already-working root is accepted immediately without reinstalling Magisk. Setup and authorization have no fixed deadline of a few minutes.
Open Magisk, check that root is working and allow the Shell root request. Having only the Magisk app installed is not enough. Restore root if it is missing; a reset may also require granting permission again.
#### Must I create a transaction manually to resume?
#### What if my installation record is missing?
No. The installer automatically saves a record on the computer, including device identity, partition plan, payload hashes, backups and completed phases. Reopen the application and choose Continue an unfinished installation after closing, restarting the computer or moving the package. Export the full transaction and backups before moving to another computer, then extract and import the full directory there. **If both computer records and exported backups are lost, this version cannot reconstruct a record from the device alone.** Do not substitute a fresh partitioning task for missing records. Updating or temporarily booting an already-installed system does not need its previous installation record.
Check the original computer’s transaction directory and any exported full backups. **If both computer records and exported backups are lost, this version cannot reconstruct a record from the device alone.** Preserve the device and contact the developer; do not create a new partitioning task instead. Updating or temporarily booting an installed OpenWrt does not require its previous installation record.
#### When is data erased, and can I close while waiting?
#### When is data erased?
Read the final plan. TF installation formats the selected target; reinstallation replaces existing OpenWrt; encrypted userdata that must shrink requires an explicitly warned Android reset. Unencrypted userdata keeps its preserving shrink path, and sufficient unallocated space is preferred first. Confirm once after reviewing the plan. Keep power connected during writes. To exit, request Pause at a safe boundary and close only after it actually pauses. Pausing cannot undo an offline boot request already submitted to the device.
TF installation erases the selected card target. Reinstallation replaces existing OpenWrt and its settings. Encrypted userdata that must be resized requires an Android reset. Review the final plan and back up data before confirming.
+2
View File
@@ -1,5 +1,7 @@
# Building the desktop installer
Apple Silicon macOS builds use the same `python installer/build.py` entry on an ARM64 Mac with Xcode command-line tools, Rust 1.90, Node 22 and Python 3.12. The build outputs `artifacts/macos-arm64/OpenWrt-Installer.app` plus native backend and official ADB under `tools/macos`, verifies the ARM64 Mach-O and applies an ad-hoc signature. It is not notarized. `.github/workflows/gui-macos.yml` builds on the native ARM64 `macos-15` runner. CI artifacts use a tar archive to preserve framework links and executable permissions. Set `OPENWRT_GUI_MACOS_ARTIFACT` to the extracted artifact directory when assembling a combined Windows/macOS firmware package. The Mac uses system WebKit, no bundled browser runtime. Installation records live under `~/Library/Application Support/OpenWrt-Installer`.
The shared sidebar credits installer author Minikano and provides four copy-number QQ buttons plus two fixed project links. E5 points to `https://github.com/sprd-linux-devs/e5-linux` (Enceka and Minikano), and MU300 points to `https://github.com/dikeckaan/mu300-linux` (dikeckaan and Minikano). Minikano is credited as co-author of both. Native `open_repository` accepts only the IDs `e5` and `mu300`, which map to those two literal URLs; it does not accept a URL or shell command.
`ui/src/components/support.tsx` provides an optional donation notice on every application launch, followed by onboarding when applicable. Closing it lasts for that window only; older `support-notice-v1` acknowledgements are ignored. A labeled sidebar button reopens it. Both repository entries include a Lucide GitHub icon, and the dialog invites a Star through the same fixed-ID repository opener. Opening the page does not automatically star anything. Only the donation image host is added to CSP `img-src`; scripts and IPC/network command permissions remain restricted. Online loading uses a normal no-referrer image request, with a five-second timeout/error fallback to `ui/src/assets/donation-fallback.png`. The checked-in 613×514 PNG was downloaded from `https://api.kanokano.cn/pay/zsm.png` on 2026-10-15: 161,701 bytes, SHA-256 `22c0d03221750cfb7a8c59692ff0e7d7530e56b807fe731ed23522403ce99be3`. It is fingerprinted and embedded in the GUI release, not the device rootfs. To refresh it, download that exact source, inspect the image and update this provenance before rebuilding.
+28 -28
View File
@@ -5,7 +5,7 @@
".gitignore": "a5773f83330fc9adddfd159fe0391bccffbf7663dccb2b873f6b2d1b2d2eca11",
"backend_entry.py": "238a3534a790ce46ae396040623117299f78b9fc9fc89fe152bfdd5788f7b664",
"build.py": "e3adff7e7c6a20e19ed541a4fc22589ba65306cd70dae2b4afde582e8c55a976",
"GUIDE.md": "e5ce730f39c0a13ad68ac541c6a9be50ef155bb57199c809ec32a31a3ab8cf75",
"GUIDE.md": "52d4c6526353b45d68b5f4a3072e82ab139978eaa8f3a6129a004037b3c14176",
"package_gui.py": "76435dcfd5c6386f39735b74e8c1dd541dbfdf4da391d02636c4482cc1b6d715",
"platform-tools.json": "d8fcf938e150bc314b5e6b2660c540976bb12ea6108fa75a8fb183115ebbd01e",
"PROTOCOL.md": "542b7909ffbcc9aa6c3ca5acffdbf8137f5a64487d52ba3997514d8cb5cbd2cc",
@@ -23,41 +23,41 @@
"backend/state.py": "bc17eac46b099524b2f2ad687d9fd6fcd3d867929487ef4a80d528992d6b3d48",
"backend/transport.py": "b022c4b6c2bc63090ebc2bf64ce6f3720a71cc90c95cfd5fa81836c156d956ba",
"backend/__init__.py": "4227d63763e764fd2de7fc2bc13e474ae5de33176fb57aa0fd51cbb4ad80b88c",
"screenshots/author-sidebar-zh.png": "c3d56dd01c1504107e682009692bbfc0f4f4d7cd25aca188755fdfa2f1142dbc",
"screenshots/automatic-restart-log-en.png": "faa89f19ab382e92696394376480ef25389c6eeecb960ed94c9cb3f6d58614ee",
"screenshots/backup-progress-debug-zh.png": "7e43bf33bc9a82e4e5767118c9c51c4826fcfd2056dffeedb48a2f27d3181c53",
"screenshots/complete-dark-en.png": "05ad7cefc8cb2d3d77305899b5bb0804f5ec3de2dfb83bf472a32b9ced31d891",
"screenshots/failure-copy-diagnostics-zh.png": "849c775ed4fba7648a9ac19b2b88d91983bd2035e08e0b9df517e8b3591b613f",
"screenshots/firmware-convert-debug-zh.png": "b670ee87fa916ec9cf8f66891a674fa2d11df3ee9b4b1ca4ec0fb730c805f488",
"screenshots/help-recovery-light-zh.png": "fe5832e539c43ead2b71010337d4d4dc03a3c6681d25d56fed73278b4af61965",
"screenshots/help-small-dark-en.png": "7d0aad05c6ba967c4126255e6e2f56b4e70f0c3398b15490c44044edfcea4614",
"screenshots/home-light-zh.png": "bd6c007fe839d7569c34acd0d9be42cc73dcd9368cd7f1211cc51412aee4086e",
"screenshots/install-activity-debug-zh.png": "d9e0ab7721d2484db0eb802352ee25d3b0200380d556259da123258468a26ac5",
"screenshots/author-sidebar-zh.png": "c1e4aefe0c6676e5c34228ed3633d375cc940ff6489eb414f1b5c0e41192c11f",
"screenshots/automatic-restart-log-en.png": "bb0fefb84e70c02473b7ecf4433b9bd61760c180bca24aeee2383da9d28e651c",
"screenshots/backup-progress-debug-zh.png": "f2653249edfee89403812cf741dd52ac1c900e3155c8f183e431aced116d9fc1",
"screenshots/complete-dark-en.png": "0b67f30e2a2cc5e55a4fac3fc5087edf29af0a1bb203084ac5eab3810b081ff9",
"screenshots/failure-copy-diagnostics-zh.png": "3b67dc78efaed2fd38e2c9f8a65f2a47b91ebca9227cc4173bceec34c17b16e0",
"screenshots/firmware-convert-debug-zh.png": "bc286a505a33d477033c148cbbe413b02f4352c70bf83222efab60f7136b29da",
"screenshots/help-recovery-light-zh.png": "68dbb2b5486145ed58998c43e4ae95dc08b65671abed714770f6721900f4f4f3",
"screenshots/help-small-dark-en.png": "b5041781331d04c036be44f956efcc36d8bc2757022d270486f78247f5dedd42",
"screenshots/home-light-zh.png": "ab65bda3e997c4698abc81678718d0f1e513d4cc456c54efdd39a3bebe4f8138",
"screenshots/install-activity-debug-zh.png": "de2721e5d34e66bf47af67cc76bd63f0b7f21fce42d518b65148ccbc20e5ff12",
"screenshots/install-small-light-zh.png": "9c088b24f9062b7afef64c3a4a6884add25592d0a46f6db9e5ac40daf1edb0b2",
"screenshots/manual-restart-log-zh.png": "f547e0471909af3f8f9a17a9caef16a6b70fff98d1a259e7f5075c8d759138a7",
"screenshots/manual-restart-log-zh.png": "a0e18e1be24079ba03da42a5534bc27c849be001831f721585b10e590620bd92",
"screenshots/native-home.png": "7b6709a73d05acccba0e199fe31fb0b862e555a5dd18f12ec94584fc80aaddc7",
"screenshots/native-mu300-home.png": "48ca20b2732f9a3d9522512ddd6121fc5eac4943d2cd928d7a21f0ba7c82a3a3",
"screenshots/native-support.png": "112d5086a0274a4a185e742338128b4721168eb74c12eafab24852e6be763e1a",
"screenshots/no-device-refresh-light-zh.png": "d8fc555f38c1b88c777bc405e65f959d6e152fb66380f93342286cde78c76135",
"screenshots/onboarding-light-zh.png": "fd2cf2fd894d075e8dd0003e27e189b9981878b1eb564cca9499d9299eb2d45e",
"screenshots/onboarding-small-dark-en.png": "3123c90cad20065f2787248a50daa3873a8b420c8d589a16f5474db85904be05",
"screenshots/openwrt-endpoint-mismatch-zh.png": "e6321a503fd9ba8fab1ebe16fab5f4ccc6a139863e9a17fe57108878d27f62e6",
"screenshots/onboarding-light-zh.png": "f52022eb357ee8f2b494dad993545c61ec3a9a68d65a6eff83bda9af1add2194",
"screenshots/onboarding-small-dark-en.png": "0f6b877e0504ea92397b0073dd3d0205056bdf98238d9b6bb0c4a3da592d1aa7",
"screenshots/openwrt-endpoint-mismatch-zh.png": "6b8d5fdaf20a2191e1ca4f316b5af9616fcff46fbf8c6074b855b7a27884ebb2",
"screenshots/plan-light-zh.png": "af27983a24c5098052a3ba61ab107bd3a03cc7eb83a290de1d26b38dd78fd4ae",
"screenshots/plan-small-dark-en.png": "0e41a92614671dc7b8cccdbca0caf115a0aa4ad96bec2688ec0c38cf101fb6f5",
"screenshots/plan-small-dark-en.png": "46445c164d1bce9748bbef405381b4fcd4b4792bebe10630393931a4b5097320",
"screenshots/reinstall-no-card-plan-zh.png": "22a4271252b3d849ef64c4f050f34e6ad8fce5d893fadad009cd63d2403e2121",
"screenshots/resume-small-light-zh.png": "2365fcaafa6f21e55f2d9367b21a09f25f1fe82b6916bdaaf7f96ca23876b0c3",
"screenshots/resume-small-light-zh.png": "e34f32331347b88b759c2de1ed9fb62233b37b7834c1aa1d65e6b8efbc891b9e",
"screenshots/support-first-launch-zh.png": "a10da09083fd1a430427d11206ad94780b8e5c5187ddc6f54e34eeaf6bc8efac",
"screenshots/support-offline-dark-en.png": "f539238255b9c4bee1e452b50facf9e2dcea7029433978c63c47a87ad853a7a6",
"screenshots/update-complete-clock-en.png": "87aef4564f846e34a59316d9114a2d6407b22588ebde42eea47de5c430c38d2d",
"screenshots/update-reboot-zh.png": "c83a637ba1534626664ff6f3981e001a634136a8b6c6e2606ca8d85cb0583260",
"screenshots/update-reconnecting-zh.png": "2590fb04c4dc84759f65ad33b555321cfc0c56df338483ae4e729088f01243bc",
"screenshots/wait-root-dark-en.png": "6ca798769306e338e34cf42b9fd482bdc932dbd441de23e31349a3cbe4d9b08d",
"screenshots/wait-setup-light-zh.png": "64ae42f304cd9c96d784ef85d8b660e5738288dcb95d2ca17eb7104a6ec8fda1",
"tests/diagnostics_smoke.py": "eae02d1c8352fe7d23a1ed38a3b9530a5dce99724c09ff04355a0ac8a2000591",
"screenshots/support-offline-dark-en.png": "3fbb1c15f1848e5f638ef51b9c2fca1f1b82f7955f3f1cd81f8c26ce384db868",
"screenshots/update-complete-clock-en.png": "10158e8e766a7d866bd3002d3277ae9df3ca83d5a1cecd6decfe15cde89599a5",
"screenshots/update-reboot-zh.png": "8287b75a57c71c25b9c550abd0692ec7716081ef635b06c2db652b7ca19ea7a2",
"screenshots/update-reconnecting-zh.png": "c8516e19f9fa65744b7968697a762342d4d5efeb227aceeb952e2cb15a15249a",
"screenshots/wait-root-dark-en.png": "84de205d53e92ed610333f31fb1289f7c5e37441b008e4872626dd41a4e7d479",
"screenshots/wait-setup-light-zh.png": "60988a52fce638892c4be36ae2ef84894a58ec80dbbe4e3dc210693d611f84bc",
"tests/diagnostics_smoke.py": "696ae478e24f4e227e334201812bf3c403a596028d8c04b16a26c2069a222893",
"tests/enumeration_smoke.py": "289a34ebaf95eb6e41fda57d6386d9aa848ba7f219a16ec05d49497ef93345d9",
"tests/frozen_flow_smoke.py": "9c451b8dcfa36154063a68c1690dbe0eefbdc48a73d58e3ace4a3d7ff6afd8af",
"tests/frozen_method_smoke.py": "5741114dc5468c36652d832c5206c1f207a10010f43bc29f0f8e4ce68f9da2de",
"tests/help_smoke.py": "859be310d207f42726dc85224b1fda0ee59b87ee613160d4533c3e7d9c0a56f2",
"tests/help_smoke.py": "5007c5e57b5cd0d68164c52e266f65c43161c0a87e423df733a180a637195ebc",
"tests/method_smoke.py": "698cc41317139f50bc5cac8252a8c31310856ba87ab1ddf421c3197a320ed072",
"tests/ordering_smoke.py": "b96022ebdd80fe1d9f2e8b3e1c543aeb96534c0323bc4e36f619d80fc7e3b3f5",
"tests/package_smoke.py": "f9ea830ae0e1801f52c8669b0b06033c6ee8c9a16745acc56c4b70b5f575ed26",
@@ -157,9 +157,9 @@
"verification/update-reboot-packages.json": "861a7816829aeb3c94ea0a1297e457a01ae70e82999b95a5690b02a9bb30adb5",
"verification/update-reboot.json": "26d586d25315c1d290d3e6ddae83322dd294a00a43a60ec232d7e47af7f61dee",
"verification/windows-packages.json": "2527a520a27d9eb0f9243aa9e2ed05b0e4b90caefc8257ea3afe76acdb75a19d",
"ui/src/help-data.ts": "3559333ab059b60829b7aef8fbdf92b932c2ce01cee5d7d8b5eef40cae42e4b6",
"ui/src/help-i18n.ts": "ffc22b67831f01ae70e8d3d98c6e3c0a351f22a1049e05b998bc072ca9b2864a",
"ui/src/i18n.ts": "7c1a3248a6cbe185a489be346a33433af81f9e3c2d97a79ede244745f65fd246",
"ui/src/help-data.ts": "e89b63d2fc496cf954bea237b2ff193bf1cfb93c8416d4860bbc4825e74fdb78",
"ui/src/help-i18n.ts": "4fb623fdc31fbd5f78d7e362389739b37529978b8625291d25547c15ae1fc4cd",
"ui/src/i18n.ts": "08a2eae0c6452589f56618cdfe22957fc1d4eae13af22a956137b261593f7bc5",
"ui/src/main.tsx": "624b34b1d51148dd8eb19d324558e3bd4a58fda5542b7f307364798523a85680",
"ui/src/protocol.ts": "acee2ee6a5608024563087a194998ebc4f2b55df01b449075bac3cb8e9f7e723",
"ui/src/style.css": "d5eec0a99a097581b43e02ef9bed2b7f0489817192e663d0e94e76263a7156b3",
+4 -3
View File
@@ -244,7 +244,8 @@ class Service:
if target.exists():
raise ValueError('Transaction already exists')
if record.get('legacy'):
relative = Path(record['legacy']).relative_to(Path(record.get('data_directory', directory)))
# macOS /var and /private/var can refer to the same directory.
relative = Path(record['legacy']).resolve().relative_to(Path(record.get('data_directory', directory)).resolve())
record['legacy'] = str(target/relative)
record['data_directory'] = str(target)
shutil.copytree(directory, target)
@@ -371,7 +372,7 @@ class Service:
r['package']['adapter'] == 'e5' and r['choices']['method'] == 'boot')
manual = manual and not r.get('openwrt_confirmed',False)
host = r['choices'].get('host') or ('192.168.9.1' if r['package']['adapter'] == 'e5' else
'192.168.78.1' if r['device']['profile'] == 'u30air' else '192.168.77.1')
'192.168.77.1')
context.stage('openwrt_boot', 'waiting_user' if manual or error else 'waiting_device',
host=host, reboot_manually=manual, boot_confirmed=bool(r.get('openwrt_confirmed')),
verification_error=error, connection_state=connection_state)
@@ -380,7 +381,7 @@ class Service:
import paramiko
r = context.record
host = r['choices'].get('host') or ('192.168.9.1' if r['package']['adapter'] == 'e5' else
'192.168.78.1' if r['device']['profile'] == 'u30air' else '192.168.77.1')
'192.168.77.1')
# No network/interface changes and no automatic hotspot connection.
while True:
context.boundary()
+3
View File
@@ -3,6 +3,7 @@ from contextlib import contextmanager
import hashlib
import json
import os
import sys
from pathlib import Path
import re
import tempfile
@@ -17,6 +18,8 @@ WAITING = {'waiting_device', 'waiting_user'}
def app_directory():
if sys.platform == 'darwin':
return Path.home() / 'Library/Application Support/OpenWrt-Installer'
return Path(os.environ.get('LOCALAPPDATA', Path.home() / '.local/share')) / 'OpenWrt-Installer'
+2 -1
View File
@@ -19,7 +19,8 @@ def hidden_process():
class Adb:
def __init__(self, package, serial=None):
self.serial = serial
paths = [Path(package) / 'tools/adb.exe', Path(package) / 'platform-tools/adb.exe']
names = ('tools/adb.exe', 'platform-tools/adb.exe') if os.name == 'nt' else ('tools/macos/adb', 'tools/adb', 'platform-tools/adb', 'tools/adb.exe')
paths = [Path(package) / name for name in names]
self.exe = next((str(p) for p in paths if p.is_file()), shutil.which('adb'))
if not self.exe:
raise ValueError('ADB is missing from tools / 安装包缺少 ADB 工具')
+42 -17
View File
@@ -1,7 +1,9 @@
"""Build the portable Tauri release and bundled Python backend on Windows."""
"""Build the portable Tauri release on Windows x64 or Apple Silicon macOS."""
import argparse
import json
import os
import platform
import plistlib
from pathlib import Path
import shutil
import subprocess
@@ -23,30 +25,32 @@ def main():
p.add_argument('--skip-ui', action='store_true')
p.add_argument('--adb-dir', type=Path, help='optional pre-fetched platform-tools directory')
a = p.parse_args()
if os.name != 'nt':
raise SystemExit('Build Windows binaries on Windows (MSVC, Rust 1.90, Node and Python are build dependencies only).')
if not a.skip_ui:
run('npm.cmd','ci','--no-audit','--no-fund','--registry=https://registry.npmjs.org',cwd=HERE/'ui')
run('npm.cmd','run','tauri','--','build','--no-bundle',cwd=HERE/'ui')
mac = sys.platform == 'darwin'
if os.name != 'nt' and not (mac and platform.machine() == 'arm64'):
raise SystemExit('Build natively on Windows x64 or Apple Silicon macOS (Rust 1.90, Node and Python required).')
before = sources()
work = HERE.parent/'work/installer-backend'
npm = 'npm' if mac else 'npm.cmd'
if not a.skip_ui:
run(npm,'ci','--no-audit','--no-fund','--registry=https://registry.npmjs.org',cwd=HERE/'ui')
run(npm,'run','tauri','--','build','--no-bundle',cwd=HERE/'ui')
work = HERE.parent/('work/installer-backend-macos' if mac else 'work/installer-backend')
run(sys.executable,'-m','PyInstaller','--noconfirm','--clean','--noupx','--optimize','2','--onedir','--console',
'--name','openwrt-backend','--distpath',work/'dist','--workpath',work/'build','--specpath',work,
'--hidden-import','lz4.block','--hidden-import','xml.etree.ElementTree','--hidden-import','xml.parsers.expat',
'--hidden-import','tarfile','--hidden-import','gzip','--hidden-import','zlib','--hidden-import','lzma',
'--hidden-import','bz2','--hidden-import','http.server','--hidden-import','decimal',
'--collect-all','paramiko',HERE/'backend_entry.py')
artifact = HERE/'artifacts/windows'
artifact = HERE/('artifacts/macos-arm64' if mac else 'artifacts/windows')
artifact.mkdir(parents=True,exist_ok=True)
tools = artifact/'tools'
tools.mkdir(exist_ok=True)
names = ('adb.exe','AdbWinApi.dll','AdbWinUsbApi.dll','NOTICE.txt')
tools = artifact/('tools/macos' if mac else 'tools')
tools.mkdir(parents=True,exist_ok=True)
names = ('adb','NOTICE.txt') if mac else ('adb.exe','AdbWinApi.dll','AdbWinUsbApi.dll','NOTICE.txt')
if a.adb_dir:
for name in names:
shutil.copy2(a.adb_dir/name, tools/('ADB-NOTICE.txt' if name=='NOTICE.txt' else name))
else:
dependency = json.loads((HERE/'platform-tools.json').read_text())
cache = HERE.parent/'work/installer-platform-tools/platform-tools-pinned.zip'
dependency = json.loads((HERE/('platform-tools-macos.json' if mac else 'platform-tools.json')).read_text())
cache = HERE.parent/'work/installer-platform-tools'/('platform-tools-macos-pinned.zip' if mac else 'platform-tools-pinned.zip')
cache.parent.mkdir(parents=True,exist_ok=True)
if not cache.is_file() or digest(cache) != dependency['sha256']:
urllib.request.urlretrieve(dependency['url'],cache)
@@ -55,19 +59,40 @@ def main():
with zipfile.ZipFile(cache) as archive:
for name in names:
(tools/('ADB-NOTICE.txt' if name=='NOTICE.txt' else name)).write_bytes(archive.read('platform-tools/'+name))
shutil.copy2(HERE/'ui/src-tauri/target/release/openwrt-installer.exe',artifact/'OpenWrt-Installer.exe')
destination = artifact/'tools/backend'
if mac:
(tools/'adb').chmod(0o755)
app = artifact/'OpenWrt-Installer.app'
executable = app/'Contents/MacOS/openwrt-installer'
executable.parent.mkdir(parents=True,exist_ok=True)
shutil.copy2(HERE/'ui/src-tauri/target/release/openwrt-installer',executable)
executable.chmod(0o755)
(app/'Contents/Resources').mkdir(exist_ok=True)
shutil.copy2(HERE/'ui/src-tauri/icons/icon.icns',app/'Contents/Resources/icon.icns')
info = {'CFBundleExecutable':'openwrt-installer','CFBundleIdentifier':'org.openwrt.desktop-installer',
'CFBundleName':'OpenWrt Installer','CFBundleDisplayName':'OpenWrt Installer',
'CFBundleIconFile':'icon.icns',
'CFBundlePackageType':'APPL','CFBundleShortVersionString':'1.0.0','CFBundleVersion':'1.0.0',
'LSMinimumSystemVersion':'11.0','NSHighResolutionCapable':True,
'NSAppTransportSecurity':{'NSAllowsLocalNetworking':True}}
(app/'Contents/Info.plist').write_bytes(plistlib.dumps(info))
run('codesign','--force','--deep','--sign','-',app)
run('codesign','--verify','--deep','--strict',app)
architectures = subprocess.check_output(['lipo','-archs',str(executable)],text=True).strip()
if architectures != 'arm64': raise ValueError('Expected native Apple Silicon GUI: '+architectures)
else:
shutil.copy2(HERE/'ui/src-tauri/target/release/openwrt-installer.exe',artifact/'OpenWrt-Installer.exe')
destination = tools/'backend'
# Use a clean build directory so removed dependencies cannot survive a rebuild.
if destination.exists():
resolved = destination.resolve()
if not resolved.is_relative_to(artifact.resolve()): raise ValueError('Invalid artifact target')
shutil.rmtree(resolved)
shutil.copytree(work/'dist/openwrt-backend',destination)
subprocess.run([str(tools/'adb.exe'),'version'],check=True,stdout=subprocess.DEVNULL)
subprocess.run([str(tools/('adb' if mac else 'adb.exe')),'version'],check=True,stdout=subprocess.DEVNULL)
if sources() != before:
raise ValueError('Source changed during compilation; rebuild before packaging')
files = {p.relative_to(artifact).as_posix():digest(p) for p in artifact.rglob('*') if p.is_file() and p.name!='build.json'}
(artifact/'build.json').write_text(json.dumps({'protocol':1,'source':before,'files':files},indent=2)+'\n',encoding='utf-8')
(artifact/'build.json').write_text(json.dumps({'protocol':1,'platform':'macos-arm64' if mac else 'windows-x64','source':before,'files':files},indent=2)+'\n',encoding='utf-8')
print(artifact)
+23 -3
View File
@@ -18,12 +18,16 @@ def digest(path):
def sources():
paths = [HERE/'backend_entry.py', HERE/'package_gui.py', HERE/'platform-tools.json', HERE/'GUIDE.md']
paths = [HERE/n for n in ('backend_entry.py','build.py','package_gui.py','platform-tools.json','platform-tools-macos.json','GUIDE.md')]
paths += list((HERE/'backend').glob('*.py'))
paths += [p for p in (HERE/'ui/src').rglob('*') if p.is_file()]
paths += [HERE/'ui'/n for n in ('package.json','package-lock.json','vite.config.ts','tailwind.config.js','postcss.config.js','tsconfig.json','index.html','rust-toolchain.toml')]
paths += [HERE/'ui/src-tauri'/n for n in ('Cargo.toml','Cargo.lock','build.rs','tauri.conf.json','src/main.rs','capabilities/default.json','icons/icon.ico')]
return {p.relative_to(HERE).as_posix(): digest(p) for p in sorted(paths)}
paths += [HERE/'ui/src-tauri'/n for n in ('Cargo.toml','Cargo.lock','build.rs','tauri.conf.json','src/main.rs','capabilities/default.json','icons/icon.ico','icons/icon.icns','icons/icon.png')]
# Git checkouts can normalize CRLF on the native macOS build runner.
# Only source text is normalized; binary artifact hashes stay exact.
text = {'.py','.ts','.tsx','.json','.toml','.rs','.js','.html','.md','.css','.lock'}
return {p.relative_to(HERE).as_posix(): hashlib.sha256(p.read_bytes().replace(b'\r\n', b'\n')).hexdigest()
if p.suffix in text else digest(p) for p in sorted(paths)}
def attach(package, artifact=None, required=True):
@@ -43,6 +47,22 @@ def attach(package, artifact=None, required=True):
raise ValueError('Portable build checksum mismatch: '+name)
shutil.copy2(artifact/'OpenWrt-Installer.exe', package/'OpenWrt-Installer.exe')
shutil.copytree(artifact/'tools', package/'tools', dirs_exist_ok=True)
mac_artifact = os.environ.get('OPENWRT_GUI_MACOS_ARTIFACT')
if mac_artifact:
mac_artifact = Path(mac_artifact)
mac_metadata = mac_artifact/'build.json'
mac_build = json.loads(mac_metadata.read_text())
if mac_build.get('platform') != 'macos-arm64' or mac_build['source'] != sources():
raise ValueError('Apple Silicon GUI build is stale or has the wrong architecture')
for name, wanted in mac_build['files'].items():
path = (mac_artifact/name).resolve()
if not path.is_relative_to(mac_artifact.resolve()) or digest(path) != wanted:
raise ValueError('Apple Silicon build checksum mismatch: '+name)
# Flatten framework links for ZIP extractors without symlink privileges.
shutil.copytree(mac_artifact/'OpenWrt-Installer.app', package/'OpenWrt-Installer.app', dirs_exist_ok=True)
shutil.copytree(mac_artifact/'tools', package/'tools', dirs_exist_ok=True)
(package/'docs').mkdir(exist_ok=True)
shutil.copy2(mac_metadata, package/'docs/GUI-BUILD-macos.json')
docs = package/'docs'
docs.mkdir(exist_ok=True)
shutil.copy2(HERE/'GUIDE.md', docs/'GUI-GUIDE.md')
+5
View File
@@ -0,0 +1,5 @@
{
"version": "37.0.1",
"url": "https://dl.google.com/android/repository/platform-tools_r37.0.1-darwin.zip",
"sha256": "ee39ad5967e95c2a07f04dbcbde96b1a0c916ba376096db5d2f498b7727a5d1d"
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 70 KiB

After

Width:  |  Height:  |  Size: 70 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 73 KiB

After

Width:  |  Height:  |  Size: 73 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 64 KiB

After

Width:  |  Height:  |  Size: 64 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 86 KiB

After

Width:  |  Height:  |  Size: 86 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 65 KiB

After

Width:  |  Height:  |  Size: 65 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 66 KiB

After

Width:  |  Height:  |  Size: 66 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 131 KiB

After

Width:  |  Height:  |  Size: 119 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 63 KiB

After

Width:  |  Height:  |  Size: 62 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 87 KiB

After

Width:  |  Height:  |  Size: 87 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 65 KiB

After

Width:  |  Height:  |  Size: 65 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 87 KiB

After

Width:  |  Height:  |  Size: 86 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 100 KiB

After

Width:  |  Height:  |  Size: 101 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 53 KiB

After

Width:  |  Height:  |  Size: 53 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 76 KiB

After

Width:  |  Height:  |  Size: 76 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 70 KiB

After

Width:  |  Height:  |  Size: 69 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 109 KiB

After

Width:  |  Height:  |  Size: 109 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 65 KiB

After

Width:  |  Height:  |  Size: 65 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 92 KiB

After

Width:  |  Height:  |  Size: 92 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 91 KiB

After

Width:  |  Height:  |  Size: 91 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 86 KiB

After

Width:  |  Height:  |  Size: 86 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 88 KiB

After

Width:  |  Height:  |  Size: 88 KiB

+2 -2
View File
@@ -56,7 +56,7 @@ def main():
bar=page.get_by_role('progressbar',name='当前阶段进度')
assert bar.get_attribute('aria-valuenow') is None
assert page.locator('progress').count()==0
assert page.get_by_text('此操作没有可靠百分比,正在显示真实阶段与耗时。',exact=True).count()==1
assert page.get_by_text('正在处理,请保持设备供电。',exact=True).count()==1
page.screenshot(path=str(ROOT/'screenshots/install-activity-debug-zh.png'))
page.evaluate("window.__emitFixture({stage:'openwrt_boot',status:'waiting_user',revision:13,details:{host:'192.168.9.1',reboot_manually:true}})")
settle(page);layout(page)
@@ -69,7 +69,7 @@ def main():
confirm=page.get_by_role('button',name='我已进入 OpenWrt,开始校验',exact=True)
assert confirm.bounding_box()['y']+confirm.bounding_box()['height']<page.locator('.log-panel').bounding_box()['y']
page.get_by_label('设备管理 IP / 主机名').fill('192.168.9.22')
page.get_by_label('SSH root 密码(仅在内存中使用)').fill('fixture-private')
page.get_by_label('SSH root 密码(不保存)').fill('fixture-private')
page.screenshot(path=str(ROOT/'screenshots/manual-restart-log-zh.png'))
confirm.click();settle(page)
assert page.evaluate("window.__fixture.calls.filter(c=>c.command==='verify_openwrt').at(-1).params")=={'transaction':'a'*32,'host':'192.168.9.22','password':'fixture-private'}
+4
View File
@@ -46,6 +46,8 @@ def main():
dialog.get_by_role('textbox',name='搜索使用指南').fill('Magisk')
assert dialog.locator('.help-topics button').count()>=1
dialog.get_by_role('textbox',name='搜索使用指南').fill('')
dialog.get_by_role('button',name='更新与自动重启',exact=True).click()
dialog.get_by_text('不要因为重启期间连接不上而重新执行更新。',exact=True).wait_for()
dialog.get_by_role('button',name='连接与常见问题',exact=True).click()
dialog.get_by_text('电脑记录和导出备份都丢失时',exact=False).wait_for()
assert dialog.locator('article').evaluate('(el)=>el.scrollHeight>el.clientHeight')
@@ -84,6 +86,8 @@ def main():
page.keyboard.press('F1')
dialog=page.get_by_role('dialog',name='Help and user guide');dialog.wait_for();settle(page)
bounded_dialog(page)
dialog.get_by_role('button',name='Updates and automatic restart',exact=True).click()
dialog.get_by_text('Do not start another update because the device is unreachable during restart.',exact=True).wait_for()
dialog.get_by_role('button',name='Connection and troubleshooting',exact=True).click()
dialog.get_by_text('this version cannot reconstruct a record from the device alone',exact=False).wait_for()
page.evaluate("window.__emitFixture({stage:'root_permission',status:'waiting_user'})");settle(page)
+20
View File
@@ -0,0 +1,20 @@
"""Run the actual ARM64 frozen protocol backend without opening device transports."""
import json
from pathlib import Path
import subprocess
import tempfile
artifact = Path(__file__).resolve().parents[1]/'artifacts/macos-arm64'
backend = artifact/'tools/macos/backend/openwrt-backend'
assert 'arm64' in subprocess.check_output(['lipo','-archs',str(backend)],text=True)
with tempfile.TemporaryDirectory() as folder:
request = json.dumps({'protocol':1,'id':1,'command':'hello','params':{}})+'\n'
result = subprocess.run([str(backend),'--package-root',folder,'--data-dir',str(Path(folder)/'state')],
input=request,text=True,capture_output=True,timeout=30)
assert result.returncode == 0,result.stderr
replies = [json.loads(line) for line in result.stdout.splitlines()]
reply = next(row for row in replies if row.get('type')=='response')
assert reply['data']['ok'],reply
print(json.dumps(reply))
subprocess.run([str(artifact/'tools/macos/adb'),'version'],check=True)
print('Native ARM64 backend/ADB smoke passed; no device connection opened.')
Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

+46 -7
View File
@@ -62,7 +62,7 @@ fn write_log(state: State<'_, Arc<Bridge>>, path: String, text: String) -> Resul
#[tauri::command]
fn open_data(state: State<'_, Arc<Bridge>>) -> Result<(), String> {
// Fixed directory, never a shell string supplied by the webview.
Command::new("explorer.exe").arg(&state.directory).spawn().map_err(|e|e.to_string())?;
open_native(&state.directory)?;
Ok(())
}
@@ -73,20 +73,55 @@ fn open_repository(repository: String) -> Result<(), String> {
"mu300" => "https://github.com/dikeckaan/mu300-linux",
_ => return Err("Unknown project repository".into()),
};
Command::new("explorer.exe").arg(url)
.spawn().map_err(|e|e.to_string())?;
open_native(url)?;
Ok(())
}
fn open_native(target: impl AsRef<std::ffi::OsStr>) -> Result<(), String> {
#[cfg(target_os = "windows")] let opener = "explorer.exe";
#[cfg(target_os = "macos")] let opener = "open";
#[cfg(not(any(target_os = "windows", target_os = "macos")))] let opener = "xdg-open";
Command::new(opener).arg(target).spawn().map_err(|e|e.to_string())?;
Ok(())
}
fn data_directory() -> PathBuf {
#[cfg(target_os = "macos")]
return std::env::var_os("HOME").map(PathBuf::from).unwrap_or_else(std::env::temp_dir)
.join("Library/Application Support/OpenWrt-Installer");
#[cfg(not(target_os = "macos"))]
return std::env::var_os("LOCALAPPDATA").map(PathBuf::from).unwrap_or_else(std::env::temp_dir).join("OpenWrt-Installer");
}
fn distribution_root(executable: &std::path::Path) -> Result<PathBuf, String> {
#[cfg(target_os = "macos")]
for ancestor in executable.ancestors() {
if ancestor.extension().is_some_and(|ext| ext == "app") {
let root = ancestor.parent().ok_or("Application has no parent directory")?;
if root.join("desktop/manifest.json").is_file() { return Ok(root.to_path_buf()); }
// Finder may translocate quarantined applications. Ask for the
// extracted package rather than guessing its original location.
return rfd::FileDialog::new().set_title("Select extracted OpenWrt package / 选择完整解压的安装包")
.pick_folder().ok_or_else(|| "No package selected".into());
}
}
executable.parent().map(|p|p.to_path_buf()).ok_or_else(|| "Executable has no directory".into())
}
fn main() {
let directory = std::env::var_os("LOCALAPPDATA").map(PathBuf::from).unwrap_or_else(std::env::temp_dir).join("OpenWrt-Installer");
let directory = data_directory();
let bridge = Arc::new(Bridge {input:Mutex::new(None),pending:Mutex::new(HashMap::new()),sequence:AtomicU64::new(1),busy:AtomicBool::new(false),directory,export_log:Mutex::new(None)});
let setup_state = bridge.clone();
let app = tauri::Builder::default().manage(bridge.clone())
.invoke_handler(tauri::generate_handler![backend_request,pick_package,pick_recovery,save_backup,save_log,write_log,open_data,open_repository])
.setup(move |app| {
let root = std::env::current_exe()?.parent().ok_or("Executable has no directory")?.to_path_buf();
let mut process = Command::new(root.join("tools/backend/openwrt-backend.exe"));
let executable = std::env::current_exe()?;
let root = distribution_root(&executable).map_err(std::io::Error::other)?;
#[cfg(target_os = "macos")]
let backend = "tools/macos/backend/openwrt-backend";
#[cfg(not(target_os = "macos"))]
let backend = "tools/backend/openwrt-backend.exe";
let mut process = Command::new(root.join(backend));
process.args(["--package-root", &root.to_string_lossy(), "--data-dir", &setup_state.directory.to_string_lossy()]);
process.stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::null());
#[cfg(windows)] { use std::os::windows::process::CommandExt; process.creation_flags(0x08000000); }
@@ -141,7 +176,11 @@ fn main() {
if matches!(event,tauri::RunEvent::Exit) {bridge.input.lock().unwrap().take();}
}),
Err(error) => {
rfd::MessageDialog::new().set_title("OpenWrt Installer / WebView2").set_description(format!("Cannot start the system WebView2. Install Microsoft Edge WebView2 Evergreen Runtime and reopen the installer.\n无法启动系统 WebView2。请安装 Microsoft Edge WebView2 Evergreen Runtime 后重试。\nhttps://developer.microsoft.com/microsoft-edge/webview2/\n\n{error}")).set_level(rfd::MessageLevel::Error).show();
#[cfg(target_os = "macos")]
let message = format!("Cannot start OpenWrt Installer. Keep the app beside tools and payload in the extracted package.\n无法启动安装器,请将 app 与 tools、payload 一起保留在完整解压目录。\n\n{error}");
#[cfg(not(target_os = "macos"))]
let message = format!("Cannot start the system WebView2. Install Microsoft Edge WebView2 Evergreen Runtime and reopen the installer.\n无法启动系统 WebView2。请安装 Microsoft Edge WebView2 Evergreen Runtime 后重试。\nhttps://developer.microsoft.com/microsoft-edge/webview2/\n\n{error}");
rfd::MessageDialog::new().set_title("OpenWrt Installer").set_description(message).set_level(rfd::MessageLevel::Error).show();
}
}
}
+1
View File
@@ -13,6 +13,7 @@ export function helpTopics(language: Language) {
{id:'purpose', title:zh ? '选择安装方式' : 'Choose your purpose', markdown:sections.get(zh ? '选择用途' : 'Choose your purpose')},
{id:'storage', title:zh ? 'TF 卡与内置容量' : 'TF card and capacity', markdown:zh ? `### TF 卡\n\n${sections.get('TF 卡')}\n\n### 独立内置分区\n\n${sections.get('独立内置分区')}` : sections.get('Storage and capacity')},
{id:'reset', title:zh ? 'Android 重置后续装' : 'Resume after Android reset', markdown:sections.get(zh ? '加密 userdata:重置后自动续装' : 'Encrypted userdata and reset')},
{id:'update', title:zh ? '更新与自动重启' : 'Updates and automatic restart', markdown:sections.get(zh ? '更新与自动重启' : 'Updates and automatic restart')},
{id:'recovery', title:zh ? '安装记录与失败恢复' : 'Records and recovery', markdown:sections.get(zh ? '暂停、关闭与失败恢复' : 'Recovery and results')},
{id:'faq', title:zh ? '连接与常见问题' : 'Connection and troubleshooting', markdown:sections.get(zh ? '连接与常见问题' : 'Connection and troubleshooting')},
].map(topic => ({...topic, markdown:topic.markdown || ''}));
+2 -2
View File
@@ -10,7 +10,7 @@ export const helpStrings = {
['首次安装从“安装 OpenWrt”开始。TF 卡只格式化选定目标,不重新划卡;内置分区会先检查未分配空间。','核对最终计划里的机型、写入目标、Android 保留空间和数据影响。需要重置时,Android 用户数据会被清空。','已装好 OpenWrt 时可选择更新或临时启动;重装和有 F2FS 损坏风险的实验性镜像放在高级选项。'],
['首次离线分区准备可能需要数分钟,之后会自动重启。预期断线、Android 初始化和授权都是等待状态。','重置后完成 Android 初始化、开启 USB 调试并允许授权。已有 root 会直接使用;只有 root 不可用时才需要恢复 Magisk。','安装记录自动保存在电脑。关闭或重启后从“继续未完成的安装”恢复;换电脑前导出完整事务与备份。电脑记录和备份都丢失时,目前无法仅凭设备自动重建续装记录。'],
],
noAction:'本引导只作说明,不会操作设备。最终安装仍需单独确认。', currentHelp:'查看当前步骤帮助',
noAction:'开始安装前,请核对设备、写入目标和数据影响,并备份重要文件。', currentHelp:'查看当前步骤帮助',
},
en: {
help:'Help and user guide', helpIntro:'Available offline. Browse a topic or search for connection, authorization or recovery help.', close:'Close help', closeGuide:'Close getting started',
@@ -23,6 +23,6 @@ export const helpStrings = {
['Use Install OpenWrt for a first installation. TF installation formats only the selected target without repartitioning the card. Internal installation checks unallocated space first.','Review the model, write target, retained Android space and data impact in the final plan. A required Android reset erases its user data.','For installed OpenWrt, choose update or a one-time boot. Reinstallation and the experimental image option, which can damage F2FS, live under Advanced options.'],
['The first offline preparation may take several minutes and then reboot automatically. Expected USB disconnects, Android setup and authorization are waiting states.','After a reset, complete Android setup, enable USB debugging and grant authorization. Working root is accepted immediately; restore Magisk only if root is unavailable.','Installation records are saved automatically on the computer. After closing or restarting, choose Continue an unfinished installation. Export the full transaction and backups before moving computers. If both records and backups are lost, this version cannot reconstruct a record from the device alone.'],
],
noAction:'This guide does not operate the device. Installation still requires a separate final confirmation.', currentHelp:'Help for this step',
noAction:'Before installing, check the device, write target and data impact, and back up important files.', currentHelp:'Help for this step',
},
};
+12 -12
View File
@@ -4,21 +4,21 @@ export const strings = {
installerAuthor:'安装器作者',
starTitle:'喜欢这个项目?点个 Star 吧', starDescription:'你的 Star,是持续维护与更新的动力。', starAction:'去 GitHub 给项目点 Star',
supportDescription:'本安装器可以被打赏。如果它帮到了你,欢迎自愿赞赏,支持 Minikano 的开发与维护。', supportOptional:'自愿赞赏,可直接关闭继续使用。', continueUsing:'继续使用', supportImageAlt:'Minikano 赞赏码', supportImageLoading:'正在加载赞赏码…', supportImageUnavailable:'赞赏码暂时无法显示,可以稍后从侧栏重新打开。',
copyDiagnostics:'复制诊断信息给开发者', phase:'阶段', stageProgress:'当前阶段进度', noPercentage:'此操作没有可靠百分比,正在显示真实阶段与耗时。',
copyDiagnostics:'复制诊断信息给开发者', phase:'阶段', stageProgress:'当前阶段进度', noPercentage:'正在处理,请保持设备供电。',
installMethod:'安装方式',
noDevicesShort:'未发现设备', inspectNeedsPackage:'可以先刷新并选择设备;检查设备和安装前仍需校验安装包。',
copied:'日志已复制', exportedLog:'日志已导出', exportedBackup:'事务与备份已导出', imported:'恢复记录已导入', openedData:'事务目录已打开', inspected:'设备检查完成', refreshed:'设备列表已刷新', noDevices:'未发现设备,请连接 USB 并开启调试。', multipleDevices:'检测到多台设备,请明确选择本次操作的设备。', pauseRequested:'已请求暂停,将在安全边界生效。', dismiss:'关闭提示', notifications:'操作通知', deviceStates:{device:'已连接',unauthorized:'等待调试授权',offline:'离线'},
title:'OpenWrt 安装器', subtitle:'安装、更新与恢复', home:'开始', package:'安装包', choosePackage:'选择安装包目录', verify:'校验安装包', verified:'校验通过',
device:'设备', refresh:'刷新设备', select:'请选择设备', connect:'通过 USB 连接设备,开启调试并允许电脑访问。', inspect:'检查设备',
install:'安装 OpenWrt', installDesc:'选择 TF 卡或独立内置分区,逐步完成安装。', update:'更新 OpenWrt', updateDesc:'保留设置、已有容量和本机固件。',
resume:'继续未完成的安装', resumeDesc:'从电脑上的事务记录恢复,包括 Android 重置后的续装。', boot:'临时启动已安装的 OpenWrt', bootDesc:'仅修改 misc 中的试启动信息。默认启动设置保持原值。',
resume:'继续未完成的安装', resumeDesc:'从电脑上的安装记录继续,也可用于 Android 重置后续装。', boot:'临时启动已安装的 OpenWrt', bootDesc:'仅本次启动进入 OpenWrt,不改变默认启动设置。',
advanced:'高级选项', advancedDesc:'重装已有分区或使用实验性 userdata 镜像。', tf:'TF 卡', part:'独立内置分区', reinstall:'重装已有内置分区', image:'userdata 镜像',
experimental:'实验性功能:可能损坏 Android F2FS 文件系统。', size:'OpenWrt 分配容量(GiB)', grow:'使用全部已分配的 OpenWrt 分区容量', growHelp:'扩满所选分区。分配大小由上方容量决定。',
theme:'主题', system:'跟随系统', light:'浅色', dark:'深色', language:'语言', model:'实际型号', os:'当前系统', slot:'当前槽位', root:'Root 状态', ready:'已就绪', unavailable:'未就绪', unknown:'尚未读取',
plan:'查看安装计划', review:'确认安装计划', target:'写入目标', android:'Android 保留空间', allocation:'OpenWrt 分配空间', impact:'数据影响',
wipe:'Android 应用、账号、照片和内部存储将全部清空。请先备份个人数据。', preserve:'保留 Android 用户数据。', tfErase:'会格式化所选 TF 目标,卡上该分区的数据会被替换。不会重新划分 TF 卡。',
reinstallErase:'已有 OpenWrt 系统与设置会被替换,Android 用户数据保留。', imageImpact:'创建镜像,保留原有镜像备份。需额外安装临时空间。',
updateImpact:'保留设置、分区容量和本机固件;上传通过 SSH,设备端互斥锁保护提交。提交后设备会自动重启以应用更新,网络会暂时断开。', bootImpact:'临时试启动;不挂载、不写入 OpenWrt 根分区。失败时由原启动策略回退。',
updateImpact:'保留设置、分区容量和本机固件。设备会自动重启以应用更新,网络会暂时断开,请保持供电。', bootImpact:'仅本次启动进入 OpenWrt,保留已有系统和设置,不改变默认启动设置。',
updateReboot:'更新已提交,设备将自动重启', updateReconnecting:'设备正在重启,等待重新连接', updateRebootDesc:'设备将自动重启以应用更新,期间网络会暂时断开。请保持供电并等待,安装器将在确认设备重启、重新连接并校验实际容量后显示完成。',
updateNext:'设备已重启,更新已通过校验。请打开管理地址检查服务;原设置、容量和本机固件保留,事务记录仍保存在电脑上。',
firstBoot:'首次启动会进行离线分区准备,可能需要数分钟,完成后设备会自动重启一次。',
@@ -35,31 +35,31 @@ export const strings = {
bootConfirmed:'已确认进入 OpenWrt。请核对这台设备的管理地址与 SSH root 密码,并将电脑连接到它的网络。',
pause:'在安全边界暂停', unsafe:'正在写入,请保持供电。暂停将在当前操作完成后生效。', closeBlocked:'任务仍在执行。请先在安全边界暂停,再关闭窗口。',
logs:'详细日志', copy:'复制', exportLog:'导出日志', exportBackup:'导出事务与备份', openData:'打开事务目录', import:'导入恢复目录',
noRecords:'没有可恢复的事务。若电脑记录丢失,请导入完整备份目录;设备标记不足以证明安装计划时,安装器会停止。', continue:'继续安装', retry:'复核并重试',
noRecords:'没有未完成的安装记录。若曾导出备份,请先解压,再导入完整恢复目录。', continue:'继续安装', retry:'复核并重试',
success:'OpenWrt 已安装并通过校验', successBoot:'OpenWrt 已临时启动', successUpdate:'OpenWrt 已更新并通过校验', actual:'实际文件系统容量', visit:'管理地址', next:'下一步', nextDesc:'打开管理地址,修改管理员与无线密码。备份与事务会保留在电脑上。',
host:'设备管理 IP / 主机名', password:'SSH root 密码(仅在内存中使用)', checkUpdate:'检查 OpenWrt', recommended:'推荐',
noBackend:'无法连接本地后端。请从完整解压后的安装包运行 OpenWrt-Installer.exe。', error:'操作未完成', elapsed:'阶段用时', bytes:'已传输', speed:'速度', packageHint:'请完整解压安装包;载荷校验通过后才能操作设备。',
host:'设备管理 IP / 主机名', password:'SSH root 密码(不保存)', checkUpdate:'检查 OpenWrt', recommended:'推荐',
noBackend:'安装器启动失败。请完整解压安装包,再运行 OpenWrt-Installer.exe。', error:'操作未完成', elapsed:'阶段用时', bytes:'已传输', speed:'速度', packageHint:'请完整解压安装包;载荷校验通过后才能操作设备。',
},
en: {
author:'Author', qqGroup:'QQ group ', copyGroup:'Copy group number', groupCopied:'Group number copied', repositoryOpened:'Project repository opened', support:'Support the author', closeSupport:'Close support notice',
installerAuthor:'Installer author',
starTitle:'Enjoying the project? Give it a Star', starDescription:'Your Star encourages continued maintenance and updates.', starAction:'Star the project on GitHub',
supportDescription:'This installer accepts donations. If it helped you, you are welcome to support Minikano’s development and maintenance.', supportOptional:'Donations are optional. Close to continue.', continueUsing:'Continue', supportImageAlt:'Minikano donation code', supportImageLoading:'Loading donation code…', supportImageUnavailable:'The donation code is unavailable. You can reopen it from the sidebar later.',
copyDiagnostics:'Copy diagnostics for the developer', phase:'Phase', stageProgress:'Current phase progress', noPercentage:'This operation has no reliable percentage. The phase and elapsed time are shown.',
copyDiagnostics:'Copy diagnostics for the developer', phase:'Phase', stageProgress:'Current phase progress', noPercentage:'Processing. Keep the device powered.',
installMethod:'Installation method',
noDevicesShort:'No devices found', inspectNeedsPackage:'You can refresh and select a device now. Verify the package before inspecting or installing.',
copied:'Log copied', exportedLog:'Log exported', exportedBackup:'Transaction and backups exported', imported:'Recovery record imported', openedData:'Transaction folder opened', inspected:'Device inspection complete', refreshed:'Device list refreshed', noDevices:'No devices found. Connect USB and enable debugging.', multipleDevices:'Multiple devices found. Select the device for this operation.', pauseRequested:'Pause requested. It will take effect at a safe boundary.', dismiss:'Dismiss notification', notifications:'Operation notifications', deviceStates:{device:'Connected',unauthorized:'Awaiting debugging authorization',offline:'Offline'},
title:'OpenWrt Installer',subtitle:'Install, update and recover',home:'Start',package:'Package',choosePackage:'Choose package folder',verify:'Verify package',verified:'Verified',
device:'Device',refresh:'Refresh devices',select:'Select a device',connect:'Connect by USB, enable debugging and authorize this computer.',inspect:'Inspect device',
install:'Install OpenWrt',installDesc:'Install step by step on a TF card or an independent internal partition.',update:'Update OpenWrt',updateDesc:'Keep settings, existing capacity and device firmware.',
resume:'Continue an unfinished installation',resumeDesc:'Recover from a computer transaction, including after an Android reset.',boot:'Boot installed OpenWrt once',bootDesc:'Change only the trial selection in misc. Keep the existing boot default.',
resume:'Continue an unfinished installation',resumeDesc:'Continue from a saved installation record, including after an Android reset.',boot:'Boot installed OpenWrt once',bootDesc:'Start OpenWrt for this boot without changing the default system.',
advanced:'Advanced options',advancedDesc:'Reinstall an internal partition or use an experimental userdata image.',tf:'TF card',part:'Independent internal partition',reinstall:'Reinstall internal partition',image:'Userdata image',
experimental:'Experimental: may damage the Android F2FS filesystem.',size:'OpenWrt allocation (GiB)',grow:'Use all capacity allocated to the OpenWrt partition',growHelp:'Grow to fill the selected partition. The allocation above controls its size.',
theme:'Theme',system:'System',light:'Light',dark:'Dark',language:'Language',model:'Actual model',os:'Current system',slot:'Current slot',root:'Root status',ready:'Ready',unavailable:'Not ready',unknown:'Not read yet',
plan:'Review installation plan',review:'Confirm installation plan',target:'Write target',android:'Android retained space',allocation:'OpenWrt allocation',impact:'Data impact',
wipe:'All Android apps, accounts, photos and internal storage will be erased. Back up personal files first.',preserve:'Preserve Android user data.',tfErase:'Format the selected TF target and replace its data. The card is not repartitioned.',
reinstallErase:'Replace the installed OpenWrt system and settings. Preserve Android user data.',imageImpact:'Create an image and retain the previous image as a backup. Temporary staging space is also required.',
updateImpact:'Preserve settings, partition capacity and local firmware. Upload over SSH; a device upgrade lock protects commit. The device automatically restarts to apply the update, briefly disconnecting its network.',bootImpact:'Trial boot only. Do not mount or write the OpenWrt root partition. Existing boot policy handles fallback.',
updateImpact:'Keep settings, partition capacity and local firmware. The device restarts after updating and its network briefly disconnects. Keep power connected.',bootImpact:'Start OpenWrt for this boot. Keep existing systems, settings and the default boot choice.',
updateReboot:'Update submitted; device restarting', updateReconnecting:'Device restarting; waiting to reconnect', updateRebootDesc:'The device will automatically restart to apply the update and its network will briefly disconnect. Keep power connected. Completion follows a confirmed restart, reconnection and actual-capacity verification.',
updateNext:'The device restarted and the update passed verification. Open its management address to check services. Settings, capacity and local firmware are retained; the transaction remains on this computer.',
firstBoot:'The first boot performs offline partition preparation. This may take several minutes; the device will reboot automatically once it finishes.',
@@ -75,10 +75,10 @@ export const strings = {
bootConfirmed:'OpenWrt boot confirmed. Check this device’s management address and SSH root password, and connect this computer to its network.',
pause:'Pause at a safe boundary',unsafe:'A write is in progress. Keep power connected. Pause takes effect after the current operation finishes.',closeBlocked:'A task is still active. Pause at a safe boundary before closing the window.',
logs:'Detailed log',copy:'Copy',exportLog:'Export log',exportBackup:'Export transaction and backups',openData:'Open transaction folder',import:'Import recovery folder',
noRecords:'No saved transactions. If computer records were lost, import a full backup folder. Insufficient device evidence stops installation.',continue:'Continue installation',retry:'Recheck and retry',
noRecords:'No unfinished installation records. If you exported a backup, extract it and import the complete recovery folder.',continue:'Continue installation',retry:'Recheck and retry',
success:'OpenWrt installed and verified',successBoot:'OpenWrt started for this boot',successUpdate:'OpenWrt updated and verified',actual:'Actual filesystem capacity',visit:'Management address',next:'Next steps',nextDesc:'Open the management address and change administrator and wireless passwords. Backups and the transaction remain on this computer.',
host:'Device management IP / hostname',password:'SSH root password (held only in memory)',checkUpdate:'Inspect OpenWrt',recommended:'Recommended',
noBackend:'Cannot connect to the local backend. Run OpenWrt-Installer.exe from a fully extracted package.',error:'Operation incomplete',elapsed:'Stage elapsed',bytes:'Transferred',speed:'Speed',packageHint:'Extract the complete package. Payload verification is required before device operations.',
host:'Device management IP / hostname',password:'SSH root password (not saved)',checkUpdate:'Inspect OpenWrt',recommended:'Recommended',
noBackend:'The installer could not start. Extract the complete package, then run OpenWrt-Installer.exe.',error:'Operation incomplete',elapsed:'Stage elapsed',bytes:'Transferred',speed:'Speed',packageHint:'Extract the complete package. Payload verification is required before device operations.',
}
};
export type Language = keyof typeof strings;
+1 -1
View File
@@ -90,7 +90,7 @@ function App() {
}
if (next.stage === 'openwrt_boot' && verificationTransaction.current !== next.id) {
verificationTransaction.current = next.id;
setHost(next.details?.host || next.choices.host || (next.package.adapter === 'e5' ? '192.168.9.1' : next.device.profile === 'u30air' ? '192.168.78.1' : '192.168.77.1'));
setHost(next.details?.host || next.choices.host || (next.package.adapter === 'e5' ? '192.168.9.1' : '192.168.77.1'));
}
setTx(next);
}, [append, t]);
+2 -1
View File
@@ -182,12 +182,13 @@ for f in sbin/block lib/libblkid-tiny.so etc/init.d/fstab; do
[ -s "$R/$f" ] || { echo "patched block-mount required file missing: $f" >&2; exit 1; }
done
chmod 0755 $R/opt/mu300/bin/cpu-voltage-platform $R/etc/init.d/mu300-cpu-driver
for helper in mu300-data-sim-u30 mu300-sim-u30 mu300-sim2-start mu300-sim2-warmup; do
for helper in mu300-data-sim-u30 mu300-sim-u30 mu300-sim2-start mu300-sim2-warmup u30air-led-status; do
[ -s "$R/opt/mu300/bin/$helper" ] || { echo "missing U30 helper: $helper" >&2; exit 1; }
chmod 0755 "$R/opt/mu300/bin/$helper"
done
chroot "$R" /bin/sh -c "command -v flock >/dev/null" || { echo "missing native SIM flock dependency" >&2; exit 1; }
[ -s "$R/opt/mu300/lib/sim-config.sh" ] || { echo "missing U30 SIM configuration library" >&2; exit 1; }
chmod 0755 $R/etc/hotplug.d/power_supply/70-mu300-led
chmod 0755 $R/opt/mu300/bin/mu300-platform-config
chmod 0755 $R/opt/mu300/bin/v50-led-status
chmod 0755 $R/opt/mu300/bin/openwrt-board-check
@@ -18,6 +18,7 @@ var CSS = `
.mud-sim-page .mud-sim-panel h3{margin:0 0 10px;padding:0;border:0;font-size:1rem;font-weight:600;color:var(--text,#222)}
.mud-sim-page .mud-sim-intro{margin:0 0 16px;line-height:1.65}
.mud-sim-page .mud-data-sim{display:grid;gap:10px;margin:0;padding:14px;border:1px solid var(--hairline,var(--border-color,#ddd));border-radius:10px;min-width:0}
.mud-sim-page .mud-data-sim + .mud-data-sim{margin-top:16px}
.mud-sim-page .mud-data-sim-controls{display:flex;align-items:center;flex-wrap:wrap;gap:8px 12px}
.mud-sim-page .mud-data-sim-controls label{flex:1;min-width:110px;font-weight:600;margin:0;color:var(--text,#222)}
.mud-sim-page .mud-data-sim-controls input[type="checkbox"]{width:18px;height:18px;min-height:0;margin:0;flex:none;accent-color:var(--brand,var(--primary,#2f7bf6))}
+4
View File
@@ -0,0 +1,4 @@
#!/bin/sh
[ "$ACTION" = change ] || [ "$ACTION" = add ] || exit 0
[ "$(/opt/mu300/bin/mu300-device 2>/dev/null)" = u30air ] || exit 0
/opt/mu300/bin/led-status battery
+1 -1
View File
@@ -1,5 +1,5 @@
#!/bin/sh
# First boot: one LAN for USB and Wi-Fi (192.168.77.1/24 on an F50, 192.168.78.1/24 on a U30 Air), cellular WAN through the modem, hostname, USB console.
# First boot: one LAN for USB and Wi-Fi (192.168.77.1/24 on all supported boards), cellular WAN through the modem, hostname, USB console.
# lan ip6assign 64: a carrier hands out one /64 (the wan_6 that mu300cell adds), and the default /60 request
# would leave the LAN without IPv6
usb_host_mac=$(cat /run/mu300-usb-host-mac 2>/dev/null)
@@ -21,6 +21,12 @@ const labels = {
'LED Configuration': ['LED 配置', 'LED yapılandırması'],
'Configure physical status lamps and optional LED trigger actions.': ['配置物理状态灯与可选的 LED 触发动作。', 'Fiziksel durum ışıklarını ve isteğe bağlı LED tetikleyicilerini yapılandırın.'],
'Physical status lamps': ['物理状态灯', 'Fiziksel durum ışıkları'],
'Battery lamp': ['电池灯', 'Pil ışığı'],
'Battery lamp brightness': ['电池灯亮度', 'Pil ışığı parlaklığı'],
'LED timeout (seconds)': ['状态灯自动熄灭(秒)', 'LED kapanma süresi (saniye)'],
'While charging lamps stay on. Otherwise 0 keeps them on; press the power key to show them again.': ['充电时状态灯保持点亮;未充电时 0 表示常亮,熄灭后短按电源键可再次点亮。', 'Şarjda ışıklar açık kalır. Diğer durumlarda 0 sürekli açık tutar; yeniden göstermek için güç tuşuna basın.'],
'U30 Air: network blue on 4G, white on 5G, red without data. Wi-Fi blue on 2.4 GHz, white on 5 GHz. These lamps support on/off only.': ['U30 Air:网络灯 4G 蓝色、5G 白色、无数据红色;Wi-Fi 灯 2.4 GHz 蓝色、5 GHz 白色。这两组灯仅支持开关。', 'U30 Air: 4G mavi, 5G beyaz, veri yoksa kırmızı. Wi-Fi: 2.4 GHz mavi, 5 GHz beyaz. Bu ışıklar yalnızca açılıp kapatılabilir.'],
'Charging: breathing blue; full or normal battery: white; low battery: blinking red.': ['充电时蓝色呼吸;充满或正常电量时白色;低电量时红色闪烁。', 'Şarjda yumuşakça parlayan mavi; dolu veya normal pil beyaz; düşük pil yanıp sönen kırmızı.'],
'Signal lamp (LTE / 5G / no service)': ['信号灯(4G / 5G / 无信号)', 'Sinyal ışığı (4G / 5G / servis yok)'],
'Signal lamp brightness': ['信号灯亮度', 'Sinyal ışığı parlaklığı'],
'Wi-Fi hotspot lamp': ['Wi-Fi 热点灯', 'Wi-Fi erişim noktası ışığı'],
@@ -80,6 +86,7 @@ return view.extend({
let m, s, o;
const awRgb = !!(leds.aw_led && leds.red && leds.green && leds.blue);
const v50 = !!leds['v50:net1:white'];
const u30air = !!(leds['zte-ldo0'] && leds['zte-ldo1'] && leds['zte-ldo2'] && leds.net_blue);
let wifiMax = leds['keyboard-backlight'] && Number(leds['keyboard-backlight'].max_brightness);
if (!Number.isInteger(wifiMax) || wifiMax < 1 || wifiMax > 255) wifiMax = 255;
const triggers = [];
@@ -97,15 +104,19 @@ return view.extend({
s = m.section(form.NamedSection, 'mu300_leds', 'mu300_leds', label('Physical status lamps'));
s.anonymous = true;
s.addremove = false;
if (u30air) s.description = label('U30 Air: network blue on 4G, white on 5G, red without data. Wi-Fi blue on 2.4 GHz, white on 5 GHz. These lamps support on/off only.');
if (v50) s.description = label('Each network lamp shows its own SIM status. Wi-Fi: 5 GHz white, 2.4 GHz blue.');
o = s.option(form.Flag, 'signal', label(v50 ? 'NET1 lamp (SIM 1)' : 'Signal lamp (LTE / 5G / no service)'));
o.default = '1';
o.rmempty = false;
if (!u30air) {
o = s.option(form.Value, 'signal_brightness', label(v50 ? 'NET1 brightness' : 'Signal lamp brightness'),
label('0–255; 0 is dark. LTE stays blue, 5G white, and no service red.'));
o.datatype = 'range(0,255)';
o.default = '255';
o.rmempty = false;
}
if (v50) {
o = s.option(form.Flag, 'signal2', label('NET2 lamp (SIM 2)'));
o.default = '1'; o.rmempty = false;
@@ -117,6 +128,7 @@ return view.extend({
o = s.option(form.Flag, 'wifi', label('Wi-Fi hotspot lamp'));
o.default = '1';
o.rmempty = false;
if (!u30air) {
o = s.option(form.Value, 'wifi_brightness', label('Wi-Fi lamp brightness'),
label('0 is dark. Hardware maximum: ') + wifiMax);
o.datatype = 'range(0,' + wifiMax + ')';
@@ -124,6 +136,17 @@ return view.extend({
o.rmempty = false;
}
}
if (u30air) {
o = s.option(form.Flag, 'battery', label('Battery lamp'), label('Charging: breathing blue; full or normal battery: white; low battery: blinking red.'));
o.default = '1'; o.rmempty = false;
o = s.option(form.Value, 'battery_brightness', label('Battery lamp brightness'));
o.datatype = 'range(0,255)'; o.default = '255'; o.rmempty = false;
o = s.option(form.Value, 'timeout', label('LED timeout (seconds)'), label('While charging lamps stay on. Otherwise 0 keeps them on; press the power key to show them again.'));
o.datatype = 'range(0,86400)'; o.default = '60'; o.rmempty = false;
}
s = m.section(form.GridSection, 'led', '');
s.anonymous = true;
s.addremove = true;
@@ -134,6 +157,7 @@ return view.extend({
s.option(form.Value, 'name', label('Name'));
o = s.option(form.ListValue, 'sysfs', label('LED Name'));
Object.keys(leds).sort().forEach(function(name) {
if (u30air && /^(sc27xx:|zte-ldo|net_|wifi_|pwr_green$|keyboard-backlight$)/.test(name)) return;
o.value(name);
});
o = s.option(form.ListValue, 'trigger', label('Trigger'));
+1 -1
View File
@@ -1,5 +1,5 @@
#!/bin/bash
# One LAN for USB and Wi-Fi clients: br-lan (192.168.77.1/24 on an F50, 192.168.78.1/24 on a U30 Air, unless
# One LAN for USB and Wi-Fi clients: br-lan (192.168.77.1/24 on an F50, 192.168.77.1/24 on a U30 Air, unless
# lan.conf says otherwise) with usb0 (NCM/ECM gadget, bound in the initramfs, plus rndis0 for Windows)
# and wlan0 (added by hostapd via bridge=br-lan). A single dnsmasq serves DHCP/DNS on the bridge.
set -euo pipefail
+4
View File
@@ -28,6 +28,10 @@ if [ -d "$LED_ROOT/v50:net1:white" ]; then
fi
[ "$(mu300-device 2>/dev/null)" != v50 ] || exit 0
if [ "$(mu300-device 2>/dev/null)" = u30air ]; then
exec "${MU300_U30_LED_BACKEND:-/opt/mu300/bin/u30air-led-status}" "$@"
fi
# --- detect LED paths (F50 sc27xx vs V50 plain)
RGB_WHITE=0
if [ -d "$LED_ROOT/aw_led" ] && [ -d "$LED_ROOT/green" ] && [ -d "$LED_ROOT/blue" ]; then
+1 -1
View File
@@ -2,7 +2,7 @@
# The buttons (Ubuntu and OpenWrt; run by mu300-buttons.service / /etc/init.d/mu300-buttons):
# power, short press wake the LEDs (they go dark after LED_TIMEOUT, see mu300-led)
# power, held 3 s shut down cleanly (the battery-powered U30 Air; the F50 starts again on USB power)
# Wi-Fi key, short press hotspot 2.4 <-> 5 GHz (U30 Air; the Wi-Fi LED shows the band: blue 5, white 2.4)
# Wi-Fi key, short press hotspot 2.4 <-> 5 GHz (U30 Air; the Wi-Fi LED shows the band: white 5, blue 2.4)
# Wi-Fi key, held 3 s hotspot off / on
# mu300-keys reports the presses; its tick every 5 s lets the LEDs time out. Ubuntu's logind leaves the power key
# to this script (/etc/systemd/logind.conf.d/mu300-buttons.conf): it used to power the device off at a touch.
+2 -6
View File
@@ -1,7 +1,3 @@
#!/bin/sh
# The device's default LAN address, when /etc/mu300/lan.conf sets none: the kind of device decides it, so that an
# F50 and a U30 Air on one computer do not collide (boot/init uses the same subnets before switch_root).
case $(${MU300_BIN:-/opt/mu300/bin}/mu300-device) in
u30air) echo 192.168.78.1 ;;
*) echo 192.168.77.1 ;;
esac
# Shared default for all supported boards; explicit LAN configuration takes precedence.
echo 192.168.77.1
+115 -7
View File
@@ -3,7 +3,7 @@
# mu300-led power on|off Linux is up (set at boot, which also wakes the LEDs; cleared at shutdown)
# mu300-led data on|5g|off|error mobile data connected (5g: over 5G) / not connected / no service (no SIM, not
# registered)
# mu300-led wifi on|off the Wi-Fi hotspot is up (U30 Air: blue on 5 GHz, white on 2.4 GHz)
# mu300-led wifi on|off the Wi-Fi hotspot is up (U30 Air: white on 5 GHz, blue on 2.4 GHz)
# mu300-led wake show the LEDs again, for LED_TIMEOUT seconds (the power button, mu300-buttons)
# mu300-led sleep [--if-due] dark now (--if-due: only once the timeout has passed; mu300-buttons asks)
# mu300-led test each LED in turn, 2 s each, with its name (to tell which one is where)
@@ -13,7 +13,7 @@
# battery the PMIC's RGB LED: its "green" channel is white (power: Linux is up), red, blue
# network as ZTE's firmware: blue on 4G (a GPIO, net_blue), white on 5G (LDO VDDCAMA0), red without service
# (the PMIC's keypad backlight sink, "keyboard-backlight" under 5.4 and mainline)
# Wi-Fi white: LDO VDDCAMA1 (2.4 GHz); blue: LDO VDDCAMA2 (5 GHz)
# Wi-Fi white: LDO VDDCAMA1 (5 GHz); blue: LDO VDDCAMA2 (2.4 GHz)
# The LDO ones are zte-ldo0..2 under mainline (leds-zte-ldo) and vddcama0..2_status of ZTE's zte_ldo_leds under
# 5.4; the other GPIO LEDs in its device tree (net_red, net_green, net_white, pwr_green, wifi_*) light nothing,
# under Android too.
@@ -25,6 +25,7 @@
# Every write is best effort: the PMIC rejects a brightness write now and then (mobile-data), and a cosmetic
# LED must never make a service fail.
# (MU300_SYSROOT, MU300_BIN and MU300_LED_CONF are for tests/: a fake /, this directory, a led.conf)
export PATH="$PATH:/opt/mu300/bin:/opt/mu300/busybox-bin:/usr/sbin:/sbin"
R=${MU300_SYSROOT:-}
LEDS=$R/sys/class/leds
STATE=$R/run/mu300/led
@@ -41,7 +42,7 @@ if [ "$DEVICE" = v50 ]; then
fi
case $DEVICE in
u30air) POWER=sc27xx:green DATA=net_blue DATA5G=zte-ldo0 NODATA=keyboard-backlight WIFI5=zte-ldo2 WIFI24=zte-ldo1
u30air) POWER=sc27xx:green DATA=net_blue DATA5G=zte-ldo0 NODATA=keyboard-backlight WIFI5=zte-ldo1 WIFI24=zte-ldo2
DEFAULT_TIMEOUT=60 ;;
*) POWER= DATA=sc27xx:blue DATA5G=sc27xx:blue NODATA= WIFI5= WIFI24= DEFAULT_TIMEOUT=0 ;;
esac
@@ -51,9 +52,40 @@ case $DEVICE in u30air) SIREN="sc27xx:red sc27xx:green sc27xx:blue" ;; *) SIREN=
SIREN_PID=$R/run/mu300/led-siren.pid
TIMEOUT=$(sed -n 's/^LED_TIMEOUT=\([0-9][0-9]*\)$/\1/p' "${MU300_LED_CONF:-/etc/mu300/led.conf}" 2>/dev/null | tail -n1)
TIMEOUT=${TIMEOUT:-$DEFAULT_TIMEOUT}
if [ "$DEVICE" = u30air ]; then
value=$(uci -q get system.mu300_leds.timeout 2>/dev/null)
case $value in ''|*[!0-9]*) ;; *) [ "${#value}" -le 5 ] && [ "$value" -le 86400 ] && TIMEOUT=$value ;; esac
fi
cfg() { uci -q get "system.mu300_leds.$1" 2>/dev/null; }
# A power-supply event and the button timeout may arrive together. Keep the
# power snapshot, desired state and physical writes in one transaction, so an
# event started before unplug cannot restart breathing after timeout darkening.
# flock is already a runtime dependency of the native SIM controller.
if [ "$DEVICE" = u30air ] && [ "${1:-}" != siren ]; then
mkdir -p "$STATE" || exit 0
exec 9>"$STATE/.lock"
flock -w 2 9 || exit 0
fi
external_power() {
[ "$DEVICE" = u30air ] || return 1
local root=${MU300_POWER_SUPPLY_DIR:-$R/sys/class/power_supply} value
if [ -r "$root/bq256xx-charger/online" ]; then
IFS= read -r value < "$root/bq256xx-charger/online"
[ "$value" = 1 ]; return
fi
[ -r "$root/sc27xx-fgu/status" ] || return 1
IFS= read -r value < "$root/sc27xx-fgu/status"
case $value in Charging|Full) return 0 ;; *) return 1 ;; esac
}
KEEP_LIT=0
external_power && KEEP_LIT=1
uptime_s() { cut -d. -f1 "$R/proc/uptime" 2>/dev/null || echo 0; }
awake() {
[ "$KEEP_LIT" != 1 ] || return 0
[ "$TIMEOUT" = 0 ] && return 0
until=$(cat "$STATE/.awake-until" 2>/dev/null) || return 1
[ "$(uptime_s)" -lt "${until:-0}" ]
@@ -65,10 +97,49 @@ vendor_ldo() { # vendor_ldo zte-ldoN: the 5.4 kernel's switch for that LDO, if
}
has_led() { [ -e "$LEDS/$1" ] || vendor_ldo "$1" >/dev/null; }
write() { # write NAME 0|1: the LED itself
if [ ! -e "$LEDS/$1" ] && f=$(vendor_ldo "$1"); then echo "$2" > "$f" 2>/dev/null; return 0; fi
local requested=$2 group= value maximum level pattern
if [ "$DEVICE" = u30air ]; then
case $1 in
net_blue|zte-ldo0|keyboard-backlight) group=signal ;;
zte-ldo1|zte-ldo2) group=wifi ;;
sc27xx:*) group=battery ;;
esac
[ -z "$group" ] || [ "$(cfg "$group")" != 0 ] || requested=0
fi
if [ ! -e "$LEDS/$1" ] && f=$(vendor_ldo "$1"); then echo "$requested" > "$f" 2>/dev/null; return 0; fi
[ -w "$LEDS/$1/brightness" ] || return 0
maximum=$(cat "$LEDS/$1/max_brightness" 2>/dev/null)
case $maximum in ''|*[!0-9]*) maximum=255 ;; esac
value=0
if [ "$requested" = 1 ]; then
value=$maximum
if [ "$DEVICE" = u30air ] && [ "$group" = battery ]; then
level=$(cfg battery_brightness)
case $level in ''|*[!0-9]*) level=255 ;; *) [ "${#level}" -le 3 ] && [ "$level" -le 255 ] || level=255 ;; esac
value=$(( (maximum * level + 127) / 255 ))
fi
fi
# SC27xx provides a hardware rise/hold/fall/rest engine. No animation worker.
if [ "$value" -gt 0 ] && [ "$(cat "$STATE/.battery-breathe" 2>/dev/null)" = "$1" ] &&
grep -qw pattern "$LEDS/$1/trigger"; then
# 2.25 s cycle: quicker ramps and a longer full-brightness hold.
# Keep the requested peak (up to 255); do not overdrive the PMIC.
pattern="0 625 $value 750 0 625 0 250"
if ! grep -q '\[pattern\]' "$LEDS/$1/trigger"; then echo pattern > "$LEDS/$1/trigger"; fi
if [ -w "$LEDS/$1/hw_pattern" ]; then
[ "$(cat "$LEDS/$1/repeat" 2>/dev/null)" = -1 ] || echo -1 > "$LEDS/$1/repeat"
[ "$(cat "$LEDS/$1/hw_pattern" 2>/dev/null)" = "$pattern" ] || echo "$pattern" > "$LEDS/$1/hw_pattern"
return 0
fi
fi
echo none > "$LEDS/$1/trigger" 2>/dev/null
if [ "$2" = 1 ]; then cat "$LEDS/$1/max_brightness" 2>/dev/null; else echo 0; fi > "$LEDS/$1/brightness" 2>/dev/null
echo "$value" > "$LEDS/$1/brightness" 2>/dev/null
if [ "$value" -gt 0 ] && [ "$(cat "$STATE/.battery-blink" 2>/dev/null)" = "$1" ] &&
grep -qw timer "$LEDS/$1/trigger"; then
echo timer > "$LEDS/$1/trigger"
echo 750 > "$LEDS/$1/delay_on"
echo 750 > "$LEDS/$1/delay_off"
fi
return 0
}
set_led() { # set_led NAME 0|1: what it should show; lit only while awake
@@ -91,8 +162,44 @@ show_all() { # every LED as it should be
siren_running() { p=$(cat "$SIREN_PID" 2>/dev/null) && [ -n "$p" ] && kill -0 "$p" 2>/dev/null; }
nap() { sleep "$1" 2>/dev/null || sleep 1; } # (a busybox without fractional sleep)
battery() {
[ "$DEVICE" = u30air ] || return 0
local root=${MU300_POWER_SUPPLY_DIR:-$R/sys/class/power_supply} cap status color channel value previous_power
cap=$(cat "$root/sc27xx-fgu/capacity" 2>/dev/null)
case $cap in ''|*[!0-9]*) return 0 ;; esac
[ "$cap" -le 100 ] || return 0
status=$(cat "$root/sc27xx-fgu/status" 2>/dev/null)
# Charger online changes before the fuel-gauge status sometimes does.
# A stale "Charging"/"Full" must not keep the charging indication alive.
[ "$KEEP_LIT" != 0 ] || status=Discharging
color=sc27xx:green
mkdir -p "$STATE"
previous_power=$(cat "$STATE/.external-power" 2>/dev/null)
echo "$KEEP_LIT" > "$STATE/.external-power"
if [ "$previous_power" = 1 ] && [ "$KEEP_LIT" = 0 ] && [ "$TIMEOUT" != 0 ]; then
echo $(( $(uptime_s) + TIMEOUT )) > "$STATE/.awake-until"
fi
rm -f "$STATE/.battery-blink" "$STATE/.battery-breathe"
case $status in
Charging) color=sc27xx:blue ;;
Full) ;;
*) if [ "$cap" -le 15 ]; then color=sc27xx:red; fi ;;
esac
case "$status:$color" in
Charging:*) echo "$color" > "$STATE/.battery-breathe" ;;
*:sc27xx:red) echo "$color" > "$STATE/.battery-blink" ;;
esac
for channel in sc27xx:red sc27xx:green sc27xx:blue; do
value=0; [ "$channel" != "$color" ] || value=1
if siren_running; then echo "$value" > "$STATE/$channel"; else set_led "$channel" "$value"; fi
done
if [ "$KEEP_LIT" = 1 ] && [ "$previous_power" != 1 ] && ! siren_running; then show_all; fi
}
case "$1 ${2:-}" in
"power on") set_led "$POWER" 1; [ "$TIMEOUT" = 0 ] || exec "$0" wake ;;
"battery "*) battery ;;
"refresh "*) if awake; then show_all; fi ;;
"power on") set_led "$POWER" 1; [ "$TIMEOUT" = 0 ] || { exec 9>&-; exec "$0" wake; } ;;
"power off") set_led "$POWER" 0 ;;
"data on") set_led "$NODATA" 0; [ "$DATA5G" = "$DATA" ] || set_led "$DATA5G" 0; set_led "$DATA" 1 ;;
"data 5g") set_led "$NODATA" 0; [ "$DATA5G" = "$DATA" ] || set_led "$DATA" 0; set_led "$DATA5G" 1 ;;
@@ -106,6 +213,7 @@ case "$1 ${2:-}" in
[ "$TIMEOUT" = 0 ] && exit 0
mkdir -p "$STATE" 2>/dev/null
echo $(( $(uptime_s) + TIMEOUT )) > "$STATE/.awake-until"
battery
show_all ;;
"sleep "*)
[ "$TIMEOUT" = 0 ] && exit 0
@@ -116,7 +224,7 @@ case "$1 ${2:-}" in
"alarm on")
siren_running && exit 0
mkdir -p "${SIREN_PID%/*}" 2>/dev/null
"$0" siren </dev/null >/dev/null 2>&1 &
"$0" siren 9>&- </dev/null >/dev/null 2>&1 &
echo $! > "$SIREN_PID" ;;
"alarm off")
siren_running || { rm -f "$SIREN_PID"; exit 0; }
+27 -7
View File
@@ -1,13 +1,13 @@
#!/bin/sh
# The USB-C port's role (U30 Air; Ubuntu and OpenWrt, mainline kernels):
# mu300-usb show it
# mu300-usb host host: flash drives, keyboards, modems through an OTG adapter, with 5 V from the charger's
# boost. The USB network to a computer is gone until "device" (it is the same port).
# mu300-usb device back to the USB network / serial console to a computer (the default at every boot)
# mu300-usb boot at boot (mu300-fixups, OpenWrt's mu300-hw): boost off. The charger runs on the battery,
# so its registers outlive a reboot, and a boost left on would meet a computer's 5 V.
# The role is explicit; the charger driver manages charge current and disables
# its watchdog. Never re-enable that watchdog while the driver owns the chip.
# mu300-usb host request data host (USB network to a computer disappears).
# mu300-usb device request data device for the computer's USB network.
# mu300-usb boot native PD: leave role/power negotiation to TCPM.
# old kernels: clear stale charger boost before USB attach.
# Native Type-C/PD controls power separately: host can keep charging via a dock.
# The legacy path manages boost explicitly, with external-VBUS protection.
# Never enable the charger watchdog while the kernel driver owns the chip.
# Battery-less F50/V50 boards never enter this helper's charger register path.
export PATH="$PATH:/opt/mu300/bin:/usr/sbin:/sbin"
R=${MU300_SYSROOT:-} # (for tests/: a fake /sys)
@@ -53,6 +53,26 @@ setbits() { # setbits REG MASK VALUE
i2c set "$BUS" $ADDR "$1" $(( (v & ~$2) | $3 )) || die "cannot write the charger"
}
# A native PD controller owns the boost and negotiates data-role changes.
# Do not force I2C bits behind it: USB host may legitimately remain a sink.
if [ "$(mu300-device)" = u30air ]; then
for native_port in "$R"/sys/class/typec/port*; do
[ -w "$native_port/data_role" ] || continue
case ${1:-status} in
boot) exit 0 ;;
host|device)
[ "$(id -u)" = 0 ] || die "run as root"
echo "$1" > "$native_port/data_role" || die "the Type-C partner refused the data-role swap"
echo "USB data role requested: $1 (power role is negotiated separately)"
exit 0 ;;
status)
printf 'data role: '; cat "$native_port/data_role"
printf 'power role: '; cat "$native_port/power_role"
exit 0 ;;
esac
done
fi
if [ "${1:-}" = boot ]; then
# quietly, on whatever kernel: the 5.4 one has its own charger driver and no I2C device node for this
[ "$(mu300-device)" = u30air ] && BUS=$(bus) || exit 0
+33
View File
@@ -0,0 +1,33 @@
#!/bin/sh
# Independent U30 Air network, Wi-Fi and battery lamps. No AT or polling.
export PATH="$PATH:/opt/mu300/bin:/usr/sbin:/sbin"
RUN=${MU300_LED_RUN_DIR:-${MU300_SYSROOT:-}/run}
LED=${MU300_BIN:-/opt/mu300/bin}/mu300-led
mkdir -p "$RUN"
network() {
case "$1" in
online-5g) "$LED" data 5g ;;
online-4g) "$LED" data on ;;
offline) "$LED" data error ;;
*) "$LED" data off ;;
esac
}
case "${1:-}" in
current) cat "$RUN/led-status.state" 2>/dev/null || echo boot ;;
wifi-on|wifi-off)
[ "$1" = wifi-on ] && state=on || state=off
echo "$state" > "$RUN/led-status.wifi"
"$LED" wifi "$state" ;;
battery) "$LED" battery ;;
refresh)
network "$(cat "$RUN/led-status.state" 2>/dev/null)"
"$LED" wifi "$(cat "$RUN/led-status.wifi" 2>/dev/null || echo off)"
"$LED" battery
"$LED" refresh ;;
thermal) "$LED" alarm on ;;
boot|modem|registering|online-4g|online-5g|offline)
echo "$1" > "$RUN/led-status.state"
network "$1"
"$LED" battery ;;
*) exit 1 ;;
esac
+5 -5
View File
@@ -30,7 +30,7 @@ class Device(ShellTest):
(r / 'run' / 'mu300' / 'device').unlink(missing_ok=True)
def test_lan_ip(self):
for device, want in (('f50', '192.168.77.1'), ('v50', '192.168.77.1'), ('u30air', '192.168.78.1'), ('', '192.168.77.1')):
for device, want in (('f50', '192.168.77.1'), ('v50', '192.168.77.1'), ('u30air', '192.168.77.1'), ('', '192.168.77.1')):
r = self.root(device)
for shell in self.each_shell():
out = self.script(shell, BIN / 'mu300-lan-ip', MU300_SYSROOT=r, MU300_BIN=BIN).stdout.strip()
@@ -141,8 +141,8 @@ class Led(ShellTest):
for shell in self.each_shell():
self.reset()
self.led(shell, 'u30air', 'power', 'on')
for iw, lit, dark in (('channel 36 (5180 MHz), width: 80 MHz', 'zte-ldo2', 'zte-ldo1'),
('channel 6 (2437 MHz), width: 20 MHz', 'zte-ldo1', 'zte-ldo2')):
for iw, lit, dark in (('channel 36 (5180 MHz), width: 80 MHz', 'zte-ldo1', 'zte-ldo2'),
('channel 6 (2437 MHz), width: 20 MHz', 'zte-ldo2', 'zte-ldo1')):
(self.tmp / 'iw.out').write_text(f'Interface wlan0\n\ttype AP\n\t{iw}\n')
self.led(shell, 'u30air', 'wifi', 'on')
s = self.state()
@@ -152,7 +152,7 @@ class Led(ShellTest):
# the hotspot just started and has no channel yet: its setting decides
(self.tmp / 'iw.out').write_text('Interface wlan0\n\ttype AP\n')
conf = self.tmp / 'hotspot.conf'
for band, lit in (('2.4', 'zte-ldo1'), ('5', 'zte-ldo2')):
for band, lit in (('2.4', 'zte-ldo2'), ('5', 'zte-ldo1')):
conf.write_text(f'SSID=x\nPSK=12345678\nBAND={band}\n')
(self.root / 'run/mu300/device').write_text('u30air\n')
self.script(shell, BIN / 'mu300-led', 'wifi', 'on', MU300_SYSROOT=self.root, MU300_BIN=BIN,
@@ -247,7 +247,7 @@ class Led(ShellTest):
self.led(shell, 'u30air', 'data', '5g')
(self.tmp / 'iw.out').write_text('Interface wlan0\n\ttype AP\n\tchannel 36 (5180 MHz)\n')
self.led(shell, 'u30air', 'wifi', 'on')
self.assertEqual([(vendor / f'vddcama{i}_status').read_text().strip() for i in range(3)], ['1', '0', '1'])
self.assertEqual([(vendor / f'vddcama{i}_status').read_text().strip() for i in range(3)], ['1', '1', '0'])
self.led(shell, 'u30air', 'sleep')
self.assertEqual([(vendor / f'vddcama{i}_status').read_text().strip() for i in range(3)], ['0', '0', '0'])
shutil.rmtree(self.root / 'sys/devices')
+54
View File
@@ -0,0 +1,54 @@
"""Compile the actual shutdown callback against a live-counter/retention model."""
from pathlib import Path
import re
import shutil
import subprocess
import tempfile
import unittest
ROOT=Path(__file__).resolve().parents[1]
PATCH=ROOT/'upstream/patches/0017-power-sc27xx-retain-live-soc-before-reset.patch'
@unittest.skipUnless(shutil.which('cc'),'requires C compiler')
class ShutdownCapacity(unittest.TestCase):
def test_live_soc_is_saved_and_errors_do_not_write_stale_state(self):
added='\n'.join(line[1:] for line in PATCH.read_text().splitlines() if line.startswith('+') and not line.startswith('+++'))
start=added.index('static void sc27xx_fgu_shutdown(');pos=added.index('{',start);depth=1;end=pos+1
while depth:
depth+=(added[end]=='{')-(added[end]=='}');end+=1
function=added[start:end]
before=r"""
#include <assert.h>
#include <stdbool.h>
#include <stdio.h>
static int ump9620_info,other;
struct sc27xx_fgu_data { const void *var; bool bat_present; int lock; void *dev; };
struct platform_device { struct sc27xx_fgu_data *data; };
#define SC27XX_FGU_NORMAIL_POWERTON 5
static int held,read_error,save_error,mode_error,reads,saves,modes,warnings,fresh,saved;
static struct sc27xx_fgu_data *platform_get_drvdata(struct platform_device *p){return p->data;}
static void mutex_lock(int *p){(void)p;assert(!held);held=1;}
static void mutex_unlock(int *p){(void)p;assert(held);held=0;}
static int sc27xx_fgu_get_capacity(struct sc27xx_fgu_data *d,int *v){(void)d;assert(held);reads++;*v=fresh;return read_error;}
static int sc27xx_fgu_save_last_cap(struct sc27xx_fgu_data *d,int v){(void)d;assert(held);saves++;if(!save_error)saved=v;return save_error;}
static int sc27xx_fgu_save_boot_mode(struct sc27xx_fgu_data *d,int v){(void)d;assert(held&&v==5);modes++;return mode_error;}
#define dev_warn(...) do {warnings++;} while(0)
"""
after=r"""
static void reset(void){held=reads=saves=modes=warnings=read_error=save_error=mode_error=0;fresh=76;saved=18;}
int main(void){
struct sc27xx_fgu_data d={.var=&ump9620_info,.bat_present=true};struct platform_device p={.data=&d};
reset();sc27xx_fgu_shutdown(&p);assert(saved==76&&reads==1&&saves==1&&modes==1&&!held&&!warnings);
reset();read_error=-5;sc27xx_fgu_shutdown(&p);assert(saved==18&&reads==1&&!saves&&!modes&&!held&&warnings==1);
reset();save_error=-5;sc27xx_fgu_shutdown(&p);assert(saved==18&&saves==1&&!modes&&!held&&warnings==1);
reset();mode_error=-5;sc27xx_fgu_shutdown(&p);assert(saved==76&&modes==1&&!held&&warnings==1);
reset();d.bat_present=false;sc27xx_fgu_shutdown(&p);assert(!reads&&!saves&&!modes&&!held);
reset();d.bat_present=true;d.var=&other;sc27xx_fgu_shutdown(&p);assert(!reads&&!saves&&!modes&&!held);
puts("PASS: live SOC, retention errors and battery/PMIC gating");return 0;
}
"""
with tempfile.TemporaryDirectory() as tmp:
source=Path(tmp)/'test.c';binary=Path(tmp)/'test';source.write_text(before+function+after)
subprocess.run(['cc','-Wall','-Wextra','-Werror',str(source),'-o',str(binary)],check=True,capture_output=True)
result=subprocess.run([str(binary)],capture_output=True,text=True)
self.assertEqual(result.returncode,0,result.stdout+result.stderr)
+7
View File
@@ -168,6 +168,13 @@ for (const [locale, title, signal, wifi] of [
const adapted = page.render([{ 'v50:net1:white': { max_brightness: 80, triggers: [] } }, []]);
if (!adapted.sections[0].options.some(o => o.key === 'signal2') ||
!adapted.sections[0].options.some(o => o.key === 'wifi')) throw Error('V50 physical lamps missing');
const u30 = page.render([{ 'zte-ldo0': {max_brightness:1,triggers:[]}, 'zte-ldo1': {max_brightness:1,triggers:[]}, 'zte-ldo2': {max_brightness:1,triggers:[]}, net_blue: {max_brightness:1,triggers:[]} }, []]);
const opts = u30.sections[0].options;
if (opts.some(o => ['signal_brightness','wifi_brightness','signal2'].includes(o.key))) throw Error('U30 binary lamps must not offer fake brightness or a second SIM lamp');
const battery = opts.find(o => o.key === 'battery_brightness');
if (!battery || battery.datatype !== 'range(0,255)' || !opts.some(o => o.key === 'battery')) throw Error('U30 battery controls');
if (!opts.some(o => o.key === 'timeout' && o.default === '60')) throw Error('U30 idle timeout');
}
'''
result = subprocess.run(['node', '-', str(UI)], input=harness, capture_output=True,
+138
View File
@@ -0,0 +1,138 @@
"""U30 status events own three independent physical lamp groups."""
import os
import subprocess
from pathlib import Path
from helpers import BIN,ShellTest
class U30Leds(ShellTest):
def setUp(self):
super().setUp()
self.root=self.tmp/'root';self.lamps=self.root/'sys/class/leds'
for name in ['net_blue','zte-ldo0','zte-ldo1','zte-ldo2','keyboard-backlight','sc27xx:red','sc27xx:green','sc27xx:blue']:
p=self.lamps/name;p.mkdir(parents=True)
(p/'brightness').write_text('0\n');(p/'max_brightness').write_text('255\n' if name.startswith('sc27xx:') else '1\n');(p/'trigger').write_text('[none] timer\n')
(self.root/'run/mu300').mkdir(parents=True);(self.root/'run/mu300/device').write_text('u30air\n')
(self.root/'proc').mkdir();(self.root/'proc/uptime').write_text('100.00 999.00\n')
self.battery=self.root/'sys/class/power_supply/sc27xx-fgu';self.battery.mkdir(parents=True)
(self.battery/'capacity').write_text('65\n');(self.battery/'status').write_text('Charging\n')
self.stub('uci',"""case "$3" in
system.mu300_leds.timeout) echo "${TEST_TIMEOUT:-0}" ;;
system.mu300_leds.signal) echo "${TEST_SIGNAL:-1}" ;;
system.mu300_leds.wifi) echo "${TEST_WIFI:-1}" ;;
system.mu300_leds.battery) echo "${TEST_BATTERY:-1}" ;;
system.mu300_leds.battery_brightness) echo "${TEST_BRIGHTNESS:-255}" ;;
esac""")
self.stub('iw','echo "channel 36 (5180 MHz)"')
self.extra=dict(MU300_SYSROOT=self.root,MU300_BIN=BIN)
def apply(self,shell,*args,**extra):
r=self.script(shell,BIN/'u30air-led-status',*args,**dict(self.extra,**extra))
self.assertEqual(r.returncode,0,r.stderr)
return r.stdout.strip()
def value(self,name):return (self.lamps/name/'brightness').read_text().strip()
def test_events_do_not_confuse_network_with_battery_and_wifi(self):
for shell in self.each_shell():
self.apply(shell,'online-5g');self.apply(shell,'wifi-on')
self.assertEqual([self.value(n) for n in ['net_blue','zte-ldo0','zte-ldo1','zte-ldo2']],['0','1','1','0'])
self.assertEqual(self.value('sc27xx:blue'),'255');self.assertEqual(self.value('sc27xx:green'),'0')
self.apply(shell,'online-4g')
self.assertEqual(self.value('net_blue'),'1');self.assertEqual(self.value('zte-ldo0'),'0')
self.assertEqual(self.value('zte-ldo1'),'1');self.assertEqual(self.value('sc27xx:blue'),'255')
self.apply(shell,'offline');self.assertEqual(self.value('keyboard-backlight'),'1')
self.apply(shell,'wifi-off');self.assertEqual(self.value('zte-ldo1'),'0')
def test_controls_do_not_erase_desired_state(self):
for shell in self.each_shell():
self.apply(shell,'online-5g');self.apply(shell,'wifi-on')
self.apply(shell,'refresh',TEST_SIGNAL='0',TEST_WIFI='0',TEST_BATTERY='0')
self.assertTrue(all(self.value(n)=='0' for n in ['zte-ldo0','zte-ldo1','sc27xx:blue']))
self.apply(shell,'refresh',TEST_BRIGHTNESS='40')
self.assertEqual(self.value('zte-ldo0'),'1');self.assertEqual(self.value('zte-ldo1'),'1');self.assertEqual(self.value('sc27xx:blue'),'40')
def test_battery_states_and_timeout(self):
for shell in self.each_shell():
(self.battery/'status').write_text('Discharging\n');(self.battery/'capacity').write_text('10\n')
self.apply(shell,'battery');self.assertEqual(self.value('sc27xx:red'),'255')
(self.battery/'status').write_text('Full\n');self.apply(shell,'battery')
self.assertEqual(self.value('sc27xx:green'),'255');self.assertEqual(self.value('sc27xx:red'),'0')
(self.battery/'status').write_text('Discharging\n')
self.apply(shell,'online-5g',TEST_TIMEOUT='60')
self.assertEqual(self.value('zte-ldo0'),'0')
r=self.script(shell,BIN/'mu300-led','wake',**dict(self.extra,TEST_TIMEOUT='60'));self.assertEqual(r.returncode,0,r.stderr)
self.assertEqual(self.value('zte-ldo0'),'1')
self.apply(shell,'current',TEST_TIMEOUT='60');self.assertEqual(self.value('zte-ldo0'),'1')
self.script(shell,BIN/'mu300-led','sleep',**dict(self.extra,TEST_TIMEOUT='60'));self.assertEqual(self.value('zte-ldo0'),'0')
def test_power_holds_lamps_and_unplug_restarts_timeout(self):
for shell in self.each_shell():
online=self.root/'sys/class/power_supply/bq256xx-charger/online';online.parent.mkdir(exist_ok=True);online.write_text('1\n')
(self.battery/'status').write_text('Charging\n')
self.apply(shell,'online-5g',TEST_TIMEOUT='60');self.apply(shell,'wifi-on',TEST_TIMEOUT='60')
(self.root/'proc/uptime').write_text('10000.00 0.00\n')
self.script(shell,BIN/'mu300-led','sleep','--if-due',**dict(self.extra,TEST_TIMEOUT='60'))
self.assertEqual(self.value('zte-ldo0'),'1');self.assertEqual(self.value('zte-ldo1'),'1')
online.write_text('0\n');(self.battery/'status').write_text('Discharging\n')
self.apply(shell,'battery',TEST_TIMEOUT='60')
self.assertEqual((self.root/'run/mu300/led/.awake-until').read_text().strip(),'10060')
(self.root/'proc/uptime').write_text('10061.00 0.00\n')
self.script(shell,BIN/'mu300-led','sleep','--if-due',**dict(self.extra,TEST_TIMEOUT='60'))
self.assertEqual(self.value('zte-ldo0'),'0');self.assertEqual(self.value('zte-ldo1'),'0')
self.assertTrue(all(self.value(n)=='0' for n in ['sc27xx:red','sc27xx:green','sc27xx:blue']))
online.write_text('1\n');(self.battery/'status').write_text('Charging\n')
self.apply(shell,'battery',TEST_TIMEOUT='60')
self.assertEqual(self.value('zte-ldo0'),'1');self.assertEqual(self.value('zte-ldo1'),'1')
def test_charging_uses_hardware_rise_hold_fall_rest(self):
for shell in self.each_shell():
blue=self.lamps/'sc27xx:blue'
(blue/'trigger').write_text('[none] timer pattern\n');(blue/'hw_pattern').write_text('');(blue/'repeat').write_text('0\n')
self.apply(shell,'battery',TEST_BRIGHTNESS='40')
self.assertEqual((blue/'trigger').read_text().strip(),'pattern')
self.assertEqual((blue/'hw_pattern').read_text().strip(),'0 625 40 750 0 625 0 250')
self.assertEqual((blue/'repeat').read_text().strip(),'-1')
self.assertFalse((blue/'delay_on').exists())
(self.battery/'status').write_text('Full\n');self.apply(shell,'battery')
self.assertEqual((blue/'trigger').read_text().strip(),'none');self.assertEqual(self.value('sc27xx:green'),'255')
(self.battery/'status').write_text('Charging\n')
def test_unplug_ignores_stale_fgu_charging_and_stays_dark_after_events(self):
for shell in self.each_shell():
online=self.root/'sys/class/power_supply/bq256xx-charger/online'
online.parent.mkdir(exist_ok=True);online.write_text('1\n')
(self.root/'proc/uptime').write_text('100.00 0.00\n')
self.apply(shell,'online-5g',TEST_TIMEOUT='60')
self.apply(shell,'wifi-on',TEST_TIMEOUT='60')
online.write_text('0\n') # FGU deliberately still reports Charging.
self.apply(shell,'battery',TEST_TIMEOUT='60')
self.assertEqual(self.value('sc27xx:blue'),'0')
self.assertEqual(self.value('sc27xx:green'),'255')
self.assertFalse((self.root/'run/mu300/led/.battery-breathe').exists())
(self.root/'proc/uptime').write_text('161.00 0.00\n')
self.script(shell,BIN/'mu300-led','sleep','--if-due',**dict(self.extra,TEST_TIMEOUT='60'))
self.apply(shell,'refresh',TEST_TIMEOUT='60')
self.assertTrue(all(self.value(n)=='0' for n in ['zte-ldo0','zte-ldo1','sc27xx:red','sc27xx:green','sc27xx:blue']))
def test_queued_power_event_reads_online_after_timeout_lock(self):
import fcntl,time
for shell in self.each_shell():
online=self.root/'sys/class/power_supply/bq256xx-charger/online'
online.parent.mkdir(exist_ok=True);online.write_text('1\n')
self.apply(shell,'online-5g',TEST_TIMEOUT='60')
state=self.root/'run/mu300/led'
with (state/'.lock').open('w') as lock:
fcntl.flock(lock,fcntl.LOCK_EX)
proc=subprocess.Popen(shell+[str(BIN/'mu300-led'),'battery'],env=self.env(**dict(self.extra,TEST_TIMEOUT='60')),stdout=subprocess.PIPE,stderr=subprocess.PIPE,text=True)
try:
time.sleep(.1)
self.assertIsNone(proc.poll(),'battery event bypassed shared LED lock')
online.write_text('0\n')
(state/'.external-power').write_text('0\n')
(state/'.awake-until').unlink(missing_ok=True)
fcntl.flock(lock,fcntl.LOCK_UN)
out,err=proc.communicate(timeout=10)
self.assertEqual(proc.returncode,0,err)
finally:
if proc.poll() is None:proc.kill();proc.communicate()
self.assertTrue(all(self.value(n)=='0' for n in ['sc27xx:red','sc27xx:green','sc27xx:blue']))
+142
View File
@@ -0,0 +1,142 @@
"""Execute the actual callbacks against independent USB/power-role models."""
from pathlib import Path
import re
import shutil
import subprocess
import tempfile
import unittest
from helpers import ShellTest, BIN
ROOT=Path(__file__).resolve().parents[1]
DRIVER=ROOT/'upstream/port/drivers/usb/typec/tcpm/sc27xx-ump9620.c'
def function(text,name):
start=re.search(r'^static [^\n]*\b'+name+r'\(',text,re.M).start()
end=text.index('{',start)+1;depth=1
while depth:
depth+=(text[end]=='{')-(text[end]=='}');end+=1
return text[start:end]+'\n'
@unittest.skipUnless(shutil.which('cc'),'requires C compiler')
class PDRoles(unittest.TestCase):
def test_power_sink_can_be_usb_host_without_enabling_boost(self):
text=DRIVER.read_text()
before=r'''
#include <assert.h>
#include <stdbool.h>
#include <errno.h>
enum usb_role {USB_ROLE_NONE,USB_ROLE_HOST,USB_ROLE_DEVICE};
enum typec_role {TYPEC_SINK,TYPEC_SOURCE};
enum typec_data_role {TYPEC_DEVICE,TYPEC_HOST};
enum tcpm_transmit_status {TCPC_TX_SUCCESS,TCPC_TX_FAILED};
struct tcpc_dev {void *pd;};
struct sc27xx_pd {void *role_sw,*dev,*port;bool attached,tx_pending,pd_capable;enum typec_role power_role;};
#define SC27XX_PD_CFG0 16
#define SC27XX_PD_SRC_SINK_MODE 512
#define dev_info(...) ((void)0)
static int writes,usb_calls,power_value,usb_value,write_error,usb_error,tx_completions;
static struct sc27xx_pd *to_pd(struct tcpc_dev *dev){return dev->pd;}
static int pd_update(struct sc27xx_pd *pd,int reg,int mask,int val){(void)pd;assert(reg==16&&mask==512);writes++;power_value=val;return write_error;}
static int usb_role_switch_set_role(void *sw,enum usb_role role){(void)sw;usb_calls++;usb_value=role;return usb_error;}
static void tcpm_pd_transmit_complete(void *port,enum tcpm_transmit_status status){(void)port;(void)status;tx_completions++;}
'''
after=r'''
int main(void){
struct sc27xx_pd pd={0};struct tcpc_dev tcpc={.pd=&pd};
assert(!sc27xx_set_roles(&tcpc,true,TYPEC_SINK,TYPEC_HOST));
assert(usb_value==USB_ROLE_HOST&&!power_value&&pd.attached&&pd.power_role==TYPEC_SINK);
assert(!sc27xx_set_roles(&tcpc,true,TYPEC_SOURCE,TYPEC_HOST));
assert(usb_value==USB_ROLE_HOST&&power_value==512&&pd.power_role==TYPEC_SOURCE);
assert(!sc27xx_set_roles(&tcpc,true,TYPEC_SINK,TYPEC_DEVICE));
assert(usb_value==USB_ROLE_DEVICE&&!power_value);
assert(!sc27xx_set_roles(&tcpc,false,TYPEC_SINK,TYPEC_HOST));
assert(usb_value==USB_ROLE_DEVICE&&!pd.attached);
write_error=-EIO;int calls=usb_calls;
assert(sc27xx_set_roles(&tcpc,true,TYPEC_SOURCE,TYPEC_HOST)==-EIO&&usb_calls==calls&&!pd.attached);
write_error=0;usb_error=-EIO;
assert(sc27xx_set_roles(&tcpc,true,TYPEC_SOURCE,TYPEC_HOST)==-EIO&&!pd.attached);
pd.tx_pending=true;sc27xx_complete_tx(&pd,TCPC_TX_SUCCESS);sc27xx_complete_tx(&pd,TCPC_TX_SUCCESS);
assert(tx_completions==1&&!pd.tx_pending);
return 0;
}
'''
with tempfile.TemporaryDirectory() as d:
source=Path(d)/'roles.c';binary=Path(d)/'roles'
source.write_text(before+function(text,'sc27xx_set_roles')+function(text,'sc27xx_complete_tx')+after)
result=subprocess.run(['cc','-Wall','-Wextra','-Werror',str(source),'-o',str(binary)],capture_output=True,text=True)
self.assertEqual(result.returncode,0,result.stderr)
subprocess.run([str(binary)],check=True)
def test_receive_frame_trailer_is_not_a_second_pd_message(self):
text=DRIVER.read_text()
regs=(DRIVER.parent/'sc27xx-ump9620-regs.h').read_text().split('enum sc27xx_state')[0]
before=r"""
#include <assert.h>
#include <stdbool.h>
#include <stdint.h>
#include <errno.h>
typedef uint32_t u32;typedef uint16_t u16;typedef int irqreturn_t;
#define BIT(n) (1U<<(n))
#define GENMASK(h,l) ((~0U<<(l))&(~0U>>(31-(h))))
#define cpu_to_le16(v) (v)
#define cpu_to_le32(v) (v)
#define pd_header_cnt_le(v) (((v)>>12)&7)
#define pd_header_type_le(v) ((v)&31)
#define PD_CTRL_GOOD_CRC 1
#define TCPC_TX_SOP 0
#define IRQ_HANDLED 1
#define dev_warn_ratelimited(...) ((void)0)
"""
model=r"""
enum tcpm_transmit_status {TCPC_TX_SUCCESS,TCPC_TX_FAILED};
struct pd_message {u16 header;u32 payload[7];};
struct sc27xx_pd {void *regmap,*port,*dev;u32 base,typec_base;int lock;bool tx_pending,pd_capable;};
static u32 fifo[8],flags;static int at,held,flushes,messages,completions,hard_resets,read_error;static struct pd_message received;
static void mutex_lock(int *p){(void)p;assert(!held);held=1;}
static void mutex_unlock(int *p){(void)p;assert(held);held=0;}
static int regmap_read(void *map,u32 reg,u32 *value){(void)map;assert(held);if(reg==SC27XX_INT_FLG){*value=flags;return 0;}assert(reg==SC27XX_PD_RX_BUF);if(read_error)return -EIO;assert(at<8);*value=fifo[at++];return 0;}
static int regmap_write(void *map,u32 reg,u32 value){(void)map;(void)value;assert(held&&reg==SC27XX_INT_CLR);return 0;}
static int regmap_write_bits(void *map,u32 reg,u32 mask,u32 value){(void)map;assert(held&&reg==SC27XX_PD_CTRL);if(mask&SC27XX_PD_RX_FLASH){assert(value&SC27XX_PD_RX_FLASH);flushes++;}return 0;}
static int cc_update(struct sc27xx_pd *pd,u32 reg,u32 mask,u32 value){(void)pd;(void)reg;(void)mask;(void)value;return 0;}
static void tcpm_pd_receive(void *port,const struct pd_message *msg,int sop){(void)port;assert(sop==TCPC_TX_SOP);received=*msg;messages++;}
static void tcpm_pd_transmit_complete(void *port,enum tcpm_transmit_status status){(void)port;(void)status;completions++;}
static void tcpm_pd_hard_reset(void *port){(void)port;hard_resets++;}
"""
after=r"""
int main(void){
struct sc27xx_pd pd={0};
flags=SC27XX_PD_PKG_RV_FLAG;fifo[0]=0x1161;fifo[1]=0x90c8;fifo[2]=0x2601;fifo[3]=0xc0d8;fifo[4]=0xb104;
sc27xx_pd_irq(1,&pd);assert(messages==1&&at==3&&flushes==1&&received.header==0x1161&&received.payload[0]==0x260190c8&&!held);
at=0;fifo[0]=PD_CTRL_GOOD_CRC;flags|=SC27XX_PD_TX_OK_FLAG;pd.tx_pending=true;
sc27xx_pd_irq(1,&pd);assert(messages==1&&completions==1&&!pd.tx_pending&&at==1&&flushes==2&&!held);
read_error=1;flags=SC27XX_PD_PKG_RV_FLAG;sc27xx_pd_irq(1,&pd);assert(messages==1&&completions==1&&flushes==3&&!held);
flags=SC27XX_PD_HARD_RST_FLAG;sc27xx_pd_irq(1,&pd);assert(hard_resets==1&&!held);
return 0;
}
"""
with tempfile.TemporaryDirectory() as d:
source=Path(d)/'receive.c';binary=Path(d)/'receive'
source.write_text(before+regs+model+function(text,'sc27xx_complete_tx')+function(text,'sc27xx_receive')+function(text,'sc27xx_pd_irq')+after)
result=subprocess.run(['cc','-Wall','-Wextra','-Werror','-Wno-unused-parameter',str(source),'-o',str(binary)],capture_output=True,text=True)
self.assertEqual(result.returncode,0,result.stderr)
subprocess.run([str(binary)],check=True)
class NativeRoleHelper(ShellTest):
def test_pd_data_role_requests_never_force_charger_registers(self):
root=self.tmp/'root'
port=root/'sys/class/typec/port0'
port.mkdir(parents=True)
(port/'data_role').write_text('device\n')
(port/'power_role').write_text('sink\n')
self.stub('mu300-device','echo u30air')
self.stub('id','echo 0')
self.stub('i2cget','echo unexpected >> "$STUBLOG/i2c"; exit 1')
self.stub('i2cset','echo unexpected >> "$STUBLOG/i2c"; exit 1')
for shell in self.each_shell():
for mode in ('boot','host','device','status'):
result=self.script(shell,BIN/'mu300-usb',mode,MU300_SYSROOT=root)
self.assertEqual(result.returncode,0,result.stderr)
self.assertEqual((port/'power_role').read_text(),'sink\n')
self.assertFalse((self.tmp/'i2c').exists())
+1 -1
View File
@@ -34,7 +34,7 @@ class Vpn(ShellTest):
('LAN_CIDRS=192.168.77.0/24\n', 'u30air', '192.168.78.1/24', '192.168.77.0/24,192.168.78.0/24'),
('LAN_CIDRS=192.168.78.0/24\n', 'u30air', '192.168.78.1/24', '192.168.78.0/24'),
# br-lan not up yet: the device's default address
('', 'u30air', None, '192.168.78.0/24'),
('', 'u30air', None, '192.168.77.0/24'),
('', 'f50', None, '192.168.77.0/24'),
# an address set in lan.conf / UCI, as br-lan has it
('LAN_CIDRS=10.0.0.0/8\n', 'f50', '192.168.5.1/24', '10.0.0.0/8,192.168.5.0/24'),
+6
View File
@@ -30,6 +30,11 @@ mkdir -p "$TOP/work"
# desktop code is not added to the Magisk boot image.
DESKTOP=${MU300_DESKTOP_INSTALLER:-1}
DESKTOP_TOOLS=${MU300_DESKTOP_TOOLS:-$TOP/work/desktop-tools}
# Include the native Mac build when it has been downloaded/built alongside the
# Windows artifact. The assembler checks both against the current source hash.
if [ -z "${OPENWRT_GUI_MACOS_ARTIFACT:-}" ] && [ -f "$TOP/installer/artifacts/macos-arm64/build.json" ]; then
export OPENWRT_GUI_MACOS_ARTIFACT="$TOP/installer/artifacts/macos-arm64"
fi
if [ "$DESKTOP" = 1 ]; then
[ -s "$DESKTOP_TOOLS/lib/ld-musl-aarch64.so.1" ] || {
echo "desktop maintenance tools missing: $DESKTOP_TOOLS (set MU300_DESKTOP_TOOLS or MU300_DESKTOP_INSTALLER=0)" >&2; exit 1;
@@ -91,6 +96,7 @@ MU300_GPU=0 MU300_INPUTS="$IN" MU300_MAINLINE_OUT="$UO" MU300_LUCI_PLUGIN_SRC="$
for f in ./lib/netifd/proto/mu300cell.sh ./lib/netifd/proto/mu300cell-v6.sh \
./sbin/block ./lib/libblkid-tiny.so ./etc/init.d/fstab ./etc/mu300/block-mount.build-id \
./opt/mu300/bin/mu300-keys ./opt/mu300/bin/mu300-bt-init ./opt/mu300/bin/mu300-atd ./opt/mu300/bin/mu300-at ./opt/mu300/bin/mobile-data \
./opt/mu300/bin/u30air-led-status ./etc/hotplug.d/power_supply/70-mu300-led \
./opt/mu300/bin/mu300-data-sim-u30 ./opt/mu300/bin/mu300-sim-u30 ./opt/mu300/bin/mu300-sim2-start ./opt/mu300/bin/mu300-sim2-warmup ./opt/mu300/lib/sim-config.sh \
./opt/mu300/bin/mu300-user-packages ./etc/init.d/mu300-user-packages ./etc/mu300/image-packages \
./opt/mu300/lib/wifi-channels.sh ./usr/share/ucode/wifi/hostapd.uc \
+1 -1
View File
@@ -1,6 +1,6 @@
#!/usr/bin/env python3
"""scp to the MU300 with password auth (no sshpass). usage: mu300-scp.py LOCAL REMOTE_PATH
env: MU300_HOST (ubuntu@192.168.77.1; a U30 Air is ubuntu@192.168.78.1), MU300_PASS"""
env: MU300_HOST (ubuntu@192.168.77.1; a U30 Air is ubuntu@192.168.77.1), MU300_PASS"""
import os, pty, select, sys
pw = os.environ.get('MU300_PASS', 'ubuntu').encode()
cmd = ['scp', '-O', '-o', 'StrictHostKeyChecking=no', '-o', 'UserKnownHostsFile=/dev/null', '-o', 'LogLevel=ERROR',
+1 -1
View File
@@ -1,6 +1,6 @@
#!/usr/bin/env python3
"""Run a command on the MU300 over SSH with password auth (no sshpass needed).
usage: MU300_PASS=ubuntu mu300-ssh.py 'command' (MU300_HOST: ubuntu@192.168.77.1; a U30 Air is ubuntu@192.168.78.1)"""
usage: MU300_PASS=ubuntu mu300-ssh.py 'command' (MU300_HOST: ubuntu@192.168.77.1; a U30 Air is ubuntu@192.168.77.1)"""
import os, pty, select, sys, time
host = os.environ.get('MU300_HOST', 'ubuntu@192.168.77.1')
pw = os.environ.get('MU300_PASS', 'ubuntu').encode()
+4
View File
@@ -124,6 +124,9 @@ CONFIG_GPIO_SPRD=y
CONFIG_GPIO_EIC_SPRD=y
CONFIG_GPIO_PMIC_EIC_SPRD=y
CONFIG_EXTCON_USB_GPIO=y
CONFIG_TYPEC=y
CONFIG_TYPEC_TCPM=y
CONFIG_TYPEC_SC27XX_UMP9620=y
CONFIG_PINCTRL=y
CONFIG_WATCHDOG=y
CONFIG_WATCHDOG_CORE=y
@@ -323,6 +326,7 @@ CONFIG_CPU_IDLE_GOV_MENU=y
CONFIG_NEW_LEDS=y
CONFIG_LEDS_CLASS=y
CONFIG_LEDS_SC27XX_BLTC=y
CONFIG_LEDS_TRIGGER_PATTERN=y
# the U30 Air's power, network and Wi-Fi LEDs are gpio-leds (the F50 has none)
CONFIG_LEDS_GPIO=y
# ... and its white ones, on PMIC LDOs (upstream/port/drivers/leds/leds-zte-ldo.c)
@@ -0,0 +1,101 @@
power: supply: sc27xx: force retained-register strobes and snapshot live SOC before reset
Dashboard reads are optional; reboot must preserve the latest coulomb count.
Retained SET/CLEAR registers require unconditional writes even when their
readback is unchanged. Limit shutdown sampling to populated UMP9620 batteries.
--- a/drivers/power/supply/sc27xx_fuel_gauge.c
+++ b/drivers/power/supply/sc27xx_fuel_gauge.c
@@ -233,7 +233,7 @@
{
int ret;
- ret = regmap_update_bits(data->regmap,
+ ret = regmap_write_bits(data->regmap,
data->base + SC27XX_FGU_USER_AREA_CLEAR,
SC27XX_FGU_MODE_AREA_MASK,
SC27XX_FGU_MODE_AREA_MASK);
@@ -248,7 +248,7 @@
*/
udelay(200);
- ret = regmap_update_bits(data->regmap,
+ ret = regmap_write_bits(data->regmap,
data->base + SC27XX_FGU_USER_AREA_SET,
SC27XX_FGU_MODE_AREA_MASK,
boot_mode << SC27XX_FGU_MODE_AREA_SHIFT);
@@ -268,7 +268,7 @@
* make the user area data available, otherwise we can not save the user
* area data.
*/
- return regmap_update_bits(data->regmap,
+ return regmap_write_bits(data->regmap,
data->base + SC27XX_FGU_USER_AREA_CLEAR,
SC27XX_FGU_MODE_AREA_MASK, 0);
}
@@ -277,7 +277,7 @@
{
int ret;
- ret = regmap_update_bits(data->regmap,
+ ret = regmap_write_bits(data->regmap,
data->base + SC27XX_FGU_USER_AREA_CLEAR,
SC27XX_FGU_CAP_AREA_MASK,
SC27XX_FGU_CAP_AREA_MASK);
@@ -296,7 +296,7 @@
if (data->var == &ump9620_info)
cap = clamp(cap, 0, 100);
- ret = regmap_update_bits(data->regmap,
+ ret = regmap_write_bits(data->regmap,
data->base + SC27XX_FGU_USER_AREA_SET,
SC27XX_FGU_CAP_AREA_MASK, cap);
if (ret)
@@ -315,7 +315,7 @@
* make the user area data available, otherwise we can not save the user
* area data.
*/
- ret = regmap_update_bits(data->regmap,
+ ret = regmap_write_bits(data->regmap,
data->base + SC27XX_FGU_USER_AREA_CLEAR,
SC27XX_FGU_CAP_AREA_MASK, 0);
if (!ret)
@@ -1551,6 +1551,30 @@
}
#endif
+/* SOC may not have been read since the last dashboard visit. Sample the
+ * live coulomb counter before reset, while the PMIC transport is still up.
+ * The retained SET/CLEAR registers are strobes: equal readback must not skip
+ * a write, hence regmap_write_bits() in the save helpers above.
+ */
+static void sc27xx_fgu_shutdown(struct platform_device *pdev)
+{
+ struct sc27xx_fgu_data *data = platform_get_drvdata(pdev);
+ int cap, ret;
+
+ if (data->var != &ump9620_info || !data->bat_present)
+ return;
+
+ mutex_lock(&data->lock);
+ ret = sc27xx_fgu_get_capacity(data, &cap);
+ if (!ret)
+ ret = sc27xx_fgu_save_last_cap(data, cap);
+ if (!ret)
+ ret = sc27xx_fgu_save_boot_mode(data, SC27XX_FGU_NORMAIL_POWERTON);
+ mutex_unlock(&data->lock);
+ if (ret)
+ dev_warn(data->dev, "failed to retain shutdown capacity: %d\n", ret);
+}
+
static const struct dev_pm_ops sc27xx_fgu_pm_ops = {
SET_SYSTEM_SLEEP_PM_OPS(sc27xx_fgu_suspend, sc27xx_fgu_resume)
};
@@ -1563,6 +1587,7 @@
MODULE_DEVICE_TABLE(of, sc27xx_fgu_of_match);
static struct platform_driver sc27xx_fgu_driver = {
+ .shutdown = sc27xx_fgu_shutdown,
.probe = sc27xx_fgu_probe,
.driver = {
.name = "sc27xx-fgu",
@@ -0,0 +1,159 @@
power: supply: bq256xx: independent PD sink and USB host roles
--- a/drivers/power/supply/bq256xx_charger.c
+++ b/drivers/power/supply/bq256xx_charger.c
@@ -16,6 +16,7 @@
#include <linux/moduleparam.h>
#include <linux/slab.h>
#include <linux/acpi.h>
+#include <linux/regulator/driver.h>
#include <linux/bitfield.h>
#include <linux/devm-helpers.h>
#include <linux/extcon.h>
@@ -275,6 +276,7 @@
*/
bool bq2560x_chg;
bool chg_off;
+ bool pd_active;
bool iindet_noted;
int usb_type;
struct device *pmic;
@@ -943,6 +945,16 @@
int ret = -EINVAL;
switch (prop) {
+ case POWER_SUPPLY_PROP_USB_TYPE:
+ if (!bq->bq2560x_chg || (val->intval != POWER_SUPPLY_USB_TYPE_PD &&
+ val->intval != POWER_SUPPLY_USB_TYPE_UNKNOWN))
+ return -EINVAL;
+ WRITE_ONCE(bq->pd_active, val->intval == POWER_SUPPLY_USB_TYPE_PD);
+ if (!READ_ONCE(bq->pd_active))
+ mod_delayed_work(system_power_efficient_wq, &bq->vbus_work, 0);
+ power_supply_changed(psy);
+ return 0;
+
case POWER_SUPPLY_PROP_INPUT_CURRENT_LIMIT:
ret = bq->chip_info->bq256xx_set_iindpm(bq, val->intval);
if (ret)
@@ -1092,6 +1104,10 @@
break;
case POWER_SUPPLY_PROP_USB_TYPE:
+ if (bq->bq2560x_chg && READ_ONCE(bq->pd_active)) {
+ val->intval = POWER_SUPPLY_USB_TYPE_PD;
+ break;
+ }
/* "ti,bq2560x_chg": the PMIC's charger detection, when it said something (bq2560x_chg_detect) */
if (bq->bq2560x_chg && READ_ONCE(bq->usb_type) != POWER_SUPPLY_USB_TYPE_UNKNOWN &&
state.vbus_stat != BQ256XX_VBUS_STAT_NO_INPUT &&
@@ -1291,7 +1307,7 @@
BIT(POWER_SUPPLY_USB_TYPE_CDP) |
BIT(POWER_SUPPLY_USB_TYPE_DCP) |
BIT(POWER_SUPPLY_USB_TYPE_ACA) |
- BIT(POWER_SUPPLY_USB_TYPE_UNKNOWN),
+ BIT(POWER_SUPPLY_USB_TYPE_UNKNOWN) | BIT(POWER_SUPPLY_USB_TYPE_PD),
.properties = bq256xx_power_supply_props,
.num_properties = ARRAY_SIZE(bq256xx_power_supply_props),
.get_property = bq256xx_get_charger_property,
@@ -1821,15 +1837,19 @@
const char *src = "PMIC";
mutex_lock(&bq->lock);
- ret = regmap_update_bits(bq->regmap, BQ256XX_CHARGER_CONTROL_0, BQ256XX_CHG_CONFIG_MASK,
- off ? 0 : BQ256XX_CHG_CONFIG_MASK);
- if (!ret)
- ret = regmap_read(bq->regmap, BQ256XX_CHARGER_CONTROL_0, &ctrl0);
+ ret = regmap_read(bq->regmap, BQ256XX_CHARGER_CONTROL_0, &ctrl0);
+ if (!ret && !(ctrl0 & BQ256XX_OTG_CONFIG))
+ ret = regmap_update_bits(bq->regmap, BQ256XX_CHARGER_CONTROL_0,
+ BQ256XX_CHG_CONFIG_MASK, off ? 0 : BQ256XX_CHG_CONFIG_MASK);
if (!ret)
ret = regmap_read(bq->regmap, BQ256XX_CHARGER_STATUS_0, &stat);
/* nothing on VBUS, or the chip's own boost drives it (mu300-usb host) */
if (ret || (ctrl0 & BQ256XX_OTG_CONFIG) || !(stat & BQ256XX_PG_STAT_MASK) ||
(stat & BQ256XX_VBUS_STAT_MASK) == BQ256XX_VBUS_STAT_USB_OTG)
+ goto out;
+
+ /* A negotiated PD contract owns IIN; BC1.2/Rp must not replace it. */
+ if (READ_ONCE(bq->pd_active))
goto out;
type = bq2560x_chg_pmic_type(bq);
@@ -2097,6 +2117,67 @@
}
return 0;
+}
+
+
+/* The DT's otg-vbus regulator. Data-host does not imply power-source. */
+static int bq2560x_otg_enable(struct regulator_dev *rdev)
+{
+ struct bq256xx_device *bq = rdev_get_drvdata(rdev);
+ int ret;
+
+ mutex_lock(&bq->lock);
+ ret = regmap_update_bits(bq->regmap, BQ256XX_CHARGER_CONTROL_0,
+ BQ256XX_OTG_CONFIG | BQ256XX_CHG_CONFIG_MASK, BQ256XX_OTG_CONFIG);
+ mutex_unlock(&bq->lock);
+ return ret;
+}
+
+static int bq2560x_otg_disable(struct regulator_dev *rdev)
+{
+ struct bq256xx_device *bq = rdev_get_drvdata(rdev);
+ int ret;
+
+ mutex_lock(&bq->lock);
+ ret = regmap_update_bits(bq->regmap, BQ256XX_CHARGER_CONTROL_0,
+ BQ256XX_OTG_CONFIG | BQ256XX_CHG_CONFIG_MASK,
+ READ_ONCE(bq->chg_off) ? 0 : BQ256XX_CHG_CONFIG_MASK);
+ mutex_unlock(&bq->lock);
+ if (!ret)
+ mod_delayed_work(system_power_efficient_wq, &bq->vbus_work, 0);
+ return ret;
+}
+
+static int bq2560x_otg_enabled(struct regulator_dev *rdev)
+{
+ struct bq256xx_device *bq = rdev_get_drvdata(rdev);
+ unsigned int value;
+ int ret = regmap_read(bq->regmap, BQ256XX_CHARGER_CONTROL_0, &value);
+
+ return ret ? ret : !!(value & BQ256XX_OTG_CONFIG);
+}
+
+static const struct regulator_ops bq2560x_otg_ops = {
+ .enable = bq2560x_otg_enable,
+ .disable = bq2560x_otg_disable,
+ .is_enabled = bq2560x_otg_enabled,
+};
+
+static const struct regulator_desc bq2560x_otg_desc = {
+ .name = "otg-vbus", .of_match = "otg-vbus",
+ .type = REGULATOR_VOLTAGE, .owner = THIS_MODULE,
+ .ops = &bq2560x_otg_ops, .n_voltages = 1, .fixed_uV = 5000000,
+};
+
+static int bq2560x_register_otg(struct bq256xx_device *bq)
+{
+ struct regulator_config config = {
+ .dev = bq->dev, .driver_data = bq, .regmap = bq->regmap,
+ };
+ struct regulator_dev *rdev;
+
+ rdev = devm_regulator_register(bq->dev, &bq2560x_otg_desc, &config);
+ return PTR_ERR_OR_ZERO(rdev);
}
static int bq256xx_probe(struct i2c_client *client)
@@ -2256,6 +2337,9 @@
if (ret)
return dev_err_probe(dev, ret, "VBUS extcon notifier\n");
}
+ ret = bq2560x_register_otg(bq);
+ if (ret)
+ return dev_err_probe(dev, ret, "OTG regulator\n");
mod_delayed_work(system_power_efficient_wq, &bq->vbus_work, 0);
}
@@ -0,0 +1,353 @@
/* SPDX-License-Identifier: GPL-2.0
* Copyright (C) 2019 Spreadtrum Communications Inc.
* UMP9620 register definitions and calibration from the ZTE U30 Air GPL tree:
* https://github.com/Enceka/android_kernel_zte_ums9620_mifi_u30air
* drivers/usb/typec/tcpm/sc27xx_pd.c. Policy uses mainline TCPM.
*/
static int sc27xx_pd_set_aon_clock(struct sc27xx_pd *pd, bool on)
{
int ret;
u32 mask, reg;
if (!pd->aon_apb) {
dev_warn(pd->dev, "aon apb NULL\n");
return 0;
}
mask = pd->var_data->aon_apb_r2g_analog_bb_top_sindrv_ena;
reg = pd->var_data->reg_aon_apb_mipi_csi_power_ctrl;
if (on) {
ret = regmap_update_bits(pd->aon_apb, reg, mask, mask);
if (ret)
return ret;
} else {
ret = regmap_update_bits(pd->aon_apb, reg, mask, ~mask);
if (ret)
return ret;
}
return 0;
}
static int sc27xx_pd_clk_cfg(struct sc27xx_pd *pd)
{
int ret;
ret = regmap_update_bits(pd->regmap, pd->var_data->module_en,
SC27XX_TYPEC_PD_EN, SC27XX_TYPEC_PD_EN);
if (ret)
return ret;
ret = regmap_update_bits(pd->regmap, pd->var_data->arm_clk_en0,
SC27XX_CLK_PD_EN, SC27XX_CLK_PD_EN);
if (ret)
return ret;
return regmap_update_bits(pd->regmap, pd->var_data->xtl_wait_ctrl0,
SC27XX_XTL_EN, SC27XX_XTL_EN);
}
static int sc27xx_pd_disable_clk(struct sc27xx_pd *pd)
{
int ret;
ret = regmap_update_bits(pd->regmap, pd->var_data->module_en,
SC27XX_TYPEC_PD_EN, 0);
if (ret)
return ret;
return regmap_update_bits(pd->regmap, pd->var_data->arm_clk_en0,
SC27XX_CLK_PD_EN, 0);
}
static int sc27xx_pd_rc_ref_cal(struct sc27xx_pd *pd)
{
u32 vol = 0;
u32 pd_ref = 0;
u32 val = 0;
u32 cfg2_bit7 = 0, cfg0_vth = 0, cfg0_vtl = 0, typec_ibis = 0;
u32 cfg0, cfg2, cfg0_mask, cfg2_mask = 0;
int ret;
vol = (pd->rc_cal >> SC27XX_PD_SHIFT(pd->var_data->efuse_rc_shift)) & 0x7f;
pd_ref = (pd->ref_cal >> SC27XX_PD_SHIFT(pd->var_data->efuse_ref_shift)) & 0x7;
/*
* According to the datasheet, depending on the calibration
* voltage, different register values should be configured.
*/
if (vol <= 26)
val = 0x0;
if (vol >= 27 && vol <= 37)
val = 0x1;
if (vol >= 38 && vol <= 48)
val = 0x2;
if (vol >= 49 && vol <= 59)
val = 0x3;
if (vol >= 60 && vol <= 69)
val = 0x4;
if (vol >= 70 && vol <= 80)
val = 0x5;
if (vol >= 81 && vol <= 90)
val = 0x6;
if (vol >= 91 && vol <= 127)
val = 0x7;
switch (pd_ref) {
case 0:
cfg2_bit7 = 0;
cfg0_vth = 0;
cfg0_vtl = 2;
typec_ibis = 0;
break;
case 1:
cfg2_bit7 = 0;
cfg0_vth = 1;
cfg0_vtl = 1;
typec_ibis = 1;
break;
case 2:
cfg2_bit7 = 0;
cfg0_vth = 1;
cfg0_vtl = 1;
typec_ibis = 0;
break;
case 3:
cfg2_bit7 = 1;
cfg0_vth = 1;
cfg0_vtl = 1;
typec_ibis = 0;
break;
case 4:
cfg2_bit7 = 0;
cfg0_vth = 2;
cfg0_vtl = 0;
typec_ibis = 0;
break;
}
if (typec_ibis == 1)
ret = regmap_update_bits(pd->regmap,
pd->typec_base + SC27XX_TYPEC_IBIAS,
SC27XX_TYPEC_RX_REF_DECREASE,
SC27XX_TYPEC_RX_REF_DECREASE);
else
ret = regmap_update_bits(pd->regmap,
pd->typec_base + SC27XX_TYPEC_IBIAS,
SC27XX_TYPEC_RX_REF_DECREASE, 0);
cfg0 = (cfg0_vtl << SC27XX_PD_CFG0_VTL_SHIFT) & SC27XX_PD_CFG0_VTL_MASK;
cfg0 |= (val << SC27XX_PD_CFG0_RCCAL_SHIFT) & SC27XX_PD_CFG0_RCCAL_MASK;
cfg0 |= cfg0_vth & SC27XX_PD_CFG0_VTH_MASK;
cfg0_mask = SC27XX_PD_CFG0_RCCAL_MASK |
SC27XX_PD_CFG0_VTL_MASK | SC27XX_PD_CFG0_VTH_MASK;
ret = regmap_update_bits(pd->regmap,
pd->base + SC27XX_PD_PHY_CFG0,
cfg0_mask, cfg0);
if (ret < 0)
return ret;
cfg2 = (cfg2_bit7 << SC27XX_PD_CFG2_RX_REF_CAL_SHIFT) & 0x80;
cfg2_mask = SC27XX_PD_CFG2_RX_REF_CAL_BIT;
return regmap_update_bits(pd->regmap, pd->base + SC27XX_PD_PHY_CFG2,
cfg2_mask, cfg2);
}
static int sc27xx_pd_select_clk_mode(struct sc27xx_pd *pd,
enum sc27xx_pd_clk_mode pd_clk_mode)
{
int ret;
u32 arm_clk_en0_mask, pd_cfg1_mask, pd_phy_cfg2_mask;
switch (pd_clk_mode) {
case SC27XX_PD_CLK_D6M_A6M:
arm_clk_en0_mask = (u32)SC27XX_CLK_PD_SEL;
pd_cfg1_mask = (u32)~SC27XX_PD_PHY_13M;
pd_phy_cfg2_mask = (u32)~SC27XX_PD_CFG2_PD_CLK_BIT;
break;
case SC27XX_PD_CLK_D13M_A13M:
arm_clk_en0_mask = (u32)~SC27XX_CLK_PD_SEL;
pd_cfg1_mask = (u32)SC27XX_PD_PHY_13M;
pd_phy_cfg2_mask = (u32)~SC27XX_PD_CFG2_PD_CLK_BIT;
break;
case SC27XX_PD_CLK_D13M_A6P5M:
default:
arm_clk_en0_mask = (u32)~SC27XX_CLK_PD_SEL;
pd_cfg1_mask = (u32)SC27XX_PD_PHY_13M;
pd_phy_cfg2_mask = (u32)SC27XX_PD_CFG2_PD_CLK_BIT;
break;
}
ret = regmap_update_bits(pd->regmap, pd->var_data->arm_clk_en0,
SC27XX_CLK_PD_SEL, arm_clk_en0_mask);
if (ret < 0) {
dev_err(pd->dev, "failed to set arm clk en0, ret = %d\n", ret);
return ret;
}
ret = regmap_update_bits(pd->regmap, pd->base + SC27XX_PD_CFG1,
SC27XX_PD_PHY_13M, pd_cfg1_mask);
if (ret < 0) {
dev_err(pd->dev, "failed to set pd cfg1 13m, ret = %d\n", ret);
return ret;
}
ret = regmap_update_bits(pd->regmap, pd->base + SC27XX_PD_PHY_CFG2,
SC27XX_PD_CFG2_PD_CLK_BIT, pd_phy_cfg2_mask);
if (ret < 0) {
dev_err(pd->dev, "failed to set pd cfg2 clk, ret = %d\n", ret);
return ret;
}
return 0;
}
static int sc27xx_pd_delta_cal(struct sc27xx_pd *pd)
{
u32 delta_cal = pd->delta_cal;
u32 vol, vref_sel = 0, ref_cal = 0, delta = 0;
u32 cfg1, cfg1_mask;
cfg1_mask = SC27XX_PD_CC1_SW | SC27XX_PD_CC2_SW |
SC27XX_PD_CFG1_VREF_SEL_MASK |
SC27XX_PD_CFG1_REF_CAL_MASK;
delta = ((delta_cal >> SC27XX_PD_SHIFT(pd->var_data->efuse_delta_shift)) & 0x7f);
/*
* According to the datasheet, delta is efuse caliration
* vol = delta * 2 + 1000
*/
vol = delta * 2 + 1000;
/*
* According to the datasheet, depending on the calibration
* voltage, different register values should be configured.
*/
if (vol >= 1185 && vol <= 1195) {
vref_sel = 0x0;
ref_cal = 0x0;
} else if (vol >= 1175 && vol < 1185) {
vref_sel = 0x0;
ref_cal = 0x1;
} else if (vol >= 1165 && vol < 1175) {
vref_sel = 0x0;
ref_cal = 0x2;
} else if (vol >= 1155 && vol < 1165) {
vref_sel = 0x0;
ref_cal = 0x3;
} else if (vol >= 1145 && vol < 1155) {
vref_sel = 0x0;
ref_cal = 0x4;
} else if (vol >= 1135 && vol < 1145) {
vref_sel = 0x0;
ref_cal = 0x5;
} else if (vol >= 1125 && vol < 1135) {
vref_sel = 0x0;
ref_cal = 0x6;
} else if (vol >= 1115 && vol < 1125) {
vref_sel = 0x1;
ref_cal = 0x2;
} else if (vol >= 1105 && vol < 1115) {
vref_sel = 0x1;
ref_cal = 0x3;
} else if (vol >= 1095 && vol < 1105) {
vref_sel = 0x1;
ref_cal = 0x4;
} else if (vol >= 1085 && vol < 1095) {
vref_sel = 0x1;
ref_cal = 0x5;
} else if (vol >= 1075 && vol < 1085) {
vref_sel = 0x1;
ref_cal = 0x6;
} else if (vol >= 1065 && vol < 1075) {
vref_sel = 0x2;
ref_cal = 0x2;
} else if (vol >= 1055 && vol < 1065) {
vref_sel = 0x2;
ref_cal = 0x3;
} else if (vol >= 1045 && vol < 1055) {
vref_sel = 0x2;
ref_cal = 0x4;
} else if (vol >= 1035 && vol < 1045) {
vref_sel = 0x2;
ref_cal = 05;
} else if (vol >= 1025 && vol < 1035) {
vref_sel = 0x2;
ref_cal = 0x6;
} else if (vol >= 1015 && vol < 1025) {
vref_sel = 0x3;
ref_cal = 0x2;
} else if (vol >= 1005 && vol < 1015) {
vref_sel = 0x3;
ref_cal = 0x3;
} else if (vol >= 1000 && vol < 1005) {
vref_sel = 0x3;
ref_cal = 0x4;
}
cfg1 = SC27XX_PD_CC1_SW | SC27XX_PD_CC2_SW;
cfg1 |= (vref_sel << SC27XX_PD_CFG1_VREF_SEL_SHIFT)
& SC27XX_PD_CFG1_VREF_SEL_MASK;
cfg1 |= (ref_cal << SC27XX_PD_CFG1_REF_CAL_SHIFT)
& SC27XX_PD_CFG1_REF_CAL_MASK;
return regmap_update_bits(pd->regmap, pd->base + SC27XX_PD_PHY_CFG1,
cfg1_mask, cfg1);
}
static int sc27xx_pd_efuse_read(struct sc27xx_pd *pd,
const char *cell_id, u32 *val)
{
struct nvmem_cell *cell;
void *buf;
size_t len = 0;
cell = nvmem_cell_get(pd->dev, cell_id);
if (IS_ERR_OR_NULL(cell))
return PTR_ERR(cell);
buf = nvmem_cell_read(cell, &len);
nvmem_cell_put(cell);
if (IS_ERR(buf))
return PTR_ERR(buf);
memcpy(val, buf, min(len, sizeof(u16)));
kfree(buf);
return 0;
}
static int sc27xx_pd_cal(struct sc27xx_pd *pd)
{
int ret;
ret = sc27xx_pd_efuse_read(pd, "pdrc_calib", &pd->rc_cal);
if (ret)
return ret;
ret = sc27xx_pd_efuse_read(pd, "pddelta_calib", &pd->delta_cal);
if (ret)
return ret;
if (pd->var_data->id == PMIC_SC2730 || pd->var_data->id == PMIC_UMP518) {
ret = sc27xx_pd_efuse_read(pd, "pdref_calib", &pd->ref_cal);
if (ret)
return ret;
} else if (pd->var_data->id == PMIC_UMP9620) {
/*
* ump9620 pdref_calib use the same block
* with pddelta_calib--block 36.
*/
ret = sc27xx_pd_efuse_read(pd, "pddelta_calib", &pd->ref_cal);
if (ret)
return ret;
}
return 0;
}
@@ -0,0 +1,307 @@
/* SPDX-License-Identifier: GPL-2.0
* Copyright (C) 2019 Spreadtrum Communications Inc.
* UMP9620 register definitions and calibration from the ZTE U30 Air GPL tree:
* https://github.com/Enceka/android_kernel_zte_ums9620_mifi_u30air
* drivers/usb/typec/tcpm/sc27xx_pd.c. Policy uses mainline TCPM.
*/
/* PMIC global registers definition */
#define SC27XX_MODULE_EN 0x1808
#define SC27XX_ARM_CLK_EN0 0x180c
#define SC27XX_RTC_CLK_EN0 0x1810
#define SC27XX_XTL_WAIT_CTRL0 0x1b78
#define UMP9620_MODULE_EN 0x2008
#define UMP9620_ARM_CLK_EN0 0x200c
#define UMP9620_RTC_CLK_EN0 0x2010
#define UMP9620_XTL_WAIT_CTRL0 0x2378
#define UMP518_MODULE_EN 0x1808
#define UMP518_ARM_CLK_EN0 0x180c
#define UMP518_RTC_CLK_EN0 0x1810
#define UMP518_XTL_WAIT_CTRL0 0x1b78
#define SC27XX_TYPEC_PD_EN BIT(13)
#define SC27XX_CLK_PD_SEL BIT(10)
#define SC27XX_CLK_PD_EN BIT(9)
#define SC27XX_XTL_EN BIT(8)
/* Typec controller registers definition */
#define SC27XX_TYPEC_EN 0x0
#define SC27XX_TYPEC_MODE 0x4
#define SC27XX_TYPEC_PD_CFG 0x8
#define SC27XX_TYPEC_STATUS 0x1c
#define SC27XX_TYPEC_SW_CFG 0x54
#define SC27XX_TYPEC_WC_REG 0x58
#define SC27XX_TYPEC_DBG1 0x60
#define SC27XX_TYPEC_IBIAS 0x70
#define SC27XX_TYPEC_RP_LEVEL(x) (((x) << 2) & GENMASK(3, 2))
#define SC27XX_TYPEC_TRY_SRC_EN BIT(7)
#define SC27XX_TYPEC_TRY_SINK_EN BIT(8)
/* PD controller registers definition */
#define SC27XX_PD_TX_BUF 0x0
#define SC27XX_PD_RX_BUF 0x4
#define SC27XX_PD_HEAD_CFG 0x8
#define SC27XX_PD_CTRL 0xc
#define SC27XX_PD_CFG0 0x10
#define SC27XX_PD_CFG1 0x14
#define SC27XX_PD_MESG_ID_CFG 0x18
#define SC27XX_PD_STS0 0x1c
#define SC27XX_PD_STS1 0x20
#define SC27XX_INT_STS 0x24
#define SC27XX_INT_FLG 0x28
#define SC27XX_INT_CLR 0x2c
#define SC27XX_INT_EN 0x30
#define SC27XX_PD_PHY_CFG0 0x50
#define SC27XX_PD_PHY_CFG1 0x54
#define SC27XX_PD_PHY_CFG2 0x58
/* Bits definitions for SC27XX_TYPEC_PD_CFG register */
#define SC27XX_TYPEC_PD_SUPPORT BIT(0)
#define SC27XX_TYPEC_PD_CONSTRACT BIT(6)
#define SC27XX_TYPEC_PD_NO_CHEK_DETACH BIT(9)
#define SC27XX_TYPEC_SW_FORCE_CC(x) (((x) << 10) & GENMASK(11, 10))
#define SC27XX_TYPEC_VCCON_LDO_RDY BIT(12)
#define SC27XX_TYPEC_VCCON_LDO_EN BIT(13)
/* Bits definitions for SC27XX_TYPEC_STATUS register */
#define SC27XX_TYPEC_CURRENT_STATUS GENMASK(4, 0)
#define SC27XX_TYPEC_FINAL_SWITCH BIT(5)
#define SC27XX_TYPEC_VBUS_CL(x) (((x) & GENMASK(7, 6)) >> 6)
/* Bits definitions for SC27XX_TYPEC_WC_REG register */
#define SC27XX_TYPEC_PD_PR_SWAP BIT(2)
#define SC27XX_TYPEC_PD_VCONN_SWAP BIT(1)
/* Bits definitions for SC27XX_TYPEC_DBG1 register */
#define SC27XX_TYPEC_VBUS_OK BIT(8)
#define SC27XX_TYPEC_CONN_CC BIT(9)
/* Bits definitions for SC27XX_TYPEC_IBIAS register */
#define SC27XX_TYPEC_RX_REF_DECREASE BIT(7)
/* Bits definitions for SC27XX_PD_HEAD_CFG register */
#define SC27XX_PD_EXTHEAD BIT(15)
#define SC27XX_PD_NUM_DO(x) (((x) << 12) & GENMASK(14, 12))
#define SC27XX_PD_MESS_ID(x) (((x) << 9) & GENMASK(11, 9))
#define SC27XX_PD_POWER_ROLE BIT(8)
#define SC27XX_PD_SPEC_REV(x) (((x) << 6) & GENMASK(7, 6))
#define SC27XX_PD_DATA_ROLE BIT(5)
#define SC27XX_PD_MESSAGE_TYPE(x) ((x) & GENMASK(4, 0))
#define SC27XX_PD_SPEC_MASK GENMASK(7, 6)
/* Bits definitions for SC27XX_PD_CTRL register */
#define SC27XX_PD_TX_START BIT(0)
#define SC27XX_PD_HARD_RESET BIT(2)
#define SC27XX_PD_TX_FLASH BIT(3)
#define SC27XX_PD_RX_FLASH BIT(4)
#define SC27XX_PD_FAST_START BIT(6)
#define SC27XX_PD_CABLE_RESET BIT(7)
#define SC27XX_PD_RX_ID_CLR BIT(8)
#define SC27XX_PD_RP_SINKTXNG_CLR BIT(9)
/* Bits definitions for SC27XX_PD_CFG0 register */
#define SC27XX_PD_RP_CONTROL(x) ((x) & GENMASK(1, 0))
#define SC27XX_PD_SINK_RP GENMASK(3, 2)
#define SC27XX_PD_EN_SOP1_TX BIT(6)
#define SC27XX_PD_EN_SOP2_TX BIT(7)
#define SC27XX_PD_EN_SOP BIT(8)
#define SC27XX_PD_SRC_SINK_MODE BIT(9)
#define SC27XX_PD_CTL_EN BIT(10)
#define SC27XX_PD_BIST_MODE_EN BIT(11)
/* Bits definitions for SC27XX_PD_CFG1 register */
#define SC27XX_PD_AUTO_RETRY BIT(0)
#define SC27XX_PD_RETRY(x) (((x) << 1) & GENMASK(2, 1))
#define SC27XX_PD_HEADER_REG_EN BIT(3)
#define SC27XX_PD_EN_SOP1_RX BIT(6)
#define SC27XX_PD_EN_SOP2_RX BIT(7)
#define SC27XX_PD_EN_SOP_RX BIT(8)
#define SC27XX_PD_RX_AUTO_GOOD_CRC BIT(9)
#define SC27XX_PD_FRS_DETECT_EN BIT(10)
#define SC27XX_PD_PHY_13M BIT(11)
#define SC27XX_PD_TX_AUTO_GOOD_CRC BIT(12)
/* Bits definitions for SC27XX_PD_MESG_ID_CFG register */
#define SC27XX_PD_MESS_ID_TX(x) ((x) & GENMASK(2, 0))
#define SC27XX_PD_MESS_ID_RX(x) (((x) << 4) & GENMASK(6, 4))
#define SC27XX_PD_RETRY_MASK GENMASK(2, 1)
#define SC27XX_PD_MESS_ID_MASK GENMASK(2, 0)
/* Bits definitions for SC27XX_TYPEC_SW_CFG register */
#define SC27XX_TYPEC_SW_SWITCH(x) (((x) << 10) & GENMASK(11, 10))
/* Bits definitions for SC27XX_INT_FLG register */
#define SC27XX_PD_HARD_RST_FLAG BIT(0)
#define SC27XX_PD_CABLE_RST_FLAG BIT(1)
#define SC27XX_PD_SOFT_RST_FLAG BIT(2)
#define SC27XX_PD_PS_RDY_FLAG BIT(3)
#define SC27XX_PD_PKG_RV_FLAG BIT(4)
#define SC27XX_PD_TX_OK_FLAG BIT(5)
#define SC27XX_PD_TX_ERROR_FLAG BIT(6)
#define SC27XX_PD_TX_COLLSION_FLAG BIT(7)
#define SC27XX_PD_PKG_RV_ERROR_FLAG BIT(8)
#define SC27XX_PD_FRS_RV_FLAG BIT(9)
#define SC27XX_PD_RX_FIFO_OVERFLOW_FLAG BIT(10)
/* Bits definitions for SC27XX_PD_STS1 register */
#define SC27XX_PD_RX_DATA_NUM_MASK GENMASK(8, 0)
#define SC27XX_PD_RX_EMPTY BIT(13)
/* Bits definitions for SC27XX_INT_CLR register */
#define SC27XX_PD_HARD_RST_RV_CLR BIT(0)
#define SC27XX_PD_CABLE_RST_RV_CLR BIT(1)
#define SC27XX_PD_SOFT_RST_RV_CLR BIT(2)
#define SC27XX_PD_PS_RDY_CLR BIT(3)
#define SC27XX_PD_PKG_RV_CLR BIT(4)
#define SC27XX_PD_TX_OK_CLR BIT(5)
#define SC27XX_PD_TX_ERROR_CLR BIT(6)
#define SC27XX_PD_TX_COLLSION_CLR BIT(7)
#define SC27XX_PD_PKG_RV_ERROR_CLR BIT(8)
#define SC27XX_PD_FRS_RV_CLR BIT(9)
#define SC27XX_PD_RX_FIFO_OVERFLOW_CLR BIT(10)
/* Bits definitions for SC27XX_INT_EN register */
#define SC27XX_PD_HARD_RST_RV_EN BIT(0)
#define SC27XX_PD_CABLE_RST_RV_EN BIT(1)
#define SC27XX_PD_SOFT_RST_RV_EN BIT(2)
#define SC27XX_PD_PS_RDY_EN BIT(3)
#define SC27XX_PD_PKG_RV_EN BIT(4)
#define SC27XX_PD_TX_OK_EN BIT(5)
#define SC27XX_PD_TX_ERROR_EN BIT(6)
#define SC27XX_PD_TX_COLLSION_EN BIT(7)
#define SC27XX_PD_PKG_RV_ERROR_EN BIT(8)
#define SC27XX_PD_FRS_RV_EN BIT(9)
#define SC27XX_PD_RX_FIFO_OVERFLOW_EN BIT(10)
/* SC27XX_PD_PHY_CFG1 */
#define SC27XX_PD_CC1_SW BIT(3)
#define SC27XX_PD_CC2_SW BIT(2)
/* SC27XX_PD_PHY_CFG2 */
#define SC27XX_PD_CFG2_PD_CLK_BIT BIT(6)
#define SC27XX_PD_CFG2_RX_REF_CAL_BIT BIT(7)
#define SC27XX_PD_CFG2_RX_REF_CAL_SHIFT 7
#define SC27XX_TX_RX_BUF_MASK GENMASK(15, 0)
#define SC27XX_PD_INT_CLR GENMASK(13, 0)
#define SC27XX_STATE_MASK GENMASK(4, 0)
#define SC27XX_EVENT_MASK GENMASK(15, 0)
#define SC27XX_TYPEC_INT_CLR_MASK GENMASK(9, 0)
#define SC27XX_PD_HEAD_CONFIG_MASK GENMASK(15, 0)
#define SC27XX_PD_CFG0_MASK GENMASK(8, 0)
#define SC27XX_PD_PHY_CFG0_MASK 0x5102
#define SC27XX_PD_PHY_CFG1_MASK 0x463c
#define SC27XX_PD_PHY_CFG2_MASK 0x40
#define SC27XX_PD_CFG0_RCCAL_MASK GENMASK(8, 6)
#define SC27XX_PD_CFG0_VTL_MASK GENMASK(3, 2)
#define SC27XX_PD_CFG0_VTH_MASK GENMASK(1, 0)
#define SC27XX_PD_CFG0_RCCAL_SHIFT 6
#define SC27XX_PD_CFG0_VTL_SHIFT 2
#define SC27XX_PD_CFG1_VREF_SEL_MASK GENMASK(7, 6)
#define SC27XX_PD_CFG1_REF_CAL_MASK GENMASK(14, 12)
#define SC27XX_PD_CFG1_VREF_SEL_SHIFT 6
#define SC27XX_PD_CFG1_REF_CAL_SHIFT 12
#define SC27XX_PD_DATA_MASK GENMASK(15, 0)
#define SC27XX_INT_CLR_MASK 0x3fff
#define SC27XX_INT_EN_MASK 0x85ff
#define SC27xx_DETECT_TYPEC_DELAY 700
/* chunked extended message */
#define SC27XX_CHUNKED_EXT_MSG_MASK GENMASK(7, 0)
#define SC27XX_CHUNKED_EXT_MSG_SHIFT 8
/* Timeout (us) for pd data ready according pd datasheet */
#define SC27XX_PD_RDY_TIMEOUT 2000
#define SC27XX_PD_POLL_RAW_STATUS 50
#define SC27XX_TYPEC_VBUS_OK_TIMEOUT 80000
#define SC27XX_TYPEC_VBUS_OK_STATUS 100
/* Timeout (us) for vbus ready according need */
#define SC27XX_PD_VBUS_TIMEOUT 200000
#define SC27XX_PD_POLL_VBUS_STATUS 50
/* pmic compatible */
#define SC2730_RC_EFUSE_SHIFT 9
#define SC2730_REF_EFUSE_SHIFT 12
#define SC2730_DELTA_EFUSE_SHIFT 7
#define UMP9620_RC_EFUSE_SHIFT 5
#define UMP9620_REF_EFUSE_SHIFT 6
#define UMP9620_DELTA_EFUSE_SHIFT 9
#define UMP518_RC_EFUSE_SHIFT 9
#define UMP518_REF_EFUSE_SHIFT 0
#define UMP518_DELTA_EFUSE_SHIFT 9
/* soc compatible */
#define UMS9620_MASK_AON_APB_R2G_ANALOG_BB_TOP_SINDRV_ENA 0x0020
#define UMS9620_REG_AON_APB_MIPI_CSI_POWER_CTRL 0x0350
#define SC27XX_PD_SHIFT(n) (n)
#define PMIC_SC2730 1
#define PMIC_UMP9620 2
#define PMIC_UMP518 3
#define SC27XX_PD_RX_ERROR_CNT_THRESHOLD 100
#define SC27XX_PD_RX_ERROR_TIME_THRESHOLD 120
#define SC27XX_PD_HARD_RESET_TIME_THRESHOLD 4
#define SC27XX_PD_RX_ERROR_INT_STATUS 0x100
enum sc27xx_state {
SC27XX_DETACHED_SNK,
SC27XX_ATTACHWAIT_SNK,
SC27XX_ATTACHED_SNK,
SC27XX_DETACHED_SRC,
SC27XX_ATTACHWAIT_SRC,
SC27XX_ATTACHED_SRC,
SC27XX_POWERED_CABLE,
SC27XX_AUDIO_CABLE,
SC27XX_DEBUG_CABLE,
};
enum sc27xx_dp_hpd_status {
SC27XX_DP_HOT_UNPLUG = 0,
SC27XX_DP_HOT_PLUG,
SC27XX_DP_HPD_IRQ,
SC27XX_DP_TYPE_DISCONNECT,
};
enum sc27xx_pd_clk_mode {
SC27XX_PD_CLK_D6M_A6M = 0,
SC27XX_PD_CLK_D13M_A6P5M,
SC27XX_PD_CLK_D13M_A13M,
};
struct sc27xx_pd_variant_data {
u32 efuse_rc_shift;
u32 efuse_ref_shift;
u32 efuse_delta_shift;
u32 id;
u32 module_en;
u32 arm_clk_en0;
u32 rtc_clk_en0;
u32 xtl_wait_ctrl0;
u32 aon_apb_r2g_analog_bb_top_sindrv_ena;
u32 reg_aon_apb_mipi_csi_power_ctrl;
};
static const struct sc27xx_pd_variant_data ump9620_data = {
.efuse_rc_shift = UMP9620_RC_EFUSE_SHIFT,
.efuse_ref_shift = UMP9620_REF_EFUSE_SHIFT,
.efuse_delta_shift = UMP9620_DELTA_EFUSE_SHIFT,
.id = PMIC_UMP9620,
.module_en = UMP9620_MODULE_EN,
.arm_clk_en0 = UMP9620_ARM_CLK_EN0,
.rtc_clk_en0 = UMP9620_RTC_CLK_EN0,
.xtl_wait_ctrl0 = UMP9620_XTL_WAIT_CTRL0,
.aon_apb_r2g_analog_bb_top_sindrv_ena =
UMS9620_MASK_AON_APB_R2G_ANALOG_BB_TOP_SINDRV_ENA,
.reg_aon_apb_mipi_csi_power_ctrl =
UMS9620_REG_AON_APB_MIPI_CSI_POWER_CTRL,
};
@@ -0,0 +1,654 @@
// SPDX-License-Identifier: GPL-2.0
/*
* UMP9620 Type-C/PD controller, using mainline TCPM policy.
* Register/PHY programming follows Spreadtrum's ZTE U30 Air GPL driver.
* USB data role and VBUS power role are deliberately independent: a powered
* dock must be able to charge the battery while DWC3 remains the USB host.
*/
#include <linux/bitfield.h>
#include <linux/delay.h>
#include <linux/extcon.h>
#include <linux/interrupt.h>
#include <linux/mfd/syscon.h>
#include <linux/module.h>
#include <linux/nvmem-consumer.h>
#include <linux/of.h>
#include <linux/of_irq.h>
#include <linux/platform_device.h>
#include <linux/power_supply.h>
#include <linux/property.h>
#include <linux/regmap.h>
#include <linux/regulator/consumer.h>
#include <linux/usb/pd.h>
#include <linux/usb/role.h>
#include <linux/usb/tcpm.h>
#include <linux/workqueue.h>
#include "sc27xx-ump9620-regs.h"
struct sc27xx_pd {
struct device *dev;
struct regmap *regmap, *aon_apb;
const struct sc27xx_pd_variant_data *var_data;
struct tcpc_dev tcpc;
struct tcpm_port *port;
struct usb_role_switch *role_sw;
struct regulator *vbus;
struct power_supply *charger;
struct mutex lock;
struct delayed_work cc_work;
struct notifier_block vbus_nb;
struct extcon_dev *vbus_extcon;
struct fwnode_handle *connector;
u32 base, typec_base, rc_cal, delta_cal, ref_cal;
int irq, cc_irq;
enum typec_role power_role;
bool attached, pd_capable;
bool vbus_on, tx_pending, stopping, irqs_enabled;
};
#include "sc27xx-ump9620-calibration.h"
static struct sc27xx_pd *to_pd(struct tcpc_dev *tcpc)
{
return container_of(tcpc, struct sc27xx_pd, tcpc);
}
static int pd_update(struct sc27xx_pd *pd, u32 reg, u32 mask, u32 value)
{
return regmap_update_bits(pd->regmap, pd->base + reg, mask, value);
}
static int cc_update(struct sc27xx_pd *pd, u32 reg, u32 mask, u32 value)
{
return regmap_update_bits(pd->regmap, pd->typec_base + reg, mask, value);
}
static int sc27xx_get_vbus(struct tcpc_dev *tcpc)
{
struct sc27xx_pd *pd = to_pd(tcpc);
u32 status;
int ret = regmap_read(pd->regmap, pd->typec_base + SC27XX_TYPEC_DBG1, &status);
return ret ? ret : !!(status & SC27XX_TYPEC_VBUS_OK);
}
static int sc27xx_get_cc(struct tcpc_dev *tcpc, enum typec_cc_status *cc1,
enum typec_cc_status *cc2)
{
struct sc27xx_pd *pd = to_pd(tcpc);
enum typec_cc_status active = TYPEC_CC_OPEN;
u32 status, state;
int ret = regmap_read(pd->regmap, pd->typec_base + SC27XX_TYPEC_STATUS, &status);
if (ret)
return ret;
state = status & SC27XX_STATE_MASK;
if (state == SC27XX_ATTACHED_SNK) {
switch (SC27XX_TYPEC_VBUS_CL(status)) {
case 0: active = TYPEC_CC_RP_DEF; break;
case 1: active = TYPEC_CC_RP_1_5; break;
case 2: active = TYPEC_CC_RP_3_0; break;
}
} else if (state == SC27XX_ATTACHED_SRC || state == SC27XX_POWERED_CABLE) {
active = TYPEC_CC_RD;
}
*cc1 = *cc2 = TYPEC_CC_OPEN;
if (status & SC27XX_TYPEC_FINAL_SWITCH) {
*cc1 = active;
if (state == SC27XX_POWERED_CABLE)
*cc2 = TYPEC_CC_RA;
} else {
*cc2 = active;
if (state == SC27XX_POWERED_CABLE)
*cc1 = TYPEC_CC_RA;
}
return 0;
}
static int sc27xx_set_cc(struct tcpc_dev *tcpc, enum typec_cc_status cc)
{
struct sc27xx_pd *pd = to_pd(tcpc);
u32 mode, rp = 1;
/* The autonomous controller owns detach/open, as in the vendor driver. */
if (cc == TYPEC_CC_OPEN)
return 0;
if (cc == TYPEC_CC_RD)
mode = 0;
else {
mode = 1;
if (cc == TYPEC_CC_RP_1_5)
rp = 2;
else if (cc == TYPEC_CC_RP_3_0)
rp = 3;
}
if (pd->attached && ((cc == TYPEC_CC_RD && pd->power_role == TYPEC_SOURCE) ||
(cc != TYPEC_CC_RD && pd->power_role == TYPEC_SINK))) {
int ret = regmap_write_bits(pd->regmap, pd->typec_base + SC27XX_TYPEC_WC_REG,
SC27XX_TYPEC_PD_PR_SWAP, SC27XX_TYPEC_PD_PR_SWAP);
if (ret)
return ret;
}
return cc_update(pd, SC27XX_TYPEC_MODE, GENMASK(3, 0), mode | (rp << 2));
}
static int sc27xx_start_toggling(struct tcpc_dev *tcpc, enum typec_port_type port,
enum typec_cc_status cc)
{
struct sc27xx_pd *pd = to_pd(tcpc);
u32 mode = port == TYPEC_PORT_DRP ? 2 : port == TYPEC_PORT_SNK ? 0 : 1;
int ret;
/* Hardware DRP, no userspace polling or periodic role-flip task. */
ret = cc_update(pd, SC27XX_TYPEC_MODE, GENMASK(3, 0), mode | BIT(2));
/* A cable already attached before probe may not generate another edge. */
if (!ret && !READ_ONCE(pd->stopping))
mod_delayed_work(system_power_efficient_wq, &pd->cc_work, msecs_to_jiffies(8));
return ret;
}
static int sc27xx_set_polarity(struct tcpc_dev *tcpc, enum typec_cc_polarity polarity)
{
/* The autonomous Type-C block selects the active CC pin. The similarly
* named PHY_CFG1 bits are calibration switches, not a polarity mux. */
return 0;
}
static int sc27xx_set_vconn(struct tcpc_dev *tcpc, bool on)
{
return cc_update(to_pd(tcpc), SC27XX_TYPEC_PD_CFG,
SC27XX_TYPEC_VCCON_LDO_EN, on ? SC27XX_TYPEC_VCCON_LDO_EN : 0);
}
static int sc27xx_set_vbus(struct tcpc_dev *tcpc, bool on, bool charge)
{
struct sc27xx_pd *pd = to_pd(tcpc);
int ret = 0;
if (on && charge)
return -EINVAL;
mutex_lock(&pd->lock);
if (pd->vbus_on != on) {
ret = on ? regulator_enable(pd->vbus) : regulator_disable(pd->vbus);
if (!ret)
pd->vbus_on = on;
}
mutex_unlock(&pd->lock);
/* The charger driver retains the user's charge limit when boost is off. */
return ret;
}
static int sc27xx_set_current_limit(struct tcpc_dev *tcpc, u32 ma, u32 mv)
{
struct sc27xx_pd *pd = to_pd(tcpc);
union power_supply_propval value;
int ret;
/* Only 5 V is advertised; do not request unsupported higher PD voltages. */
if (mv > 5000)
return -EINVAL;
value.intval = ma && pd->pd_capable ? POWER_SUPPLY_USB_TYPE_PD : POWER_SUPPLY_USB_TYPE_UNKNOWN;
ret = power_supply_set_property(pd->charger, POWER_SUPPLY_PROP_USB_TYPE, &value);
if (ret || !ma)
return ret;
value.intval = min(ma, 2000U) * 1000;
return power_supply_set_property(pd->charger, POWER_SUPPLY_PROP_INPUT_CURRENT_LIMIT, &value);
}
static int sc27xx_set_roles(struct tcpc_dev *tcpc, bool attached,
enum typec_role power, enum typec_data_role data)
{
struct sc27xx_pd *pd = to_pd(tcpc);
enum usb_role usb = !attached ? USB_ROLE_DEVICE :
data == TYPEC_HOST ? USB_ROLE_HOST : USB_ROLE_DEVICE;
int ret;
ret = pd_update(pd, SC27XX_PD_CFG0, SC27XX_PD_SRC_SINK_MODE,
power == TYPEC_SOURCE ? SC27XX_PD_SRC_SINK_MODE : 0);
if (ret)
return ret;
/* A PD data-role swap must never implicitly enable the charger's boost. */
ret = usb_role_switch_set_role(pd->role_sw, usb);
if (!ret)
dev_info(pd->dev, "%s: USB %s, power %s\n", attached ? "attached" : "detached",
usb_role_string(usb), power == TYPEC_SOURCE ? "source" : "sink");
if (!ret) {
pd->attached = attached;
pd->power_role = power;
if (!attached)
pd->pd_capable = false;
}
return ret;
}
static int sc27xx_set_rx(struct tcpc_dev *tcpc, bool on)
{
struct sc27xx_pd *pd = to_pd(tcpc);
int ret;
ret = pd_update(pd, SC27XX_PD_CFG1, SC27XX_PD_EN_SOP_RX | SC27XX_PD_RX_AUTO_GOOD_CRC,
on ? SC27XX_PD_EN_SOP_RX | SC27XX_PD_RX_AUTO_GOOD_CRC : 0);
if (ret)
return ret;
return pd_update(pd, SC27XX_PD_CFG0, SC27XX_PD_CTL_EN | SC27XX_PD_EN_SOP,
on ? SC27XX_PD_CTL_EN | SC27XX_PD_EN_SOP : 0);
}
static int sc27xx_transmit(struct tcpc_dev *tcpc, enum tcpm_transmit_type type,
const struct pd_message *msg, unsigned int rev)
{
struct sc27xx_pd *pd = to_pd(tcpc);
int ret, i, count = msg ? pd_header_cnt_le(msg->header) : 0;
u32 payload;
if (type != TCPC_TX_SOP && type != TCPC_TX_HARD_RESET)
return -EOPNOTSUPP;
mutex_lock(&pd->lock);
ret = pd_update(pd, SC27XX_PD_CFG1, SC27XX_PD_RETRY_MASK,
SC27XX_PD_RETRY(rev >= PD_REV30 ? 1 : 3));
if (ret)
goto out;
/* Flush/reset bits are strobes: repeated transactions must write them. */
ret = regmap_write_bits(pd->regmap, pd->base + SC27XX_PD_CTRL,
SC27XX_PD_TX_FLASH, SC27XX_PD_TX_FLASH);
if (ret)
goto out;
if (type == TCPC_TX_HARD_RESET) {
ret = regmap_write_bits(pd->regmap, pd->base + SC27XX_PD_CTRL,
SC27XX_PD_HARD_RESET, SC27XX_PD_HARD_RESET);
goto pending;
}
ret = regmap_write(pd->regmap, pd->base + SC27XX_PD_HEAD_CFG, le16_to_cpu(msg->header));
for (i = 0; !ret && i < count; i++) {
payload = le32_to_cpu(msg->payload[i]);
ret = regmap_write(pd->regmap, pd->base + SC27XX_PD_TX_BUF, payload & 0xffff);
if (!ret)
ret = regmap_write(pd->regmap, pd->base + SC27XX_PD_TX_BUF, payload >> 16);
}
if (!ret)
ret = regmap_write_bits(pd->regmap, pd->base + SC27XX_PD_CTRL,
SC27XX_PD_TX_START, SC27XX_PD_TX_START);
pending:
if (!ret)
pd->tx_pending = true;
out:
mutex_unlock(&pd->lock);
return ret;
}
static void sc27xx_complete_tx(struct sc27xx_pd *pd, enum tcpm_transmit_status status)
{
/* The same packet may produce TX_OK and an explicit GoodCRC reception. */
if (pd->tx_pending) {
pd->tx_pending = false;
tcpm_pd_transmit_complete(pd->port, status);
}
}
static int sc27xx_receive(struct sc27xx_pd *pd)
{
struct pd_message msg = {};
u32 word, low, high;
int ret, count, i;
ret = regmap_read(pd->regmap, pd->base + SC27XX_PD_RX_BUF, &word);
if (ret)
return ret;
msg.header = cpu_to_le16(word);
pd->pd_capable = true;
count = pd_header_cnt_le(msg.header);
for (i = 0; i < count; i++) {
ret = regmap_read(pd->regmap, pd->base + SC27XX_PD_RX_BUF, &low);
if (ret)
return ret;
ret = regmap_read(pd->regmap, pd->base + SC27XX_PD_RX_BUF, &high);
if (ret)
return ret;
msg.payload[i] = cpu_to_le32((low & 0xffff) | (high << 16));
}
if (!count && pd_header_type_le(msg.header) == PD_CTRL_GOOD_CRC) {
cc_update(pd, SC27XX_TYPEC_PD_CFG, SC27XX_TYPEC_PD_CONSTRACT,
SC27XX_TYPEC_PD_CONSTRACT);
sc27xx_complete_tx(pd, TCPC_TX_SUCCESS);
} else {
tcpm_pd_receive(pd->port, &msg, TCPC_TX_SOP);
}
return 0;
}
static irqreturn_t sc27xx_pd_irq(int irq, void *data)
{
struct sc27xx_pd *pd = data;
u32 flags;
int ret = 0;
mutex_lock(&pd->lock);
ret = regmap_read(pd->regmap, pd->base + SC27XX_INT_FLG, &flags);
if (ret)
goto out;
regmap_write(pd->regmap, pd->base + SC27XX_INT_CLR, flags & SC27XX_INT_CLR_MASK);
if (flags & SC27XX_PD_HARD_RST_FLAG) {
pd->tx_pending = false;
regmap_write_bits(pd->regmap, pd->base + SC27XX_PD_CTRL,
SC27XX_PD_RX_FLASH | SC27XX_PD_RX_ID_CLR,
SC27XX_PD_RX_FLASH | SC27XX_PD_RX_ID_CLR);
tcpm_pd_hard_reset(pd->port);
}
if (flags & SC27XX_PD_PKG_RV_FLAG) {
/* The FIFO holds one received frame plus controller trailer words.
* They are not another PD header. Match the vendor receive/flush
* sequence instead of passing those words to TCPM as messages. */
ret = sc27xx_receive(pd);
if (!ret)
ret = regmap_write_bits(pd->regmap, pd->base + SC27XX_PD_CTRL,
SC27XX_PD_RX_FLASH, SC27XX_PD_RX_FLASH);
}
if (flags & (SC27XX_PD_TX_ERROR_FLAG | SC27XX_PD_TX_COLLSION_FLAG))
sc27xx_complete_tx(pd, TCPC_TX_FAILED);
else if (flags & SC27XX_PD_TX_OK_FLAG)
sc27xx_complete_tx(pd, TCPC_TX_SUCCESS);
if (ret || (flags & SC27XX_PD_RX_FIFO_OVERFLOW_FLAG)) {
regmap_write_bits(pd->regmap, pd->base + SC27XX_PD_CTRL,
SC27XX_PD_RX_FLASH, SC27XX_PD_RX_FLASH);
dev_warn_ratelimited(pd->dev, "PD receive error %d, flags %#x\n", ret, flags);
}
out:
mutex_unlock(&pd->lock);
return IRQ_HANDLED;
}
static void sc27xx_cc_work(struct work_struct *work)
{
struct sc27xx_pd *pd = container_of(to_delayed_work(work), struct sc27xx_pd, cc_work);
if (!pd->stopping && pd->port) {
tcpm_cc_change(pd->port);
tcpm_vbus_change(pd->port);
}
}
static irqreturn_t sc27xx_cc_irq(int irq, void *data)
{
struct sc27xx_pd *pd = data;
u32 event;
if (regmap_read(pd->regmap, pd->typec_base + 0x14, &event))
return IRQ_NONE;
regmap_write(pd->regmap, pd->typec_base + 0x10, event & GENMASK(9, 0));
mod_delayed_work(system_power_efficient_wq, &pd->cc_work, msecs_to_jiffies(8));
return IRQ_HANDLED;
}
static int sc27xx_vbus_event(struct notifier_block *nb, unsigned long event, void *data)
{
struct sc27xx_pd *pd = container_of(nb, struct sc27xx_pd, vbus_nb);
if (!READ_ONCE(pd->stopping) && READ_ONCE(pd->port))
mod_delayed_work(system_power_efficient_wq, &pd->cc_work, msecs_to_jiffies(8));
return NOTIFY_OK;
}
static int sc27xx_init(struct tcpc_dev *tcpc)
{
struct sc27xx_pd *pd = to_pd(tcpc);
int ret;
ret = sc27xx_pd_set_aon_clock(pd, true);
if (ret)
return ret;
ret = sc27xx_pd_clk_cfg(pd);
if (ret)
return ret;
ret = sc27xx_pd_delta_cal(pd);
if (ret)
return ret;
ret = sc27xx_pd_rc_ref_cal(pd);
if (ret)
return ret;
ret = sc27xx_pd_select_clk_mode(pd, SC27XX_PD_CLK_D6M_A6M);
if (ret)
return ret;
ret = cc_update(pd, SC27XX_TYPEC_PD_CFG, SC27XX_TYPEC_PD_SUPPORT,
SC27XX_TYPEC_PD_SUPPORT);
if (ret)
return ret;
ret = regmap_write(pd->regmap, pd->typec_base + 0x20, 0xc7f);
if (ret)
return ret;
ret = regmap_update_bits(pd->regmap, 0x234c, BIT(4), BIT(4));
if (ret)
return ret;
ret = pd_update(pd, SC27XX_PD_CFG0, SC27XX_PD_BIST_MODE_EN, SC27XX_PD_BIST_MODE_EN);
if (ret)
return ret;
regmap_write(pd->regmap, pd->base + SC27XX_INT_CLR, SC27XX_INT_CLR_MASK);
ret = regmap_write(pd->regmap, pd->base + SC27XX_INT_EN, SC27XX_INT_EN_MASK);
if (ret)
return ret;
return cc_update(pd, 0x0c, BIT(0) | BIT(1), BIT(0) | BIT(1));
}
static void sc27xx_cleanup(void *data)
{
struct sc27xx_pd *pd = data;
if (pd->stopping)
return;
WRITE_ONCE(pd->stopping, true);
if (pd->vbus_extcon) {
devm_extcon_unregister_notifier(pd->dev, pd->vbus_extcon,
EXTCON_USB, &pd->vbus_nb);
pd->vbus_extcon = NULL;
}
if (pd->irqs_enabled) {
disable_irq(pd->irq);
disable_irq(pd->cc_irq);
pd->irqs_enabled = false;
}
cancel_delayed_work_sync(&pd->cc_work);
if (pd->port) {
tcpm_unregister_port(pd->port);
pd->port = NULL;
}
if (pd->vbus_on) {
regulator_disable(pd->vbus);
pd->vbus_on = false;
}
sc27xx_pd_disable_clk(pd);
}
static void sc27xx_put_role(void *data)
{
usb_role_switch_put(data);
}
static void sc27xx_put_charger(void *data)
{
power_supply_put(data);
}
static void sc27xx_put_connector(void *data)
{
fwnode_remove_software_node(data);
}
static int sc27xx_cc_cal(struct sc27xx_pd *pd, struct device_node *node)
{
const char *names[] = { "typec_cc1_cal", "typec_cc2_cal" };
const unsigned int shifts[] = { 1, 11 };
struct nvmem_cell *cell;
u32 trim = 0, raw;
void *bytes;
size_t length;
int i;
for (i = 0; i < ARRAY_SIZE(names); i++) {
cell = of_nvmem_cell_get(node, names[i]);
if (IS_ERR(cell))
return PTR_ERR(cell);
bytes = nvmem_cell_read(cell, &length);
nvmem_cell_put(cell);
if (IS_ERR(bytes))
return PTR_ERR(bytes);
if (length < 2) {
kfree(bytes);
return -EINVAL;
}
raw = ((u8 *)bytes)[0] | ((u8 *)bytes)[1] << 8;
kfree(bytes);
trim |= ((raw >> shifts[i]) & 31) << (i * 5);
}
return regmap_write(pd->regmap, pd->typec_base + 0x3c, trim);
}
static int sc27xx_probe(struct platform_device *pdev)
{
struct device *dev = &pdev->dev;
struct sc27xx_pd *pd;
struct device_node *typec, *usb, *gpio;
struct extcon_dev *extcon;
int ret;
/* Existing board power path is 5 V only. Do not import vendor PPS PDOs. */
u32 src[] = { PDO_FIXED(5000, 500, PDO_FIXED_DUAL_ROLE | PDO_FIXED_DATA_SWAP | PDO_FIXED_USB_COMM) };
u32 snk[] = { PDO_FIXED(5000, 2000, PDO_FIXED_DUAL_ROLE | PDO_FIXED_DATA_SWAP | PDO_FIXED_USB_COMM) };
const struct property_entry properties[] = {
PROPERTY_ENTRY_STRING("power-role", "dual"),
PROPERTY_ENTRY_STRING("data-role", "dual"),
PROPERTY_ENTRY_STRING("try-power-role", "sink"),
PROPERTY_ENTRY_U32_ARRAY("source-pdos", src),
PROPERTY_ENTRY_U32_ARRAY("sink-pdos", snk),
PROPERTY_ENTRY_U32("op-sink-microwatt", 10000000), {}
};
typec = of_get_compatible_child(dev->parent->of_node, "sprd,sc27xx-typec");
if (!typec)
return -ENODEV;
/* This path needs a real battery board with the PD-hub connector. */
if (!of_property_read_bool(typec, "use_pdhub_c2c")) {
of_node_put(typec);
return -ENODEV;
}
pd = devm_kzalloc(dev, sizeof(*pd), GFP_KERNEL);
if (!pd) {
of_node_put(typec);
return -ENOMEM;
}
pd->dev = dev;
pd->var_data = &ump9620_data;
pd->regmap = dev_get_regmap(dev->parent, NULL);
mutex_init(&pd->lock);
INIT_DELAYED_WORK(&pd->cc_work, sc27xx_cc_work);
ret = of_property_read_u32_index(dev->of_node, "reg", 0, &pd->base);
if (!ret)
ret = of_property_read_u32(typec, "reg", &pd->typec_base);
if (!ret)
ret = sc27xx_cc_cal(pd, typec);
pd->cc_irq = of_irq_get(typec, 0);
of_node_put(typec);
if (ret)
return ret;
if (pd->cc_irq < 0)
return pd->cc_irq;
pd->irq = platform_get_irq(pdev, 0);
if (pd->irq < 0)
return pd->irq;
pd->aon_apb = syscon_regmap_lookup_by_phandle(dev->of_node, "sprd,syscon-aon-apb");
if (IS_ERR(pd->aon_apb))
return PTR_ERR(pd->aon_apb);
pd->vbus = devm_regulator_get(dev, "vbus");
if (IS_ERR(pd->vbus))
return dev_err_probe(dev, PTR_ERR(pd->vbus), "OTG power regulator\n");
pd->charger = power_supply_get_by_name("bq256xx-charger");
if (!pd->charger)
return -EPROBE_DEFER;
ret = devm_add_action_or_reset(dev, sc27xx_put_charger, pd->charger);
if (ret)
return ret;
usb = of_find_compatible_node(NULL, NULL, "snps,sprd-dwc3");
if (!usb)
return -ENODEV;
pd->role_sw = usb_role_switch_find_by_fwnode(of_fwnode_handle(usb));
of_node_put(usb);
if (IS_ERR_OR_NULL(pd->role_sw))
return pd->role_sw ? PTR_ERR(pd->role_sw) : -EPROBE_DEFER;
ret = devm_add_action_or_reset(dev, sc27xx_put_role, pd->role_sw);
if (ret)
return ret;
ret = sc27xx_pd_cal(pd);
if (ret)
return dev_err_probe(dev, ret, "PD efuse calibration\n");
/* A software-node parent must itself be a software node, not an OF node. */
pd->connector = fwnode_create_software_node(properties, NULL);
if (IS_ERR(pd->connector))
return PTR_ERR(pd->connector);
ret = devm_add_action_or_reset(dev, sc27xx_put_connector, pd->connector);
if (ret)
return ret;
pd->tcpc = (struct tcpc_dev) {
.fwnode = pd->connector, .init = sc27xx_init,
.get_vbus = sc27xx_get_vbus, .get_cc = sc27xx_get_cc,
.set_cc = sc27xx_set_cc, .start_toggling = sc27xx_start_toggling,
.set_polarity = sc27xx_set_polarity, .set_vconn = sc27xx_set_vconn,
.set_vbus = sc27xx_set_vbus, .set_current_limit = sc27xx_set_current_limit,
.set_roles = sc27xx_set_roles, .set_pd_rx = sc27xx_set_rx,
.pd_transmit = sc27xx_transmit,
};
ret = devm_request_threaded_irq(dev, pd->irq, NULL, sc27xx_pd_irq,
IRQF_ONESHOT | IRQF_NO_AUTOEN, "ump9620-pd", pd);
if (ret)
goto put_node;
ret = devm_request_threaded_irq(dev, pd->cc_irq, NULL, sc27xx_cc_irq,
IRQF_ONESHOT | IRQF_NO_AUTOEN, "ump9620-cc", pd);
if (ret)
goto put_node;
/* VBUS may change without another CC attach during a PD power-role swap. */
gpio = of_find_compatible_node(NULL, NULL, "linux,extcon-usb-gpio");
if (gpio) {
extcon = extcon_find_edev_by_node(gpio);
of_node_put(gpio);
if (!IS_ERR(extcon)) {
pd->vbus_nb.notifier_call = sc27xx_vbus_event;
ret = devm_extcon_register_notifier(dev, extcon, EXTCON_USB, &pd->vbus_nb);
if (ret)
return ret;
pd->vbus_extcon = extcon;
}
}
/* Register TCPM last: its workers allocate devres after probe returns.
* Unregister in .remove before devres teardown, never as a devm action. */
pd->port = tcpm_register_port(dev, &pd->tcpc);
if (IS_ERR(pd->port)) {
ret = PTR_ERR(pd->port);
pd->port = NULL;
sc27xx_cleanup(pd);
return ret;
}
platform_set_drvdata(pdev, pd);
enable_irq(pd->irq);
enable_irq(pd->cc_irq);
pd->irqs_enabled = true;
mod_delayed_work(system_power_efficient_wq, &pd->cc_work, 0);
dev_info(dev, "Type-C/PD active: automatic USB roles, 5 V sink/source\n");
return 0;
put_node:
return ret;
}
static void sc27xx_shutdown(struct platform_device *pdev)
{
sc27xx_cleanup(platform_get_drvdata(pdev));
}
static const struct of_device_id sc27xx_ids[] = {
{ .compatible = "sprd,ump9620-pd" }, {}
};
MODULE_DEVICE_TABLE(of, sc27xx_ids);
static struct platform_driver sc27xx_driver = {
.probe = sc27xx_probe, .remove = sc27xx_shutdown,
.shutdown = sc27xx_shutdown,
.driver = { .name = "ump9620-tcpm", .of_match_table = sc27xx_ids },
};
module_platform_driver(sc27xx_driver);
MODULE_DESCRIPTION("UMP9620 Type-C/PD mainline TCPM controller");
MODULE_LICENSE("GPL");
+8
View File
@@ -21,6 +21,14 @@ def append_once(path, marker, text):
open(p, 'w').write(s.rstrip('\n') + '\n' + text)
append_once('drivers/clk/sprd/Makefile', 'reset.o', 'clk-sprd-y\t+= reset.o\n')
append_once('drivers/usb/typec/tcpm/Makefile', 'sc27xx-ump9620.o',
'obj-$(CONFIG_TYPEC_SC27XX_UMP9620) += sc27xx-ump9620.o\n')
append_once('drivers/usb/typec/tcpm/Kconfig', 'config TYPEC_SC27XX_UMP9620',
'\nconfig TYPEC_SC27XX_UMP9620\n'
'\ttristate "UMP9620 Type-C and PD controller"\n'
'\tdepends on TYPEC_TCPM && OF && MFD_SC27XX_PMIC\n'
'\tdepends on REGULATOR && POWER_SUPPLY && USB_ROLE_SWITCH && NVMEM\n'
'\thelp\n\t Autonomous Type-C and USB-PD with independent data/power roles.\n')
append_once('drivers/clk/sprd/Makefile', 'ums9620-clk.o', 'obj-$(CONFIG_SPRD_UMS9620_CLK)\t\t+= ums9620-clk.o\n')
kc = os.path.join(tree, 'drivers/clk/sprd/Kconfig')
s = open(kc).read()