feat: add U30 Air charger boot policy and selective modem startup

This commit is contained in:
kanoqwq committed 2026-10-19 16:12:17 +08:00
1 parent f0ed60ffac
commit 85d72fa95c
18 files changed
+604 -18

No files matched your search

@@ -0,0 +1,88 @@
# U30 Air 上电自启动与关机充电(2026-10-19)
## 行为与边界
网页“设备管理 → 充电管理”增加“上电自启动”,保存于
`mu300-charge.main.power_on`。默认关闭,与 E5 的开关语义一致:
- 关闭:LK 标记为 charger 的启动停在充电状态;电池灯沿用现有颜色、
呼吸和插拔延迟策略。长按电源键 1.5 秒继续启动;拔掉充电器,确认
断开持续 500 ms 后关机,不进入残缺的 OpenWrt。
- 开启:charger 启动直接继续进入 OpenWrt。
- 电源键产生的 normal 启动不等待;F50、V50 不进入此门控。
- 保留已保存的开关值。旧客户端只提交充电阈值时不覆盖上电自启动。
开关中英土三语言齐全。
只在 OpenWrt 的 `S09mu300-charge-mode` 启动路径等待,排序在
`S09mu300-vendor` 前。正常路径不加 sleep,不改 AT owner、握手、按卡
回放、射频开关或拨号顺序。关机充电时加载现有 IPC/PM 看门狗及温控模块,
推迟用户态 CP 加载、热点与网络初始化。没有关闭温控、休眠或降低硬件功能。
复用 `mu300-keys` 增加 `-c`,通过 poll 等待电源键和内核 kobject
power_supply 事件,没有周期查询、后台 SOC 定时器。只认支持 KEY_POWER
的输入设备,不响应 Wi-Fi 键;事件仅用来触发重新读取实际 online 节点。
收到 ENOBUFS 会重读供电状态;短暂断线有 500 ms 去抖。输入/供电硬件
不可用时明确记录错误并继续正常启动,避免无法开机。
拔线关机前同步文件系统,先只读重挂根文件系统、再重挂 userdata 镜像
的 backing mount,通过已有 next-boot rearm 保留用户启动选择,最后使用
内核 poweroff 路径,包含 FGU shutdown 保存。不会发 reboot,也不跳过 sync。
## “充电启动后无基带”的原厂依据
从连接的 U30 Air 导入目录只读取得本机原厂 `modem_control`。
该导入目录没有保留完整 build.prop,本次以实际文件 SHA-256 精确识别,
不把 E5 或 F50 的加载器当作 U30 Air 版本依据:
`43a3bc8c4730b87431d4fc8d90a3652b2458ef8bc9f59772685d4016cc7819a3`
反汇编确认:
- `0xc650` 的 modem_has_been_boot 先检查已运行的 PM 通道。
- `0xcf0c` 保存这个结果,随后与 `modem=shutdown` 条件合并。
PM 已在线不代表 NR/CH 已加载,但该结果会跳过初次加载。
- `0xcf50` 正常初次加载调用传入 63,包含 PM 和 CP/CH 的操作。
U30 专用 `mu300-modem-coldboot` 只在 charger+modem=shutdown、且 CP
的 stty_nr1 SBUF 尚未就绪时准备 RAM 私有副本。spipe_open 的驱动实现会
在 SBUF 不就绪时立即返回 ENODEV;`dd count=0` 仅开关文件,不读写 AT,
且执行时 AT owner 尚未启动。其他错误不会被当作“CP 离线”。
私有副本仅有两处已验证修改:
| 文件偏移 | 原指令 | 副本指令 | 目的 |
| --- | --- | --- | --- |
| 0xcf0c | mov w19,w0 | mov w19,wzr | 不用 PM 已启动推断 CP 已启动 |
| 0xcf50 | mov w0,63 | mov w0,34 | 仅 LOAD_CP / LOAD_CH,保留运行中的 PM |
副本最终 SHA-256 必须是:
`9e3490f222a312e649dd5273df216b87ca9880a621ea68a0a73df0aa6b37c2ae`
副本在 `/run/mu300/coldboot`,只绑定到 Android chroot 的独立 tmp 目录,
没有修改原可执行文件、Android 分区、固件或 NV。执行文件仍名为
modem_control,满足驱动的 task comm 检查。CP 已就绪、正常启动及其他
机型继续使用原始加载器。未知加载器明确拒绝此选择性加载,不尝试猜偏移。
## 验证及尚未验证的内容
- 97 项相关回归通过,包括充电门控、真实原厂文件副本校验、电源键短/长按、
其他实体按键隔离、U30 冷/热切卡及 LED 逻辑。
- 11 项真实 OpenWrt ucode 充电后端测试通过;中英土、亮暗色和窄屏/桌面
实际页面检查、14 项翻译回归通过。
- AArch64 静态按键程序编译通过,复用已有 WSL 交叉工具链;没有复制源码树。
打包检查会拒绝缺少 charger-event 功能的旧 mu300-keys 二进制。
- 已对当前 U30 Air 热部署,部署前复核模型与 eMMC 身份,原文件备份在
`/root/update-backups/u30air-charge-boot-20261019`。保留原充电阈值和暂停状态,
仅为缺失的 power_on 加入默认值。没有重启、断网或修改当前射频。
- 实机新 RPC 能读到 power_on=false,按键/内核事件监听正常阻塞,外部限时
结束后退出;正常启动路径选择原始 modem_control。这些只能证明接口可用。
- **尚未实测**:真正关机充电后拔线是否关机、长按是否启动并恢复基带、
长时间关机充电的 PM 看门狗握手,以及该私有加载副本的实际冷启动结果。
当前普通启动的成功不能替代这些物理条件验证。
## V50 用户改装卡槽说明
用户将两颗嵌入式 SIM 中的一颗改装成插槽。软件仍依据 board_id 和 GPIO
物理路由编号识别,不能根据运营商猜接线,也不能因为改装就给 board_id=3
凭空增加原厂 physical ID 3。此次没有增加运营商绑定或修改其他机型切卡。
+2 -1
View File
@@ -204,6 +204,7 @@ chmod 0755 $R/opt/mu300/bin/mu300-network-recovery $R/etc/init.d/mu300-network-r
chmod 0755 $R/etc/uci-defaults/92-mu300-uhttpd-key
chmod 0755 $R/opt/mu300/bin/v50-led-status
chmod 0755 $R/opt/mu300/bin/mu300-v50-sim
chmod 0755 $R/opt/mu300/bin/mu300-charge-mode $R/opt/mu300/bin/mu300-modem-coldboot $R/etc/init.d/mu300-charge-mode
chmod 0755 $R/opt/mu300/bin/openwrt-board-check
chmod 0755 $R/opt/mu300/bin/ra-deprecate $R/opt/mu300/bin/wcn-reopen
chmod 0755 $R/opt/mu300/bin/mu300-user-packages $R/etc/init.d/mu300-user-packages
@@ -287,7 +288,7 @@ unset root_hash
# enable the services (rc.common "enable" needs ubus, which is not running in the build container)
# accounts still those of the image until an installer or mu300-update puts the device ones in place
: > $R/etc/.mu300-accounts-from-image
for s in mu300-accounts mu300-cpu-driver mu300-vendor mu300-hw mu300-post mu300-toolkit mu300-atd mu300-network-recovery mu300-modem-log mu300-wifi-client mu300-buttons mu300-ndp mu300-smsd mu300-user-packages unisoc-battery ttyd; do
for s in mu300-accounts mu300-cpu-driver mu300-vendor mu300-charge-mode mu300-hw mu300-post mu300-toolkit mu300-atd mu300-network-recovery mu300-modem-log mu300-wifi-client mu300-buttons mu300-ndp mu300-smsd mu300-user-packages unisoc-battery ttyd; do
n=$(sed -n "s/^START=//p" $R/etc/init.d/$s)
ln -sf ../init.d/$s $R/etc/rc.d/S$n$s
done
@@ -4,7 +4,7 @@
'require mu300.common as M';
var get = rpc.declare({object:'mu300-charge', method:'get', expect:{'':{}}, nobatch:true});
var configure = rpc.declare({object:'mu300-charge', method:'configure', params:['enabled','start','stop'], expect:{'':{}}, nobatch:true});
var configure = rpc.declare({object:'mu300-charge', method:'configure', params:['enabled','start','stop','power_on'], expect:{'':{}}, nobatch:true});
var fullOnce = rpc.declare({object:'mu300-charge', method:'full_once', expect:{'':{}}, nobatch:true});
var pause = rpc.declare({object:'mu300-charge', method:'pause', expect:{'':{}}, nobatch:true});
@@ -47,6 +47,8 @@ return baseclass.extend({
<div class="mud-device-field"><label for="mud-charge-start">恢复充电于(20–95%)</label><input id="mud-charge-start" data-charge="start" type="number" min="20" max="95" step="1" required disabled></div>
</div>
<div class="mud-note">到达上限后暂停充电,降至下限时恢复。关闭上限会恢复正常充电。设置在重启后保留。</div>
<label class="mud-device-toggle"><input type="checkbox" data-charge="power_on" disabled>上电自启动</label>
<div class="mud-note">开启后,插入电源直接启动 OpenWrt;关闭后仅充电,长按电源键启动。设置在下次充电启动时生效。</div>
<div class="mud-device-actions"><button type="submit" class="mud-btn" data-charge="save" disabled>保存并应用</button><button type="button" class="mud-btn" data-charge="once" disabled>临时充满一次</button><button type="button" class="mud-btn" data-charge="pause" disabled>暂停电池充电</button></div>
<div class="mud-note">暂停电池充电时保留 USB 供电,不会关闭 USB 数据或 OTG。</div>
<div class="mud-note" data-charge="note" role="status" aria-live="polite">临时充满后,自动恢复原来的充电上限。</div>
@@ -56,7 +58,7 @@ return baseclass.extend({
var q = function(name) { return card.querySelector('[data-charge="' + name + '"]'); };
var state = {}, pending = false;
function disable() {
['enabled','start','stop','save','once','pause'].forEach(function(name) { q(name).disabled = pending || !state.available; });
['enabled','start','stop','power_on','save','once','pause'].forEach(function(name) { q(name).disabled = pending || !state.available; });
q('once').disabled = pending || !state.available || !!state.full_once;
q('refresh').disabled = pending;
}
@@ -69,6 +71,7 @@ return baseclass.extend({
q('status').textContent = M.translate(label);
q('pause').textContent = M.translate(s.paused ? '恢复自动充电' : '暂停电池充电');
q('enabled').checked = !!s.enabled;
q('power_on').checked = !!s.power_on;
q('start').value = s.start == null ? 70 : s.start;
q('stop').value = s.stop == null ? 80 : s.stop;
q('once').textContent = M.translate(s.full_once ? '正在临时充满…' : '临时充满一次');
@@ -95,7 +98,7 @@ return baseclass.extend({
if (pending || !state.available || !q('form').reportValidity()) return;
var start = Number(q('start').value), stop = Number(q('stop').value);
if (start >= stop) { q('note').textContent = message('charge_threshold_order'); return; }
return perform(function() { return configure(q('enabled').checked ? '1' : '0', String(start), String(stop)); }, true);
return perform(function() { return configure(q('enabled').checked ? '1' : '0', String(start), String(stop), q('power_on').checked ? '1' : '0'); }, true);
};
q('once').onclick = function() { if (state.available && !state.full_once) return perform(fullOnce, true); };
q('pause').onclick = function() { if (state.available) return perform(state.paused ? resume : pause, true); };
@@ -154,6 +154,8 @@ var DASH_I18N = {
"已暂停电池充电": ["Battery charging paused","Pil şarjı duraklatıldı"],
"恢复自动充电": ["Resume automatic charging","Otomatik şarja dön"],
"充电设置已应用,重启后保留": ["Charging settings applied and saved across reboots","Şarj ayarları uygulandı ve yeniden başlatma için kaydedildi"],
"上电自启动": ["Start automatically when power is connected","Güç bağlandığında otomatik başlat"],
"开启后,插入电源直接启动 OpenWrt;关闭后仅充电,长按电源键启动。设置在下次充电启动时生效。": ["When enabled, connecting power starts OpenWrt. When disabled, charge only; hold the power button to start. Applies on the next charger boot.","Etkinse güç bağlandığında OpenWrt başlar. Kapalıysa yalnızca şarj olur; başlatmak için güç düğmesini basılı tutun. Bir sonraki şarj açılışında uygulanır."],
"充电设置已保存,但驱动应用失败,请重试": ["Settings saved, but the charger rejected the change; retry","Ayarlar kaydedildi ancak şarj sürücüsü değişikliği uygulayamadı; yeniden deneyin"],
"充电状态保存失败,请重试": ["Unable to save charging state; retry","Şarj durumu kaydedilemedi; yeniden deneyin"],
'切换': ['Switch', 'Geçiş yap'],
@@ -4,3 +4,4 @@ config charge 'main'
option stop '80'
option paused '0'
option full_once '0'
option power_on '0'
@@ -1,7 +1,7 @@
#!/bin/sh
case "$1:$2" in
list:)
echo '{"get":{},"configure":{"enabled":"","start":"","stop":""},"full_once":{},"pause":{},"resume":{}}'
echo '{"get":{},"configure":{"enabled":"","start":"","stop":"","power_on":""},"full_once":{},"pause":{},"resume":{}}'
;;
call:get|call:configure|call:full_once|call:pause|call:resume)
exec /usr/libexec/unisoc-modem/charge "$2"
@@ -20,6 +20,7 @@ function settings() {
return { enabled: integer(cfg.get(PKG, 'main', 'enabled') || '0', 0, 1),
start: integer(cfg.get(PKG, 'main', 'start') || '70', 20, 95),
stop: integer(cfg.get(PKG, 'main', 'stop') || '80', 50, 100),
power_on: integer(cfg.get(PKG, 'main', 'power_on') ?? '0', 0, 1),
paused: integer(cfg.get(PKG, 'main', 'paused') || '0', 0, 1),
full_once: integer(cfg.get(PKG, 'main', 'full_once') || '0', 0, 1) };
}
@@ -45,7 +46,7 @@ function snapshot(c) {
return { ok: true, supported: supported(), available: valid, capacity: cap,
current_ma: match(current, /^-?[0-9]+$/) ? int(current) / 1000 : null,
status: valid ? read(CHG + '/status') : '', online: valid && read(CHG + '/online') == '1',
enabled: !!c.enabled, start: c.start, stop: c.stop, full_once: !!c.full_once,
enabled: !!c.enabled, start: c.start, stop: c.stop, power_on: !!c.power_on, full_once: !!c.full_once,
paused: !!c.paused, stopped: !!old.stopped, reason: old.reason || '', pending: !!old.pending };
}
function remember(state) {
@@ -101,7 +102,9 @@ try {
if (action == 'configure') {
let data = json(fs.readfile('/dev/stdin') || '{}');
let next = {enabled: integer(data?.enabled, 0, 1), start: integer(data?.start, 20, 95),
stop: integer(data?.stop, 50, 100), paused: 0, full_once: 0};
stop: integer(data?.stop, 50, 100), power_on: c.power_on, paused: 0, full_once: 0};
if (data?.power_on != null && data.power_on != '')
next.power_on = integer(data.power_on, 0, 1);
if (next.start >= next.stop) die('charge_threshold_order');
store(next); c = next;
} else if (action == 'pause' || action == 'resume') {
+5
View File
@@ -0,0 +1,5 @@
#!/bin/sh /etc/rc.common
# Sorts before S09mu300-vendor, then S12 hardware and network/AT startup.
START=09
boot() { /opt/mu300/bin/mu300-charge-mode; }
start() { return 0; }
@@ -61,9 +61,16 @@ else
tr -d '\000' < $src | sed 's/androidboot.slot_suffix=_b/androidboot.slot_suffix=_a/' > /run/mu300-cmdline.android
fi
mount --bind /run/mu300-cmdline.android $A/proc/cmdline
# A charger-started U30 has live PM but can still have NR/CH offline. The stock
# predicate otherwise skips CP loading. Keep the original loader on all normal
# boots/models; do not change the command line, NV, AT handshake or RF replay.
modem_exe=/vendor/bin/modem_control
if [ -x /opt/mu300/bin/mu300-modem-coldboot ]; then
modem_exe=$(/opt/mu300/bin/mu300-modem-coldboot "$A" /run/mu300-cmdline.android) || exit 5
fi
# sprd_modem_loader only accepts a task whose comm is exactly "modem_control": exec it directly
# OpenWrt's procd preloads /lib/libsetlbf.so into services; the bionic linker in the chroot cannot load it
unset LD_PRELOAD
export LD_LIBRARY_PATH=/apex/com.android.runtime/lib64/bionic:/system/lib64:/vendor/lib64
mark vendor-chroot-ready
exec chroot $A /vendor/bin/modem_control
exec chroot $A "$modem_exe"
+47
View File
@@ -0,0 +1,47 @@
#!/bin/sh
# U30 Air's LK charger boot only. Default to charging; explicit automatic start
# skips the gate. No wait is added to power-key/normal boots or other models.
export PATH="$PATH:/opt/mu300/bin:/opt/mu300/busybox-bin:/usr/sbin:/sbin"
BIN=${MU300_BIN:-/opt/mu300/bin}
R=${MU300_SYSROOT:-}
[ "$("$BIN/mu300-device")" = u30air ] || exit 0
case $(uci -q get mu300-charge.main.power_on) in
0|'') ;; # Old configurations use the same charge-only default as E5.
*) exit 0 ;;
esac
[ ! -e "$R/tmp/.failsafe" ] || exit 0
args=$(cat "$R/proc/cmdline" 2>/dev/null; tr '\000' ' ' < "$R/proc/device-tree/chosen/bootargs" 2>/dev/null)
printf '%s\n' "$args" | grep -Eq '(^|[[:space:]])(sprdboot|androidboot)\.mode=charger([[:space:]]|$)' || exit 0
# LK already runs PM during charging. Load its IPC/watchdog and the thermal
# drivers; defer the vendor CP loader, Wi-Fi, netifd and RF AT until power-on.
"$BIN/extra-modules" > "$R/tmp/mu300-charge-modules.log" 2>&1
mkdir -p "$R/run/mu300"
touch "$R/run/mu300/charging-boot"
"$BIN/mu300-led" battery
logger -t mu300-charge-mode 'charging only; hold power for 1.5 seconds to start OpenWrt'
"$BIN/mu300-keys" -c -l 1500
result=$?
if [ "$result" != 3 ]; then
# An unavailable input or supply must never trap the device in charging.
[ "$result" = 0 ] || logger -t mu300-charge-mode 'charger wait unavailable; continuing normal boot'
rm -f "$R/run/mu300/charging-boot"
exit 0
fi
logger -t mu300-charge-mode 'charger removed; powering off'
"$BIN/mu300-led" sleep
"$BIN/mu300-next-boot" --rearm || logger -t mu300-charge-mode 'could not rearm boot choice'
sync
# rcS waits here, so poweroff via procd cannot complete its rc shutdown. Flush
# root before the image backing mount, then use the kernel's poweroff path,
# including FGU shutdown accounting. Never reboot or skip sync with -n.
mount -o remount,ro / || logger -t mu300-charge-mode 'root remount read-only failed'
if mountpoint -q /mnt/mu300-disk; then
mount -o remount,ro /mnt/mu300-disk || logger -t mu300-charge-mode 'backing mount remount failed'
fi
sync
while :; do
poweroff -f
logger -t mu300-charge-mode 'poweroff returned; retrying'
sleep 1
done
+49
View File
@@ -0,0 +1,49 @@
#!/bin/sh
# Stock U30 Air charger boot: PM is alive, NR/CH were not loaded by LK.
# Only a verified RAM copy loads CP|CH (34), leaving PM untouched. No AT or NV.
set -eu
export PATH="$PATH:/opt/mu300/busybox-bin"
BIN=${MU300_BIN:-/opt/mu300/bin}
R=${MU300_SYSROOT:-}
A=${1:?Android root required}
args=${2:?vendor command line required}
original=/vendor/bin/modem_control
normal() { echo "$original"; exit 0; }
[ "$("$BIN/mu300-device")" = u30air ] || normal
grep -Eq '(^|[[:space:]])(sprdboot|androidboot)\.mode=charger([[:space:]]|$)' "$args" || normal
grep -Eq '(^|[[:space:]])modem=shutdown([[:space:]]|$)' "$args" || {
echo 'unexpected charger modem state; refusing selective load' >&2; exit 1;
}
# spipe_open() immediately returns ENODEV if its SBUF is not ready, regardless
# of O_NONBLOCK. count=0 opens/closes but does not read/write the AT channel.
# This runs before the AT owners; never use it as a runtime recovery probe.
if probe=$(LC_ALL=C dd if="$R/dev/stty_nr1" of=/dev/null count=0 2>&1); then
normal
fi
case "$probe" in
*'No such device'*|*'No such file or directory'*) ;;
*) echo "cannot establish CP offline: $probe" >&2; exit 1 ;;
esac
source=$A/vendor/bin/modem_control
expected=43a3bc8c4730b87431d4fc8d90a3652b2458ef8bc9f59772685d4016cc7819a3
patched=9e3490f222a312e649dd5273df216b87ca9880a621ea68a0a73df0aa6b37c2ae
hash=$(sha256sum "$source")
[ "${hash%% *}" = "$expected" ] || { echo "unsupported U30 Air modem_control: ${hash%% *}" >&2; exit 1; }
stage=$R/run/mu300/coldboot
target=$A/tmp/mu300-coldboot
[ ! -L "$stage" ] && [ ! -L "$target" ] || exit 1
mkdir -p "$stage" "$target"
chmod 0755 "$stage" "$target"
temp=$(mktemp "$stage/.loader.XXXXXX")
trap 'rm -f "$temp"' EXIT HUP INT TERM
cp "$source" "$temp"
# VA=file offset: 0xcf0c mov w19,w0 -> mov w19,wzr; ignore PM-only boot predicate.
# 0xcf50 mov w0,63 -> mov w0,34; LOAD_CP|LOAD_CH, without stop/load PM bits.
printf '\363\003\037\052' | dd of="$temp" bs=1 seek=53004 count=4 conv=notrunc 2>/dev/null
printf '\100\004\200\122' | dd of="$temp" bs=1 seek=53072 count=4 conv=notrunc 2>/dev/null
hash=$(sha256sum "$temp")
[ "${hash%% *}" = "$patched" ] || { echo 'selective loader verification failed' >&2; exit 1; }
chmod 0755 "$temp"
mv "$temp" "$stage/modem_control"
mountpoint -q "$target" || mount --bind "$stage" "$target"
echo /tmp/mu300-coldboot/modem_control
+7 -3
View File
@@ -8,7 +8,7 @@ const common = fs.readFileSync(path.join(dir, 'mu300/common.js'), 'utf8');
const catalog = new Function(common.slice(common.indexOf('var DASH_I18N = {'),
common.indexOf('var DASH_KEYS = ')) + 'return DASH_I18N;')();
const state = () => ({ok:true, available:true, supported:true, capacity:76, status:'Charging', online:true,
enabled:true, start:70, stop:80, full_once:false});
enabled:true, start:70, stop:80, power_on:true, full_once:false});
function fixture() {
const elements = {}, calls = [], replies = [state()];
const card = {style:{}, querySelector(selector) {
@@ -42,13 +42,16 @@ const submit = f => f.elements.form.onsubmit({preventDefault(){}});
assert.equal(f.elements.capacity.textContent,'76%');
assert.equal(f.elements.start.value,70);
assert.equal(f.elements.save.disabled,false);
assert.equal(f.elements.power_on.checked,true);
f.elements.start.value='85'; f.elements.stop.value='80';
submit(f); assert.equal(f.calls.length,1);
assert.match(f.elements.note.textContent,/恢复充电阈值/);
f.elements.start.value='65'; f.elements.stop.value='85';
f.replies.push({...state(),start:65,stop:85});
f.elements.power_on.checked=false;
f.replies.push({...state(),start:65,stop:85,power_on:false});
await submit(f);
assert.deepEqual(f.calls.at(-1),['configure','1','65','85']);
assert.deepEqual(f.calls.at(-1),['configure','1','65','85','0']);
assert.equal(f.elements.power_on.checked,false);
f.replies.push({...state(),full_once:true});
await f.elements.once.onclick();
assert.equal(f.elements.once.disabled,true);
@@ -69,6 +72,7 @@ const submit = f => f.elements.form.onsubmit({preventDefault(){}});
await submit(f); assert.match(f.elements.note.textContent,/已保存.*应用失败/);
const down = fixture(); down.replies[0]={ok:true,available:false};
await down.module.mount(down.root); assert.equal(down.elements.save.disabled,true);
assert.equal(down.elements.power_on.disabled,true);
assert.equal(down.root.card.hidden,true);
submit(down); assert.equal(down.calls.length,1);
const failed = fixture(); failed.replies[0]=new Error('connection');
+3 -3
View File
@@ -23,11 +23,11 @@ with sync_playwright() as p:
document.body.style.cssText='font-family:sans-serif;margin:16px';
window.saved=[];
window.chargeState={ok:true,available:true,supported:true,capacity:76,status:'Charging',online:true,
start:70,stop:80,enabled:true,full_once:false};
start:70,stop:80,enabled:true,power_on:true,full_once:false};
const rpc={declare:info=>(...args)=>{
if(info.object==='mu300-charge') {
if(info.method==='configure'){
saved.push(args);Object.assign(chargeState,{enabled:args[0]==='1',start:+args[1],stop:+args[2]});
saved.push(args);Object.assign(chargeState,{enabled:args[0]==='1',start:+args[1],stop:+args[2],power_on:args[3]==='1'});
}
if(info.method==='full_once')chargeState.full_once=true;
if(info.method==='pause')chargeState.paused=true;
@@ -50,7 +50,7 @@ with sync_playwright() as p:
page.locator('#mud-charge-start').fill('60')
save.click()
page.wait_for_function('saved.length===1')
assert page.evaluate('saved') == [['1','60','90']]
assert page.evaluate('saved') == [['1','60','90','1']]
page.locator('[data-charge="once"]').click()
page.wait_for_function('document.querySelector(\'[data-charge="once"]\').disabled')
assert page.locator('[data-charge="capacity"]').inner_text() == '76%'
+142
View File
@@ -0,0 +1,142 @@
"""Execute the boot gate with safe command stubs; no disks or devices touched."""
from helpers import BIN, TOP, ShellTest
import hashlib
import os
from pathlib import Path
import shutil
class ChargeBoot(ShellTest):
def setUp(self):
super().setUp()
self.root=self.tmp/'root'
for p in ('proc/device-tree/chosen', 'run/mu300', 'tmp'):
(self.root/p).mkdir(parents=True,exist_ok=True)
(self.root/'proc/cmdline').write_text('console=ttyS1\n')
self.args=self.root/'proc/device-tree/chosen/bootargs'
self.args.write_bytes(b'androidboot.mode=charger\0')
for name in ('mu300-led','extra-modules','logger','mount','sync','mu300-next-boot'):
self.stub(name, 'echo "'+name+' $*" >> "$STUBLOG/calls"')
self.stub('mu300-device','echo "${TEST_MODEL:-u30air}"')
self.stub('uci','echo "${TEST_POWER_ON-0}"')
self.stub('mu300-keys','echo "keys $*" >> "$STUBLOG/calls"; exit "${TEST_KEYS:-0}"')
self.stub('mountpoint','exit 0')
self.stub('poweroff','echo "poweroff $*" >> "$STUBLOG/calls"; kill -TERM "$PPID"')
def call(self,shell,**env):
(self.tmp/'calls').unlink(missing_ok=True)
return self.script(shell,BIN/'mu300-charge-mode',MU300_BIN=self.stubs,MU300_SYSROOT=self.root,**env)
def calls(self):
path=self.tmp/'calls'
return path.read_text() if path.exists() else ''
def test_only_explicit_u30air_charger_opt_out_waits(self):
for shell in self.each_shell():
for model in ('f50','v50','unknown'):
self.assertEqual(self.call(shell,TEST_MODEL=model).returncode,0)
self.assertEqual(self.calls(),'')
for enabled in ('1', 'invalid'):
self.assertEqual(self.call(shell,TEST_POWER_ON=enabled).returncode,0)
self.assertEqual(self.calls(),'')
self.args.write_bytes(b'androidboot.mode=normal\0')
self.assertEqual(self.call(shell).returncode,0)
self.assertEqual(self.calls(),'')
self.args.write_bytes(b'androidboot.mode=charger\0')
def test_power_key_and_input_failure_resume_without_radio_commands(self):
for shell in self.each_shell():
for result in ('0','1','2'):
self.assertEqual(self.call(shell,TEST_KEYS=result).returncode,0)
calls=self.calls()
self.assertIn('keys -c -l 1500',calls)
self.assertNotIn('poweroff',calls)
self.assertNotIn('AT+',calls)
self.assertFalse((self.root/'run/mu300/charging-boot').exists())
def test_unplug_syncs_root_before_backing_mount_and_powers_off(self):
for shell in self.each_shell():
# Some BusyBox builds prefer their own poweroff/mount applets to
# PATH stubs. Never exercise shutdown stubs under standalone ash.
if Path(shell[0]).name == 'busybox':
continue
result=self.call(shell,TEST_KEYS='3')
self.assertNotEqual(result.returncode,0) # Stub terminates the wait, no actual shutdown.
calls=self.calls()
self.assertIn('mu300-next-boot --rearm',calls)
self.assertLess(calls.index('mount -o remount,ro /\n'),calls.index('mount -o remount,ro /mnt/mu300-disk'))
self.assertIn('poweroff -f',calls)
self.assertNotIn('reboot',calls)
def test_boot_order_and_enablement(self):
init=(TOP/'openwrt/overlay/etc/init.d/mu300-charge-mode').read_text()
self.assertIn('START=09',init)
self.assertIn('mu300-vendor mu300-charge-mode mu300-hw',(TOP/'openwrt/build-rootfs.sh').read_text())
(self.root/'tmp/.failsafe').touch()
for shell in self.each_shell():
self.assertEqual(self.call(shell).returncode,0)
self.assertEqual(self.calls(),'')
class ColdModem(ShellTest):
def setUp(self):
super().setUp()
self.shells=[s for s in self.shells if Path(s[0]).name != 'busybox']
self.root=self.tmp/'root';(self.root/'dev').mkdir(parents=True)
self.android=self.tmp/'android';(self.android/'vendor/bin').mkdir(parents=True)
self.loader=self.android/'vendor/bin/modem_control'
self.loader.write_bytes(b'unknown stock firmware')
self.args=self.tmp/'args'
self.args.write_text('androidboot.mode=charger modem=shutdown\n')
self.stub('mu300-device','echo "${TEST_MODEL:-u30air}"')
self.stub('mountpoint','exit 1')
self.stub('mount','echo "mount $*" >> "$STUBLOG/calls"')
def call(self,shell,**env):
return self.script(shell,BIN/'mu300-modem-coldboot',self.android,self.args,
MU300_SYSROOT=self.root,MU300_BIN=self.stubs,**env)
def test_other_boards_and_normal_boot_do_not_probe_or_patch(self):
for shell in self.each_shell():
for model in ('f50','v50'):
result=self.call(shell,TEST_MODEL=model)
self.assertEqual(result.returncode,0,result.stderr)
self.assertEqual(result.stdout.strip(),'/vendor/bin/modem_control')
self.args.write_text('androidboot.mode=normal modem=shutdown\n')
self.assertEqual(self.call(shell).stdout.strip(),'/vendor/bin/modem_control')
self.assertFalse((self.root/'run').exists())
self.args.write_text('androidboot.mode=charger modem=shutdown\n')
def test_live_cp_uses_original_loader_without_byte_io(self):
(self.root/'dev/stty_nr1').write_bytes(b'untouched AT bytes')
for shell in self.each_shell():
result=self.call(shell)
self.assertEqual(result.returncode,0,result.stderr)
self.assertEqual(result.stdout.strip(),'/vendor/bin/modem_control')
self.assertEqual((self.root/'dev/stty_nr1').read_bytes(),b'untouched AT bytes')
self.assertFalse((self.root/'run').exists())
def test_unknown_binary_and_ambiguous_cp_state_rejected(self):
for shell in self.each_shell():
result=self.call(shell)
self.assertNotEqual(result.returncode,0)
self.assertIn('unsupported U30 Air',result.stderr)
self.assertEqual(self.loader.read_bytes(),b'unknown stock firmware')
self.args.write_text('androidboot.mode=charger modem=booting\n')
self.assertNotEqual(self.call(shell).returncode,0)
self.args.write_text('androidboot.mode=charger modem=shutdown\n')
def test_real_recipient_loader_patched_only_in_ram(self):
source=os.environ.get('MU300_COLD_LOADER_TEST_FILE')
if not source:self.skipTest('actual stock U30 Air loader is not distributed in the repository')
shutil.copyfile(source,self.loader)
original=self.loader.read_bytes()
for shell in self.each_shell():
result=self.call(shell)
self.assertEqual(result.returncode,0,result.stderr)
self.assertEqual(result.stdout.strip(),'/tmp/mu300-coldboot/modem_control')
patched=(self.root/'run/mu300/coldboot/modem_control').read_bytes()
self.assertEqual(hashlib.sha256(patched).hexdigest(),'9e3490f222a312e649dd5273df216b87ca9880a621ea68a0a73df0aa6b37c2ae')
self.assertEqual(patched[0xcf0c:0xcf10],bytes.fromhex('f3031f2a'))
self.assertEqual(patched[0xcf50:0xcf54],bytes.fromhex('40048052'))
self.assertEqual(self.loader.read_bytes(),original)
+18
View File
@@ -87,6 +87,18 @@ class ChargeControl(unittest.TestCase):
self.assertEqual((self.charger/'charge_type').read_text(),'Fast')
self.assertTrue(self.call()['enabled'])
def test_power_on_persisted_optional_for_older_clients(self):
self.assertFalse(self.call()['power_on'])
self.assertFalse(self.configure(power_on='0')['power_on'])
self.assertFalse(self.call()['power_on'])
# Existing callers that only change thresholds preserve the boot choice.
self.assertFalse(self.configure()['power_on'])
self.assertTrue(self.configure(power_on='1')['power_on'])
for board in ('f50', 'v50', 'unknown'):
before=(self.config/'mu300-charge').read_bytes()
self.assertFalse(self.call('configure',dict(enabled='0',start='70',stop='80',power_on='0'),board=board)['ok'])
self.assertEqual((self.config/'mu300-charge').read_bytes(),before)
def test_manual_pause_resume_and_boot_apply(self):
self.assertTrue(self.call('pause')['paused'])
(self.fixture/'state.json').unlink()
@@ -122,6 +134,12 @@ class ChargeControl(unittest.TestCase):
self.assertEqual((self.config/'mu300-charge').read_bytes(),initial)
self.assertEqual((self.charger/'charge_type').read_text().strip(),'Fast')
def test_invalid_power_on_leaves_settings_untouched(self):
before=(self.config/'mu300-charge').read_bytes()
for value in ('2', '-1', '1;reboot', True):
self.assertFalse(self.configure(power_on=value)['ok'])
self.assertEqual((self.config/'mu300-charge').read_bytes(),before)
def test_otg_source_keeps_pause_until_power_sink_returns(self):
self.call('pause')
self.write(self.charger/'usb_type','SDP [ACA]')
+76
View File
@@ -0,0 +1,76 @@
"""Native tests of the production charger event wait using pipes, never evdev."""
from pathlib import Path
import os
import shutil
import subprocess
import tempfile
import unittest
TOP=Path(__file__).resolve().parents[1]
@unittest.skipUnless(os.name=='posix' and shutil.which('gcc'), 'native POSIX gcc required')
class ChargerKeys(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.temp=tempfile.TemporaryDirectory(prefix='charge-keys-')
cls.path=Path(cls.temp.name)
cls.addClassCleanup(cls.temp.cleanup)
source=cls.path/'test.c'
source.write_text(r'''
#define main keys_program
#include "mu300-keys.c"
#undef main
#include <signal.h>
#include <sys/wait.h>
static void key(int fd, int code, int value) {
struct input_event e={.type=EV_KEY,.code=code,.value=value};
if(write(fd,&e,sizeof(e))!=sizeof(e)) _exit(9);
}
int main(int argc, char **argv) {
(void)argc;
char event[]="change@/devices/test\0SUBSYSTEM=power_supply\0ONLINE=0\0";
if(!charge_event(event,sizeof(event)) || charge_event("SUBSYSTEM=power_supply",22) ||
charge_event("SUBSYSTEM=usb\0",14)) return 9;
int p[2];if(pipe(p)) return 9;
pid_t child=fork();if(child<0) return 9;
if(!child) {
usleep(20000);
if(!strcmp(argv[2],"short")) {
key(p[1],KEY_POWER,1);usleep(20000);key(p[1],KEY_POWER,0);
usleep(140000);key(p[1],KEY_POWER,1);
} else if(!strcmp(argv[2],"other")) {
key(p[1],KEY_HELP,1);usleep(180000);key(p[1],KEY_POWER,1);
} else if(!strcmp(argv[2],"power")) key(p[1],KEY_POWER,1);
sleep(3);_exit(0);
}
struct pollfd fd={.fd=p[0],.events=POLLIN};
int result=charge_wait(&fd,1,-1,argv[1],80);
kill(child,SIGTERM);waitpid(child,NULL,0);close(p[0]);close(p[1]);
return result;
}
''')
cls.binary=cls.path/'test'
subprocess.run(['gcc','-Wall','-Wextra','-Werror','-O2','-I',str(TOP/'tools/keys'),
str(source),'-o',str(cls.binary)],check=True,capture_output=True)
def wait(self,value,mode):
path=self.path/'online';path.write_text(value)
import time
start=time.monotonic()
r=subprocess.run([str(self.binary),str(path),mode],timeout=2)
return r.returncode,time.monotonic()-start
def test_long_power_starts(self):
code,elapsed=self.wait('1\n','power')
self.assertEqual(code,0);self.assertLess(elapsed,1)
def test_short_power_and_wifi_key_do_not_start(self):
for mode in ('short','other'):
code,elapsed=self.wait('1\n',mode)
self.assertEqual(code,0);self.assertGreater(elapsed,.23)
def test_unplug_debounced_and_invalid_supply_fails_open(self):
code,elapsed=self.wait('0\n','idle')
self.assertEqual(code,3);self.assertGreaterEqual(elapsed,.49)
self.assertEqual(self.wait('invalid\n','idle')[0],1)
+4
View File
@@ -46,6 +46,9 @@ done
file "$IN/tools/keys/mu300-keys" | grep -q 'ELF 64-bit.*ARM aarch64' || {
echo "mu300-keys must be an AArch64 executable" >&2; exit 1;
}
grep -aq 'bq256xx-charger/online' "$IN/tools/keys/mu300-keys" || {
echo 'mu300-keys is stale: rebuild tools/keys/mu300-keys.c with charger-event support' >&2; exit 1;
}
for f in wcn_bsp.ko sprd_wlan_combo.ko sprdbt_tty.ko mali_kbase.ko; do
[ -s "$IN/out/modules/$f" ] || { echo "missing $IN/out/modules/$f" >&2; exit 1; }
done
@@ -106,6 +109,7 @@ for f in ./lib/netifd/proto/mu300cell.sh ./lib/netifd/proto/mu300cell-v6.sh \
./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-v50-sim ./opt/mu300/lib/v50-card.sh ./opt/mu300/lib/network-led.sh \
./opt/mu300/bin/mu300-charge-mode ./opt/mu300/bin/mu300-modem-coldboot ./etc/rc.d/S09mu300-charge-mode \
./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 \
./lib/netifd/hostapd-unisoc.sh ./usr/share/ucode/wifi/unisoc-sae.uc \
+140 -4
View File
@@ -15,11 +15,13 @@
#include <errno.h>
#include <fcntl.h>
#include <linux/input.h>
#include <linux/netlink.h>
#include <poll.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <time.h>
#include <unistd.h>
@@ -41,21 +43,137 @@ static int has_keys(int fd)
return (ev >> EV_KEY) & 1;
}
/* Charger-only boot: wait on input and kernel power-supply events, without a
* periodic SOC/USB poll. Return 0 for power-on, 3 for unplug, 1 on unavailable
* hardware (the caller continues normal boot rather than trapping the user). */
static int charge_online(const char *path)
{
char value[8];
int fd = open(path, O_RDONLY | O_CLOEXEC);
if (fd < 0)
return -1;
ssize_t n = read(fd, value, sizeof(value));
close(fd);
if (n < 1 || (value[0] != '0' && value[0] != '1') ||
(n > 1 && value[1] != '\n'))
return -1;
return value[0] - '0';
}
static int charge_event(const char *buf, size_t size)
{
for (size_t i = 0; i < size;) {
size_t n = strnlen(buf + i, size - i);
if (n == size - i)
return 0;
if (!strcmp(buf + i, "SUBSYSTEM=power_supply"))
return 1;
i += n + 1;
}
return 0;
}
static int charge_wait(struct pollfd *keys, int n, int events,
const char *online_path, long long hold)
{
struct pollfd fds[MAXDEV + 1];
long long down[MAXDEV] = {0}, unplug = 0;
memcpy(fds, keys, n * sizeof(*keys));
fds[n] = (struct pollfd){ .fd = events, .events = POLLIN };
for (int i = 0; i < n; i++) {
unsigned long bits[KEY_MAX / (8 * sizeof(unsigned long)) + 1] = {0};
if (ioctl(fds[i].fd, EVIOCGKEY(sizeof(bits)), bits) >= 0 &&
(bits[KEY_POWER / (8 * sizeof(unsigned long))] >>
(KEY_POWER % (8 * sizeof(unsigned long))) & 1))
down[i] = now_ms();
}
int changed = 1;
for (;;) {
long long now = now_ms();
if (changed || unplug) {
int online = charge_online(online_path);
if (online < 0)
return 1;
if (online)
unplug = 0;
else if (!unplug)
unplug = now;
else if (now - unplug >= 500)
return 3;
changed = 0;
}
long long timeout = unplug ? unplug + 500 - now : -1;
for (int i = 0; i < n; i++) {
if (!down[i])
continue;
long long left = down[i] + hold - now;
if (left <= 0)
return 0;
if (timeout < 0 || left < timeout)
timeout = left;
}
if (poll(fds, n + 1, timeout) < 0) {
if (errno == EINTR)
continue;
return 1;
}
for (int i = 0; i < n; i++)
if (fds[i].revents & (POLLERR | POLLHUP | POLLNVAL))
return 1;
if (fds[n].revents & (POLLHUP | POLLNVAL))
return 1;
if (fds[n].revents & (POLLIN | POLLERR)) {
char buf[8192];
struct sockaddr_nl sender = {0};
socklen_t len = sizeof(sender);
ssize_t size = recvfrom(events, buf, sizeof(buf), MSG_DONTWAIT,
(struct sockaddr *)&sender, &len);
if (size < 0 && errno == ENOBUFS) {
changed = 1; /* lost notification: read the actual supply again */
continue;
}
if (size < 0 && errno != EINTR && errno != EAGAIN)
return 1;
if (size > 0 && sender.nl_family == AF_NETLINK && !sender.nl_pid &&
charge_event(buf, size))
changed = 1;
}
for (int i = 0; i < n; i++) {
if (!(fds[i].revents & POLLIN))
continue;
struct input_event ev[16];
ssize_t size = read(fds[i].fd, ev, sizeof(ev));
if (size <= 0 || size % sizeof(ev[0]))
return 1;
for (int j = 0; j < size / (ssize_t)sizeof(ev[0]); j++) {
if (ev[j].type != EV_KEY || ev[j].code != KEY_POWER)
continue;
if (ev[j].value == 1)
down[i] = now_ms();
else if (ev[j].value == 0)
down[i] = 0;
}
}
}
}
int main(int argc, char **argv)
{
long long hold = 3000, tick = 0, next_tick = 0;
static long long down[MAXKEY + 1]; /* press time, 0: not held */
static char reported[MAXKEY + 1]; /* "long" already printed for this press */
struct pollfd pfd[MAXDEV];
int n = 0, opt;
int n = 0, opt, charging = 0;
while ((opt = getopt(argc, argv, "l:t:")) != -1) {
if (opt == 'l')
while ((opt = getopt(argc, argv, "cl:t:")) != -1) {
if (opt == 'c')
charging = 1;
else if (opt == 'l')
hold = atoll(optarg);
else if (opt == 't')
tick = atoll(optarg) * 1000;
else {
fprintf(stderr, "usage: mu300-keys [-l MS] [-t SEC]\n");
fprintf(stderr, "usage: mu300-keys [-c] [-l MS] [-t SEC]\n");
return 2;
}
}
@@ -74,6 +192,15 @@ int main(int argc, char **argv)
close(fd);
continue;
}
if (charging) {
unsigned long bits[KEY_MAX / (8 * sizeof(unsigned long)) + 1] = {0};
if (ioctl(fd, EVIOCGBIT(EV_KEY, sizeof(bits)), bits) < 0 ||
!(bits[KEY_POWER / (8 * sizeof(unsigned long))] >>
(KEY_POWER % (8 * sizeof(unsigned long))) & 1)) {
close(fd);
continue;
}
}
pfd[n].fd = fd;
pfd[n].events = POLLIN;
n++;
@@ -84,6 +211,15 @@ int main(int argc, char **argv)
fprintf(stderr, "mu300-keys: no input device with keys\n");
return 1;
}
if (charging) {
int fd = socket(AF_NETLINK, SOCK_DGRAM | SOCK_CLOEXEC, NETLINK_KOBJECT_UEVENT);
struct sockaddr_nl addr = { .nl_family = AF_NETLINK, .nl_groups = 1 };
if (fd < 0 || bind(fd, (struct sockaddr *)&addr, sizeof(addr)) < 0)
return 1;
int buffer = 256 * 1024;
setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &buffer, sizeof(buffer));
return charge_wait(pfd, n, fd, "/sys/class/power_supply/bq256xx-charger/online", hold);
}
setvbuf(stdout, NULL, _IOLBF, 0);
if (tick > 0)
next_tick = now_ms() + tick;