mirror of
https://github.com/dikeckaan/mu300-linux.git
synced 2026-12-05 16:03:51 +00:00
feat: add board-scoped U30 Air web charging control
This commit is contained in:
1 parent
24cd5104d6
commit
61bb5a3069
20 files changed
+777
-4
No files matched your search
@@ -10,6 +10,8 @@ U30 Air 的电池、灯和 PD 功能按机型隔离,不套用到无电池的 F
|
||||
- 补齐充电器、电量计和 PD 控制器的电池板识别:F50/V50 不进入 U30 Air 的电池管理路径,覆盖主、备用芯片地址。
|
||||
- 按原厂配置启用空闲停表、高精度定时器和 menu 空闲调度,保留 HZ=250 与业务轮询频率。不移植无屏机器不存在的相机、显示电源域。
|
||||
- 修复 SIPC 调试节点重复注册及失败清理,避免多 IPC 子设备重复创建同名节点。
|
||||
- 网页设备管理新增 U30 Air 充电上下限、临时充满、手动暂停/恢复及开机保存,位于 USB 网卡下面。复用已有驱动接口;F50/V50 隐藏且拒绝控制。
|
||||
- 使用电源事件与仅在策略生效时运行的 30 秒 SOC 检查,不照搬 Android 插件的常驻 5 秒轮询;已热部署并验证暂停/恢复和上限保存,USB 与 WAN 正常。
|
||||
- 补齐看门狗在系统挂起时停表、恢复时按原运行状态重装计数的处理,不开启额外的整机睡眠策略。
|
||||
|
||||
## U30 Air 灯、网页及 USB 扩展坞
|
||||
@@ -77,6 +79,7 @@ U30 Air 的电池、灯和 PD 功能按机型隔离,不套用到无电池的 F
|
||||
- [U30 Air 灯控](U30AIR-LEDS-20261016.zh-CN.md)
|
||||
- [U30 Air PD 扩展坞](U30AIR-PD-DOCK-20261016.zh-CN.md)
|
||||
- [原厂电量、省电与恢复](U30AIR-STOCK-CHARGE-20261016.zh-CN.md)
|
||||
- [U30 Air 网页充电管理](U30AIR-WEB-CHARGING-20261016.zh-CN.md)
|
||||
- [上游核对、采用项与未采用项](UPSTREAM-AUDIT-20261016.zh-CN.md)
|
||||
- [新机型适配清单](NEW-DEVICE-STOCK-ADAPTATION.zh-CN.md)
|
||||
- [安装器验证记录](../installer/VERIFICATION.md)
|
||||
@@ -4,6 +4,9 @@
|
||||
“源码覆盖”“编译通过”“已部署”和“用户实际验证”分别记录,不能互相替代。
|
||||
新机型先确认硬件及原厂行为,再选择公共实现;不要按 SoC 相同整包复制板级策略。
|
||||
|
||||
U30 Air 网页充电控制另见 [接口、机型隔离与测试记录](U30AIR-WEB-CHARGING-20261016.zh-CN.md)。
|
||||
先检查已有驱动的可写控制接口,不复制 Android 专有 sysfs 路径,不用 inotify 冒充 SOC 事件。
|
||||
|
||||
## 先识别机器与原厂基线
|
||||
|
||||
1. 保存型号、板号、Android 内核版本、原厂 DT/DTBO、模块哈希、实际启动槽和根分区类型。
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
# U30 Air 网页充电管理(2026-10-16)
|
||||
|
||||
## 用户入口与功能
|
||||
|
||||
网页「蜂窝 → 设备管理」,位于 USB 网卡卡片下方:
|
||||
|
||||
- 充电上限开关;停止阈值 50–100%,恢复阈值 20–95%,恢复必须低于停止。
|
||||
- 临时充满一次:达到 100% 且充电器实际报告 Full 后,恢复原上限策略。
|
||||
- 手动暂停电池充电、恢复自动充电。恢复自动仍遵守用户启用的上下限;需要越过上限时使用临时充满。
|
||||
- 显示当前电量、充电状态及暂停原因,提供手动刷新。
|
||||
- 中文、英文、土耳其语,跟随现有明暗主题及手机布局。
|
||||
|
||||
默认不启用上限,不主动改变用户的充电策略。配置在 `/etc/config/mu300-charge`,
|
||||
属于更新时保留的 UCI 配置;上限和手动暂停会在开机应用。
|
||||
没有电池的 F50/V50 隐藏该卡片,后端也拒绝控制,不读取其虚假 FGU 数值作为电池。
|
||||
|
||||
E5 仓库的公共网页卡片同样改到 USB 网卡下方,覆盖 E5/T551M/M8 的共享界面。
|
||||
它继续使用原 e5-charge 配置和服务,没有换成 U30 Air 的后端。
|
||||
|
||||
## 对照 Android 插件与已有驱动
|
||||
|
||||
用户提供的「充电控制器(直供电插件)」通过 Android 的
|
||||
`interface`/`zte_battery`/`battery_charging_enabled` 节点控制电池充电。
|
||||
这些原厂专有节点在当前主线内核中不存在。
|
||||
|
||||
进一步核对已有 0009、0018 补丁及实际驱动,等效接口已经存在:
|
||||
|
||||
| 操作 | OpenWrt 接口 |
|
||||
| --- | --- |
|
||||
| 暂停电池充电 | `bq256xx-charger/charge_type` 写入 `N/A` |
|
||||
| 恢复驱动正常充电 | 同一节点写入 `Fast` |
|
||||
|
||||
驱动只修改 CHG_CONFIG,并记录用户暂停意图用于后续 VBUS 检测;没有从网页直接写 I²C,
|
||||
没有新造原厂私有节点,不调整输入限流、充电电压、电量校准或 NV,也不需要换内核。
|
||||
`Fast` 是恢复充电的枚举命令,不代表强制快充协议或提高设定电流。
|
||||
|
||||
这里的“暂停充电”保留外部供电,不等于断开电池或实现了物理电池旁路。
|
||||
端口为 OTG 供电端时,不写入恢复充电命令;待切回受电端后再恢复。
|
||||
|
||||
## 事件与功耗
|
||||
|
||||
没有照搬插件的 5 秒循环和 sysfs inotify:当前 FGU 只提供部分中断/外部电源通知,
|
||||
不会为每次百分比变化发送 uevent;sysfs inotify 也不能可靠代替 SOC 检查。
|
||||
|
||||
- 使用已有 power_supply 热插拔入口处理电源事件。
|
||||
- 启用上限或临时充满时,单个 ucode 进程订阅事件,并每 30 秒读取一次本地 SOC。
|
||||
- 普通默认关闭和手动暂停不启动这个周期检查进程;GUI 关闭功能会停止服务实例。
|
||||
- 临时充满完成且没有上限策略时,停止 SOC 定时器;进程如仍存在,仅阻塞等待事件。
|
||||
- 网页只在进入、刷新和操作后读取状态,没有前端定时刷新;不发 AT,不新增拨号等待。
|
||||
- 配置和硬件应用经同一个文件锁串行执行,只在控制意图变化时写驱动。
|
||||
|
||||
## 验证与实机应用
|
||||
|
||||
- 实际 OpenWrt ARM64 隔离容器运行生产 ucode,覆盖阈值滞回、持久化、手动暂停/恢复、
|
||||
临时充满、禁用策略、非法输入、OTG 供电角色和无电池机型。
|
||||
- 另运行真实 ubus/uloop 监听,验证电源事件唤醒和无事件时 SOC 定时检查;
|
||||
不只校验后端单次调用或源码关键词。
|
||||
- 生产网页通过三语言、明暗主题、手机/桌面布局与 USB 页面原有生命周期回归。
|
||||
- 部署前确认 U30 Air 型号及 eMMC CID,使用独立 IPv6 地址,未修改同时连接的 F50。
|
||||
- 实机暂停后 `charge_type=N/A`、`status=Not charging`、`online=1`;恢复后正常充电。
|
||||
- 实机启用 70%/80% 策略时,当前 100% 电量立即暂停,服务进程正常运行。
|
||||
- USB LAN、蜂窝 WAN 保持 up,输入限流仍为 2,000,000 µA。
|
||||
- 测试后恢复部署前的默认配置:不启用上限,不手动暂停;用户可在网页自行开启。
|
||||
|
||||
本轮未通过放电验证实物达到下限后的恢复,也未重启或再次插拔 PD 扩展坞。
|
||||
这些边界不能写成实物测试已完成;软件状态转换已在隔离环境验证。
|
||||
备份在设备 `/root/update-backups/charge-control-20261016-*`,部署回执在忽略的
|
||||
`work/u30air-charge-20261016-live.json`。
|
||||
@@ -216,6 +216,8 @@ grep -q "device_no_dfs(config);" $R/usr/share/ucode/wifi/hostapd.uc || { echo "w
|
||||
if [ -d /in/luci-plugin ]; then
|
||||
cp -a /in/luci-plugin/root/. $R/
|
||||
cp -a /in/luci-plugin/htdocs/. $R/www/
|
||||
chmod 0600 $R/etc/config/mu300-charge
|
||||
chmod 0755 $R/etc/init.d/mu300-charge $R/etc/hotplug.d/power_supply/75-mu300-charge $R/usr/libexec/rpcd/mu300-charge
|
||||
ucode $R/usr/libexec/unisoc-modem/disable-channel-analysis $R
|
||||
chmod 0755 $R/etc/init.d/unisoc-cpu
|
||||
chmod 0600 $R/etc/config/unisoc_apn
|
||||
@@ -286,6 +288,8 @@ if [ -d /in/luci-plugin ]; then
|
||||
ln -sf ../init.d/unisoc-traffic $R/etc/rc.d/K01unisoc-traffic
|
||||
ln -sf ../init.d/unisoc-cpu $R/etc/rc.d/S99unisoc-cpu
|
||||
ln -sf ../init.d/unisoc-cpu $R/etc/rc.d/K89unisoc-cpu
|
||||
ln -sf ../init.d/mu300-charge $R/etc/rc.d/S97mu300-charge
|
||||
ln -sf ../init.d/mu300-charge $R/etc/rc.d/K20mu300-charge
|
||||
fi
|
||||
# busybox PATH is /usr/sbin:/usr/bin:/sbin:/bin, so the commands go into /usr/bin
|
||||
for c in mu300-toolkit mu300-next-boot mu300-os mu300-update mobile-data mu300-at mu300-sms led-status wifi-client mu300-ttl mu300-wifi-band mu300-led mu300-usb mu300-nfc mu300-user-packages; do ln -sf /opt/mu300/bin/$c $R/usr/bin/$c; done
|
||||
|
||||
@@ -2,7 +2,7 @@ include $(TOPDIR)/rules.mk
|
||||
|
||||
PKG_NAME:=luci-app-mu300
|
||||
PKG_VERSION:=1.2.0
|
||||
PKG_RELEASE:=14
|
||||
PKG_RELEASE:=15
|
||||
PKG_LICENSE:=MIT
|
||||
PKG_MAINTAINER:=MU300 Linux contributors
|
||||
PKGARCH:=all
|
||||
@@ -26,6 +26,7 @@ endef
|
||||
define Package/luci-app-mu300/conffiles
|
||||
/etc/config/unisoc_modem
|
||||
/etc/config/unisoc_apn
|
||||
/etc/config/mu300-charge
|
||||
/etc/unisoc-modem/cpu.json
|
||||
/etc/unisoc-modem/cpu-voltage.json
|
||||
endef
|
||||
@@ -38,6 +39,8 @@ define Package/luci-app-mu300/install
|
||||
$(CP) ./htdocs/. $(1)/www/
|
||||
$(CP) ./root/. $(1)/
|
||||
chmod 0600 $(1)/etc/config/unisoc_apn
|
||||
chmod 0600 $(1)/etc/config/mu300-charge
|
||||
chmod 0755 $(1)/etc/init.d/mu300-charge $(1)/etc/hotplug.d/power_supply/75-mu300-charge $(1)/usr/libexec/rpcd/mu300-charge
|
||||
chmod 0755 $(1)/etc/init.d/unisoc-cpu
|
||||
chmod 0755 $(1)/etc/init.d/unisoc-modem-ui $(1)/etc/init.d/unisoc-sms-forward $(1)/etc/init.d/unisoc-traffic $(1)/etc/hotplug.d/net/90-unisoc-usb-host $(1)/etc/hotplug.d/iface/90-unisoc-usb-host $(1)/usr/libexec/rpcd/mu300dash $(1)/usr/libexec/unisoc-modem/*
|
||||
$(INSTALL_DIR) $(1)/usr/lib/lua/luci/i18n
|
||||
@@ -63,6 +66,8 @@ define Package/luci-app-mu300/postinst
|
||||
/etc/init.d/rpcd restart 2>/dev/null || true
|
||||
/etc/init.d/unisoc-modem-ui enable 2>/dev/null || true
|
||||
/etc/init.d/unisoc-modem-ui start 2>/dev/null || true
|
||||
/etc/init.d/mu300-charge enable 2>/dev/null || true
|
||||
/etc/init.d/mu300-charge start 2>/dev/null || true
|
||||
/etc/init.d/unisoc-sms-forward enable 2>/dev/null || true
|
||||
/etc/init.d/unisoc-sms-forward start 2>/dev/null || true
|
||||
/etc/init.d/unisoc-traffic enable 2>/dev/null || true
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
'use strict';
|
||||
'require baseclass';
|
||||
'require rpc';
|
||||
'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 fullOnce = rpc.declare({object:'mu300-charge', method:'full_once', expect:{'':{}}, nobatch:true});
|
||||
|
||||
var pause = rpc.declare({object:'mu300-charge', method:'pause', expect:{'':{}}, nobatch:true});
|
||||
var resume = rpc.declare({object:'mu300-charge', method:'resume', expect:{'':{}}, nobatch:true});
|
||||
|
||||
function message(error) {
|
||||
return M.translate({
|
||||
charge_invalid: '充电阈值必须是范围内的整数',
|
||||
charge_threshold_order: '恢复充电阈值必须低于停止阈值',
|
||||
charge_unavailable: '当前设备的充电控制暂不可用',
|
||||
charge_save_failed: '充电设置保存失败',
|
||||
charge_reload_failed: '充电设置已保存,但服务应用失败,请重试',
|
||||
charge_busy: '充电设置正在应用,请稍后重试',
|
||||
charge_apply_failed: '充电设置已保存,但驱动应用失败,请重试',
|
||||
charge_state_failed: '充电状态保存失败,请重试'
|
||||
}[error] || '充电控制读取失败,请刷新重试');
|
||||
}
|
||||
|
||||
return baseclass.extend({
|
||||
mount: function(root) {
|
||||
var card = document.createElement('section');
|
||||
card.className = 'mud-card mud-charge-card';
|
||||
card.style.marginTop = '14px';
|
||||
card.hidden = true;
|
||||
card.innerHTML = `
|
||||
<style>
|
||||
.mud-charge-controls{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:14px;max-width:560px}
|
||||
.mud-charge-controls input{width:100%;min-height:38px;box-sizing:border-box;padding:6px 10px;border:1px solid var(--hairline,var(--border,#ccc));border-radius:var(--radius-base,.5rem);background:var(--surface,var(--background,#fff));color:var(--text,#222)}
|
||||
.mud-charge-card .mud-device-toggle{margin-top:16px}
|
||||
.mud-charge-card .mud-note{line-height:1.65}
|
||||
@media(max-width:420px){.mud-charge-controls{grid-template-columns:1fr;gap:0}}
|
||||
</style>
|
||||
<div class="mud-device-head"><h3>充电管理</h3><button type="button" class="mud-btn" data-charge="refresh">刷新</button></div>
|
||||
<div class="mud-r"><span class="mud-k">当前电量</span><span class="mud-v" data-charge="capacity">--</span></div>
|
||||
<div class="mud-r"><span class="mud-k">充电状态</span><span class="mud-v" data-charge="status" role="status" aria-live="polite">正在读取…</span></div>
|
||||
<form data-charge="form">
|
||||
<label class="mud-device-toggle"><input type="checkbox" data-charge="enabled" disabled>启用充电上限</label>
|
||||
<div class="mud-charge-controls">
|
||||
<div class="mud-device-field"><label for="mud-charge-stop">停止充电于(50–100%)</label><input id="mud-charge-stop" data-charge="stop" type="number" min="50" max="100" step="1" required disabled></div>
|
||||
<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>
|
||||
<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>
|
||||
</form>`;
|
||||
M.localize(card);
|
||||
root.appendChild(card);
|
||||
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; });
|
||||
q('once').disabled = pending || !state.available || !!state.full_once;
|
||||
q('refresh').disabled = pending;
|
||||
}
|
||||
function paint(s) {
|
||||
state = s || {};
|
||||
card.hidden = s.supported !== true;
|
||||
q('capacity').textContent = Number.isInteger(s.capacity) ? s.capacity + '%' : '--';
|
||||
var label = !s.available ? '当前设备的充电控制暂不可用' : s.pending ? '等待切回受电后恢复充电' : s.online && s.stopped ? (s.paused ? '已暂停电池充电' : '已按上限暂停充电') :
|
||||
s.status === 'Full' ? '已充满' : s.status === 'Charging' ? '正在充电' : !s.online ? '使用电池' : '未充电';
|
||||
q('status').textContent = M.translate(label);
|
||||
q('pause').textContent = M.translate(s.paused ? '恢复自动充电' : '暂停电池充电');
|
||||
q('enabled').checked = !!s.enabled;
|
||||
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 ? '正在临时充满…' : '临时充满一次');
|
||||
disable();
|
||||
}
|
||||
async function perform(action, saving) {
|
||||
if (pending) return;
|
||||
pending = true; disable();
|
||||
q('note').textContent = M.translate(saving ? '正在应用充电设置…' : '正在读取…');
|
||||
try {
|
||||
var r = await action();
|
||||
if (!r || !r.ok) throw new Error(r && r.error);
|
||||
paint(r);
|
||||
q('note').textContent = M.translate(saving ? '充电设置已应用,重启后保留' : '临时充满后,自动恢复原来的充电上限。');
|
||||
} catch (error) {
|
||||
q('note').textContent = message(error.message);
|
||||
// A failed read must never enable controls with invented defaults.
|
||||
if (!saving) { state.available = false; q('status').textContent = message(error.message); }
|
||||
} finally { pending = false; disable(); }
|
||||
}
|
||||
q('refresh').onclick = function() { return perform(get, false); };
|
||||
q('form').onsubmit = function(event) {
|
||||
event.preventDefault();
|
||||
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);
|
||||
};
|
||||
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); };
|
||||
// One local snapshot on entry; no background polling or new policy loop.
|
||||
return perform(get, false);
|
||||
}
|
||||
});
|
||||
@@ -113,6 +113,39 @@ var callUsbNetAdd = rpc.declare({ object: 'mu300dash', method: 'usb_net_add', pa
|
||||
* standalone package works in any OpenWrt buildroot without po2lmo or extra
|
||||
* language packages. Chinese remains the source/fallback language. */
|
||||
var DASH_I18N = {
|
||||
"等待切回受电后恢复充电": ["Charging will resume when the port returns to power-sink mode", "Bağlantı noktası güç alıcı moduna dönünce şarj devam edecek"],
|
||||
"保存并应用": ["Save & apply","Kaydet ve uygula"],
|
||||
"充电管理": ["Charging controls","Şarj denetimi"],
|
||||
"当前电量": ["Battery level","Pil seviyesi"],
|
||||
"充电状态": ["Charging status","Şarj durumu"],
|
||||
"正在读取…": ["Reading…","Okunuyor…"],
|
||||
"启用充电上限": ["Enable charge limit","Şarj sınırını etkinleştir"],
|
||||
"停止充电于(50–100%)": ["Stop charging at (50–100%)","Şarjı durdur (%50–100)"],
|
||||
"恢复充电于(20–95%)": ["Resume charging at (20–95%)","Şarjı sürdür (%20–95)"],
|
||||
"临时充满一次": ["Charge to full once","Bir kez tam şarj et"],
|
||||
"正在临时充满…": ["Charging to full once…","Bir kez tam şarj ediliyor…"],
|
||||
"临时充满后,自动恢复原来的充电上限。": ["The original charge limit resumes automatically after reaching full charge.","Tam şarjdan sonra önceki şarj sınırı otomatik geri yüklenir."],
|
||||
"充电阈值必须是范围内的整数": ["Charge thresholds must be whole numbers within range","Şarj eşikleri belirtilen aralıkta tam sayı olmalıdır"],
|
||||
"恢复充电阈值必须低于停止阈值": ["The resume threshold must be lower than the stop threshold","Devam eşiği durdurma eşiğinden düşük olmalıdır"],
|
||||
"当前设备的充电控制暂不可用": ["Charging controls are currently unavailable on this device","Bu cihazda şarj denetimi şu anda kullanılamıyor"],
|
||||
"充电设置保存失败": ["Failed to save charging settings","Şarj ayarları kaydedilemedi"],
|
||||
"充电设置已保存,但服务应用失败,请重试": ["Charging settings were saved, but the service could not apply them. Please retry.","Şarj ayarları kaydedildi ancak hizmet uygulayamadı. Yeniden deneyin."],
|
||||
"充电设置正在应用,请稍后重试": ["Charging settings are being applied. Please try again shortly.","Şarj ayarları uygulanıyor. Biraz sonra yeniden deneyin."],
|
||||
"充电控制读取失败,请刷新重试": ["Failed to read charging controls. Refresh to retry.","Şarj denetimi okunamadı. Yenileyerek tekrar deneyin."],
|
||||
"已按上限暂停充电": ["Paused at charge limit","Şarj sınırında duraklatıldı"],
|
||||
"已充满": ["Fully charged","Tam şarj oldu"],
|
||||
"正在充电": ["Charging","Şarj ediliyor"],
|
||||
"使用电池": ["On battery","Pille çalışıyor"],
|
||||
"未充电": ["Not charging","Şarj olmuyor"],
|
||||
"正在应用充电设置…": ["Applying charging settings…","Şarj ayarları uygulanıyor…"],
|
||||
"到达上限后暂停充电,降至下限时恢复。关闭上限会恢复正常充电。设置在重启后保留。": ["Charging pauses at the upper limit and resumes at the lower limit. Disabling the limit restores normal charging. Settings survive reboot.","Üst sınırda şarj durur, alt sınırda devam eder. Sınır kapatılınca normal şarja dönülür. Ayarlar yeniden başlatmada korunur."],
|
||||
"暂停电池充电时保留 USB 供电,不会关闭 USB 数据或 OTG。": ["Pausing battery charging keeps USB power, data and OTG available.","Pil şarjını duraklatmak USB gücünü, veriyi veya OTG işlevini kapatmaz."],
|
||||
"暂停电池充电": ["Pause battery charging","Pil şarjını duraklat"],
|
||||
"已暂停电池充电": ["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"],
|
||||
"充电设置已保存,但驱动应用失败,请重试": ["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'],
|
||||
'编辑': ['Edit', 'Düzenle'],
|
||||
'接入点 APN': ['Access points (APN)', 'Erişim noktaları (APN)'],
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
'use strict';
|
||||
'require view';
|
||||
'require mu300.common as M';
|
||||
'require mu300.charge as Charge';
|
||||
|
||||
return view.extend({
|
||||
load: function() { return L.resolveDefault(M.callUsbGet(), {}); },
|
||||
@@ -69,6 +70,7 @@ return view.extend({
|
||||
this.wire();
|
||||
this.paint();
|
||||
this.refreshAdapters();
|
||||
Charge.mount(root);
|
||||
return root;
|
||||
},
|
||||
q: function(id) { return this.root.querySelector('#mud-usb-' + id); },
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
config charge 'main'
|
||||
option enabled '0'
|
||||
option start '70'
|
||||
option stop '80'
|
||||
option paused '0'
|
||||
option full_once '0'
|
||||
@@ -0,0 +1,10 @@
|
||||
#!/bin/sh
|
||||
[ "$ACTION" = change ] || [ "$ACTION" = add ] || exit 0
|
||||
[ "$(cat /run/mu300/device 2>/dev/null)" = u30air ] || exit 0
|
||||
# The existing driver retains the pause across VBUS changes. Do not poll it
|
||||
# from hotplug, or touch the batteryless F50/V50 power path.
|
||||
if [ -s /run/mu300-charge.json ] || [ "$(uci -q get mu300-charge.main.enabled)" = 1 ] ||
|
||||
[ "$(uci -q get mu300-charge.main.paused)" = 1 ]; then
|
||||
/usr/libexec/unisoc-modem/charge apply >/dev/null
|
||||
ubus send mu300.charge '{}' >/dev/null 2>&1
|
||||
fi
|
||||
@@ -0,0 +1,19 @@
|
||||
#!/bin/sh /etc/rc.common
|
||||
START=97
|
||||
STOP=20
|
||||
USE_PROCD=1
|
||||
|
||||
start_service() {
|
||||
[ "$(cat /run/mu300/device 2>/dev/null)" = u30air ] || return 0
|
||||
/usr/libexec/unisoc-modem/charge apply >/dev/null
|
||||
[ "$(uci -q get mu300-charge.main.paused)" != 1 ] || return 0
|
||||
if [ "$(uci -q get mu300-charge.main.enabled)" != 1 ] &&
|
||||
[ "$(uci -q get mu300-charge.main.full_once)" != 1 ]; then return 0; fi
|
||||
procd_open_instance
|
||||
procd_set_param command /usr/bin/ucode /usr/libexec/unisoc-modem/charge-watch.uc
|
||||
procd_set_param respawn 3600 5 5
|
||||
procd_close_instance
|
||||
}
|
||||
|
||||
reload_service() { stop; start; }
|
||||
service_triggers() { procd_add_reload_trigger mu300-charge; }
|
||||
@@ -0,0 +1,10 @@
|
||||
#!/bin/sh
|
||||
case "$1:$2" in
|
||||
list:)
|
||||
echo '{"get":{},"configure":{"enabled":"","start":"","stop":""},"full_once":{},"pause":{},"resume":{}}'
|
||||
;;
|
||||
call:get|call:configure|call:full_once|call:pause|call:resume)
|
||||
exec /usr/libexec/unisoc-modem/charge "$2"
|
||||
;;
|
||||
*) exit 1 ;;
|
||||
esac
|
||||
@@ -0,0 +1,19 @@
|
||||
#!/bin/sh
|
||||
action=${1:-get}
|
||||
case "$action" in get|configure|full_once|pause|resume|apply) ;; *) exit 2 ;; esac
|
||||
if [ "$action" != get ]; then
|
||||
exec 9> "${MU300_CHARGE_LOCK:-/run/mu300-charge.lock}" || exit 1
|
||||
flock -n 9 || { echo '{"ok":false,"error":"charge_busy"}'; exit 0; }
|
||||
fi
|
||||
reply=$(ucode "${MU300_CHARGE_LIB:-/usr/libexec/unisoc-modem/charge.uc}" "$action")
|
||||
rc=$?
|
||||
exec 9>&-
|
||||
case "$action" in configure|full_once|pause|resume)
|
||||
if [ "$rc" = 0 ] && [ "$(printf '%s' "$reply" | jsonfilter -e '@.ok')" = true ]; then
|
||||
if ! "${MU300_CHARGE_SERVICE:-/etc/init.d/mu300-charge}" reload >/dev/null 2>&1; then
|
||||
reply='{"ok":false,"saved":true,"error":"charge_reload_failed"}'
|
||||
fi
|
||||
fi
|
||||
esac
|
||||
printf '%s\n' "$reply"
|
||||
exit "$rc"
|
||||
@@ -0,0 +1,31 @@
|
||||
// Active policy only: power events plus a low-frequency SOC check.
|
||||
// This FGU has no periodic percentage uevents; sysfs inotify is not reliable.
|
||||
import * as fs from 'fs';
|
||||
import * as ubus from 'ubus';
|
||||
import * as uloop from 'uloop';
|
||||
|
||||
uloop.init();
|
||||
const bus = ubus.connect(null, 2);
|
||||
if (!bus) die('Charge policy: ubus unavailable\n');
|
||||
let pending = false;
|
||||
let check;
|
||||
check = uloop.timer(-1, () => {
|
||||
pending = false;
|
||||
let pipe = fs.popen('/usr/libexec/unisoc-modem/charge apply', 'r');
|
||||
let state;
|
||||
if (pipe) {
|
||||
try { state = json(pipe.read('all')); } catch (e) {}
|
||||
pipe.close();
|
||||
}
|
||||
// A completed one-off charge needs no further SOC timer. A later power
|
||||
// event can still be handled while this loop is blocked in epoll.
|
||||
if (!state?.ok || (!state.paused && (state.enabled || state.full_once))) check.set(30000);
|
||||
});
|
||||
const event = bus.listener('mu300.charge', () => {
|
||||
if (!pending) { pending = true; check.set(100); }
|
||||
});
|
||||
if (!event) die('Charge policy: event subscription failed\n');
|
||||
const term = uloop.signal(15, () => uloop.end());
|
||||
const interrupt = uloop.signal(2, () => uloop.end());
|
||||
check.set(30000);
|
||||
uloop.run();
|
||||
@@ -0,0 +1,119 @@
|
||||
// U30 Air charge policy. The charger driver owns registers, VBUS and OTG.
|
||||
import * as fs from 'fs';
|
||||
import * as uci from 'uci';
|
||||
|
||||
const ROOT = getenv('MU300_CHARGE_SYS') || '/sys/class/power_supply';
|
||||
const STATE = getenv('MU300_CHARGE_STATE') || '/run/mu300-charge.json';
|
||||
const BOARD = getenv('MU300_CHARGE_DEVICE') || trim(fs.readfile('/run/mu300/device') || '');
|
||||
const cfg = uci.cursor(getenv('MU300_CHARGE_CONFIG') || '/etc/config');
|
||||
const PKG = 'mu300-charge';
|
||||
const BAT = ROOT + '/sc27xx-fgu', CHG = ROOT + '/bq256xx-charger';
|
||||
let saved = false;
|
||||
|
||||
function read(path) { return trim(fs.readfile(path) || ''); }
|
||||
function integer(v, low, high) {
|
||||
if (type(v) != 'int' && type(v) != 'string') die('charge_invalid');
|
||||
if (!match('' + v, /^[0-9]{1,3}$/) || int(v) < low || int(v) > high) die('charge_invalid');
|
||||
return int(v);
|
||||
}
|
||||
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),
|
||||
paused: integer(cfg.get(PKG, 'main', 'paused') || '0', 0, 1),
|
||||
full_once: integer(cfg.get(PKG, 'main', 'full_once') || '0', 0, 1) };
|
||||
}
|
||||
function store(values) {
|
||||
for (let key, value in values)
|
||||
if (!cfg.set(PKG, 'main', key, '' + value)) die('charge_save_failed');
|
||||
if (!cfg.commit(PKG)) die('charge_save_failed');
|
||||
saved = true;
|
||||
}
|
||||
function previous() {
|
||||
try { return json(fs.readfile(STATE)) || {}; } catch (e) { return {}; }
|
||||
}
|
||||
function supported() { return BOARD == 'u30air'; }
|
||||
function available() {
|
||||
return supported() && read(BAT + '/present') == '1' &&
|
||||
!!match(read(BAT + '/capacity'), /^(100|[0-9]{1,2})$/) &&
|
||||
!!(fs.stat(CHG + '/charge_type')?.mode & 128);
|
||||
}
|
||||
function snapshot(c) {
|
||||
let old = previous(), valid = available();
|
||||
let cap = valid ? int(read(BAT + '/capacity')) : null;
|
||||
let current = valid ? read(BAT + '/current_now') : '';
|
||||
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,
|
||||
paused: !!c.paused, stopped: !!old.stopped, reason: old.reason || '', pending: !!old.pending };
|
||||
}
|
||||
function remember(state) {
|
||||
const temp = STATE + '.new';
|
||||
let text = sprintf('%J\n', state);
|
||||
if (fs.writefile(temp, text) != length(text) || !fs.rename(temp, STATE)) {
|
||||
fs.unlink(temp); die('charge_state_failed');
|
||||
}
|
||||
}
|
||||
function apply(c) {
|
||||
if (!available()) die('charge_unavailable');
|
||||
let s = snapshot(c), old = previous();
|
||||
if (c.full_once && !c.paused && s.capacity == 100 && s.status == 'Full') {
|
||||
store({full_once: 0}); c.full_once = 0;
|
||||
}
|
||||
let reason = c.paused ? 'manual' : '';
|
||||
if (!reason && c.enabled && !c.full_once &&
|
||||
(s.capacity >= c.stop || (s.capacity > c.start && old.reason == 'limit' && old.stopped))) reason = 'limit';
|
||||
let stopped = length(reason) > 0;
|
||||
let owned = !!(c.enabled || c.paused || c.full_once);
|
||||
// Never enable battery charging while the port is sourcing OTG power.
|
||||
// Leave the previous pause owned until the next sink/charger event.
|
||||
let source = !!match(read(CHG + '/usb_type'), /\[ACA\]/);
|
||||
const TYPEC = getenv('MU300_CHARGE_TYPEC') || '/sys/class/typec';
|
||||
for (let path in fs.glob(TYPEC + '/port*/power_role') || [])
|
||||
if (match(read(path), /\[source\]/) || read(path) == 'source') source = true;
|
||||
if (!stopped && source && old.stopped) {
|
||||
remember({owned: true, stopped: true, reason: old.reason, pending: true});
|
||||
return snapshot(c);
|
||||
}
|
||||
// Default-disabled policy does not take ownership of the charger.
|
||||
if (stopped || owned || old.owned) {
|
||||
if (old.stopped !== stopped || !old.owned || old.pending) {
|
||||
let text = stopped ? 'N/A' : 'Fast';
|
||||
if (!stopped && source) {
|
||||
remember({owned, stopped: false, reason: '', pending: false});
|
||||
return snapshot(c);
|
||||
}
|
||||
if (fs.writefile(CHG + '/charge_type', text) != length(text)) die('charge_apply_failed');
|
||||
}
|
||||
}
|
||||
remember({owned, stopped, reason, pending: false});
|
||||
return snapshot(c);
|
||||
}
|
||||
|
||||
try {
|
||||
let action = ARGV[0] || 'get';
|
||||
let c = settings();
|
||||
if (c.start >= c.stop) die('charge_threshold_order');
|
||||
if (action == 'get') print(sprintf('%J\n', snapshot(c)));
|
||||
else {
|
||||
if (!available()) die('charge_unavailable');
|
||||
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};
|
||||
if (next.start >= next.stop) die('charge_threshold_order');
|
||||
store(next); c = next;
|
||||
} else if (action == 'pause' || action == 'resume') {
|
||||
store({paused: action == 'pause' ? 1 : 0, full_once: 0});
|
||||
c.paused = action == 'pause' ? 1 : 0; c.full_once = 0;
|
||||
} else if (action == 'full_once') {
|
||||
store({paused: 0, full_once: 1}); c.paused = 0; c.full_once = 1;
|
||||
} else if (action != 'apply') die('charge_invalid');
|
||||
print(sprintf('%J\n', apply(c)));
|
||||
}
|
||||
} catch (error) {
|
||||
let message = '' + (error?.message || error);
|
||||
let code = match(message, /charge_[a-z_]+/)?.[0] || 'charge_unavailable';
|
||||
print(sprintf('%J\n', {ok: false, saved, error: code}));
|
||||
}
|
||||
@@ -7,7 +7,8 @@
|
||||
"apn_get", "sysinfo", "status", "rates", "cells", "signal", "at_history",
|
||||
"lock_get", "lock_status", "sms_list", "sms_show", "forward_get",
|
||||
"forward_status", "traffic_get", "usb_get", "usb_net_list", "cpu_get", "cpu_voltage_get", "sim_get", "data_sim_get", "data_sim_status"
|
||||
]
|
||||
],
|
||||
"mu300-charge": [ "get" ]
|
||||
},
|
||||
"uci": {
|
||||
"unisoc_modem": [ "*" ]
|
||||
@@ -15,7 +16,8 @@
|
||||
},
|
||||
"write": {
|
||||
"ubus": {
|
||||
"mu300dash": [ "*" ]
|
||||
"mu300dash": [ "*" ],
|
||||
"mu300-charge": [ "configure", "full_once", "pause", "resume" ]
|
||||
},
|
||||
"uci": {
|
||||
"unisoc_modem": [ "*" ]
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
// Test the production LuCI handlers without device access or a browser timer.
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const dir = path.join(__dirname, '../openwrt/luci-app-mu300/htdocs/luci-static/resources');
|
||||
const source = fs.readFileSync(path.join(dir, 'mu300/charge.js'), 'utf8');
|
||||
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});
|
||||
function fixture() {
|
||||
const elements = {}, calls = [], replies = [state()];
|
||||
const card = {style:{}, querySelector(selector) {
|
||||
const name = /data-charge="([^"]+)"/.exec(selector)[1];
|
||||
return elements[name] ||= {disabled:false, value:'', checked:false, textContent:'', reportValidity:()=>true};
|
||||
}};
|
||||
const root = {appendChild(child){assert.equal(child,card);this.card=child;}};
|
||||
const translate = text => {
|
||||
// All user-visible Chinese strings must have both English and Turkish.
|
||||
if (/[\u4e00-\u9fff]/.test(text)) {
|
||||
assert(catalog[text], 'missing translation: ' + text);
|
||||
assert.equal(catalog[text].length, 2);
|
||||
}
|
||||
return text;
|
||||
};
|
||||
const M = {translate, localize(node) {
|
||||
for (const text of node.innerHTML.matchAll(/>([^<>]*[\u4e00-\u9fff][^<>]*)</g)) translate(text[1]);
|
||||
}};
|
||||
const rpc = {declare(info){return (...args) => {
|
||||
calls.push([info.method, ...args]);
|
||||
const reply = replies.shift();
|
||||
return reply instanceof Error ? Promise.reject(reply) : Promise.resolve(reply);
|
||||
};}};
|
||||
const module = new Function('baseclass','rpc','M','document',source)(
|
||||
{extend:x=>x}, rpc, M, {createElement:()=>card});
|
||||
return {elements, calls, replies, module, root};
|
||||
}
|
||||
const submit = f => f.elements.form.onsubmit({preventDefault(){}});
|
||||
(async () => {
|
||||
const f = fixture(); await f.module.mount(f.root);
|
||||
assert.equal(f.elements.capacity.textContent,'76%');
|
||||
assert.equal(f.elements.start.value,70);
|
||||
assert.equal(f.elements.save.disabled,false);
|
||||
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});
|
||||
await submit(f);
|
||||
assert.deepEqual(f.calls.at(-1),['configure','1','65','85']);
|
||||
f.replies.push({...state(),full_once:true});
|
||||
await f.elements.once.onclick();
|
||||
assert.equal(f.elements.once.disabled,true);
|
||||
assert.equal(f.elements.once.textContent,'正在临时充满…');
|
||||
f.replies.push({...state(), paused:true, stopped:true});
|
||||
await f.elements.pause.onclick();
|
||||
assert.deepEqual(f.calls.at(-1),['pause']);
|
||||
assert.equal(f.elements.pause.textContent,'恢复自动充电');
|
||||
f.replies.push({...state(), paused:false});
|
||||
await f.elements.pause.onclick();
|
||||
assert.deepEqual(f.calls.at(-1),['resume']);
|
||||
// Explicit refresh follows a settings change.
|
||||
f.replies.push({...state(),enabled:false,start:60,stop:90});
|
||||
await f.elements.refresh.onclick();
|
||||
assert.equal(f.elements.enabled.checked,false);
|
||||
assert.equal(f.elements.stop.value,90);
|
||||
f.replies.push({ok:false,saved:true,error:'charge_reload_failed'});
|
||||
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.root.card.hidden,true);
|
||||
submit(down); assert.equal(down.calls.length,1);
|
||||
const failed = fixture(); failed.replies[0]=new Error('connection');
|
||||
await failed.module.mount(failed.root);
|
||||
assert.equal(failed.elements.save.disabled,true);
|
||||
assert.match(failed.elements.note.textContent,/读取失败/);
|
||||
// Duplicate requests are blocked until the existing one completes.
|
||||
let resolve;
|
||||
const pending = fixture(); pending.replies[0]=new Promise(r=>{resolve=r;});
|
||||
const loading = pending.module.mount(pending.root);
|
||||
pending.elements.refresh.onclick(); assert.equal(pending.calls.length,1);
|
||||
assert.equal(pending.elements.refresh.disabled,true);
|
||||
resolve(state()); await loading;
|
||||
assert.equal(pending.elements.refresh.disabled,false);
|
||||
assert(!/setInterval|setTimeout|poll\.add/.test(source));
|
||||
console.log('PASS: charge controls, shared settings refresh, threshold checks, charge once, errors, unavailable hardware, request isolation, translations, no polling');
|
||||
})().catch(error=>{console.error(error);process.exitCode=1;});
|
||||
@@ -0,0 +1,67 @@
|
||||
"""Render the real device page and charging card on mobile and desktop."""
|
||||
from pathlib import Path
|
||||
from playwright.sync_api import sync_playwright
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
JS = ROOT/'openwrt/luci-app-mu300/htdocs/luci-static/resources'
|
||||
sources = {name: (JS/path).read_text(encoding='utf-8') for name, path in {
|
||||
'common':'mu300/common.js', 'charge':'mu300/charge.js', 'device':'view/mu300/device.js'}.items()}
|
||||
with sync_playwright() as p:
|
||||
browser = p.chromium.launch(executable_path='C:/Program Files/Google/Chrome/Application/chrome.exe')
|
||||
for lang in ('zh-cn', 'en', 'tr'):
|
||||
for dark in (False, True):
|
||||
page = browser.new_page(viewport={'width':375 if dark else 1100, 'height':900})
|
||||
errors = []
|
||||
page.on('pageerror', lambda error: errors.append(str(error)))
|
||||
page.set_content('<main></main>')
|
||||
page.evaluate('''({sources,lang,dark})=>{
|
||||
window.L={env:{lang},resolveDefault:(p,d)=>Promise.resolve(p).catch(()=>d)};
|
||||
document.documentElement.lang=lang;
|
||||
document.documentElement.style.cssText=dark
|
||||
? '--surface:#20232b;--text:#eee;--text-muted:#aaa;--hairline:#454956;color:#eee;background:#11141a'
|
||||
: '--surface:#fff;--text:#222;--text-muted:#666;--hairline:#ddd;color:#222;background:#f3f4f6';
|
||||
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};
|
||||
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]});
|
||||
}
|
||||
if(info.method==='full_once')chargeState.full_once=true;
|
||||
if(info.method==='pause')chargeState.paused=true;
|
||||
if(info.method==='resume')chargeState.paused=false;
|
||||
return Promise.resolve({...chargeState});
|
||||
}
|
||||
return Promise.resolve({ok:1,devices:[],net_current:'ncm',role:'device'});
|
||||
}};
|
||||
const baseclass={extend:x=>x};
|
||||
const M=new Function('baseclass','rpc','L',sources.common)(baseclass,rpc,L);
|
||||
const Charge=new Function('baseclass','rpc','M',sources.charge)(baseclass,rpc,M);
|
||||
const app=new Function('view','M','Charge','L',sources.device)({extend:x=>x},M,Charge,L);
|
||||
document.querySelector('main').appendChild(app.render({ok:1,role:'device',net_current:'ncm'}));
|
||||
}''', dict(sources=sources, lang=lang, dark=dark))
|
||||
save = page.locator('[data-charge="save"]')
|
||||
save.wait_for()
|
||||
assert page.locator('.mud-charge-card').evaluate("el => el.previousElementSibling.id") == 'mud-usb-adapters-card'
|
||||
page.wait_for_function('!document.querySelector(\'[data-charge="save"]\').disabled')
|
||||
page.locator('#mud-charge-stop').fill('90')
|
||||
page.locator('#mud-charge-start').fill('60')
|
||||
save.click()
|
||||
page.wait_for_function('saved.length===1')
|
||||
assert page.evaluate('saved') == [['1','60','90']]
|
||||
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%'
|
||||
assert page.evaluate('document.documentElement.scrollWidth<=innerWidth'), (lang, dark)
|
||||
if lang == 'en':
|
||||
assert page.locator('[data-charge="once"]').inner_text() == 'Charging to full once…'
|
||||
page.locator('[data-charge="pause"]').click()
|
||||
page.wait_for_function('chargeState.paused===true')
|
||||
page.locator('[data-charge="pause"]').click()
|
||||
page.wait_for_function('chargeState.paused===false')
|
||||
assert not errors, errors
|
||||
page.close()
|
||||
browser.close()
|
||||
print('PASS: actual device page, charge RPCs, mobile/desktop layout, light/dark colors, Chinese/English/Turkish')
|
||||
@@ -28,7 +28,7 @@ def main():
|
||||
return Promise.resolve({});
|
||||
}};
|
||||
window.M=new Function('rpc','baseclass','L',common)(rpc,base,L);
|
||||
window.v=new Function('view','M','L',device)(base,M,L);
|
||||
window.v=new Function('view','M','L','Charge',device)(base,M,L,{mount(){}});
|
||||
document.querySelector('main').appendChild(v.render(state));
|
||||
// Only accelerate test timers, keeping production deadline logic.
|
||||
const later=v.later;v.later=function(fn,ms){return later.call(this,fn,ms>=1500?120:Math.min(ms,30));};
|
||||
|
||||
@@ -0,0 +1,179 @@
|
||||
"""Execute the real ucode backend in an isolated OpenWrt ARM64 container.
|
||||
|
||||
Set MU300_CHARGE_TEST_IMAGE to a locally built OpenWrt image with ucode/fs/uci.
|
||||
No device access or external network is used.
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import time
|
||||
import unittest
|
||||
import uuid
|
||||
|
||||
TOP = Path(__file__).resolve().parents[1]
|
||||
ROOT = TOP/'openwrt/luci-app-mu300/root'
|
||||
IMAGE = os.environ.get('MU300_CHARGE_TEST_IMAGE')
|
||||
|
||||
|
||||
@unittest.skipUnless(IMAGE and shutil.which('docker'), 'Set MU300_CHARGE_TEST_IMAGE to run actual OpenWrt ucode')
|
||||
class ChargeControl(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.temp = tempfile.TemporaryDirectory(prefix='mu300-charge-')
|
||||
cls.fixture = Path(cls.temp.name)
|
||||
cls.container = 'mu300-charge-test-'+uuid.uuid4().hex[:8]
|
||||
subprocess.run(['docker','run','-d','--name',cls.container,'--network','none','--platform','linux/arm64',
|
||||
'-v',str(ROOT)+':/feature:ro','-v',str(cls.fixture)+':/fixture',
|
||||
'-v',str(ROOT/'usr/libexec/unisoc-modem')+':/usr/libexec/unisoc-modem:ro',
|
||||
IMAGE,'/bin/sleep','3600'],check=True,stdout=subprocess.DEVNULL)
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
subprocess.run(['docker','rm','-f',cls.container],check=True,stdout=subprocess.DEVNULL)
|
||||
cls.temp.cleanup()
|
||||
|
||||
def setUp(self):
|
||||
for path in self.fixture.iterdir():
|
||||
if path.is_dir():shutil.rmtree(path)
|
||||
else:path.unlink()
|
||||
self.config = self.fixture/'config'
|
||||
self.config.mkdir()
|
||||
shutil.copy2(ROOT/'etc/config/mu300-charge',self.config/'mu300-charge')
|
||||
self.sys = self.fixture/'power'
|
||||
self.charger = self.sys/'bq256xx-charger'
|
||||
self.battery = self.sys/'sc27xx-fgu'
|
||||
self.charger.mkdir(parents=True);self.battery.mkdir()
|
||||
for name,value in {'charge_type':'Fast','online':'1','status':'Charging','usb_type':'[SDP] DCP',
|
||||
'input_current_limit':'2000000'}.items():self.write(self.charger/name,value)
|
||||
for name,value in {'capacity':'76','current_now':'500000','present':'1','calibrate':'untouched'}.items():
|
||||
self.write(self.battery/name,value)
|
||||
|
||||
def write(self,path,value):path.write_text(str(value)+'\n')
|
||||
|
||||
def call(self,action='get',data=None,board='u30air'):
|
||||
cmd=['docker','exec','-i',self.container,'env','MU300_CHARGE_CONFIG=/fixture/config',
|
||||
'MU300_CHARGE_SYS=/fixture/power','MU300_CHARGE_STATE=/fixture/state.json',
|
||||
'MU300_CHARGE_TYPEC=/fixture/typec','MU300_CHARGE_DEVICE='+board,
|
||||
'/usr/bin/ucode','/feature/usr/libexec/unisoc-modem/charge.uc',action]
|
||||
r=subprocess.run(cmd,input=json.dumps(data or {}),capture_output=True,text=True,timeout=15)
|
||||
self.assertEqual(r.returncode,0,r.stderr)
|
||||
result=json.loads(r.stdout)
|
||||
self.assertEqual((self.charger/'input_current_limit').read_text().strip(),'2000000')
|
||||
self.assertEqual((self.battery/'calibrate').read_text().strip(),'untouched')
|
||||
return result
|
||||
|
||||
def configure(self,**change):
|
||||
return self.call('configure',dict(enabled='1',start='70',stop='80',**change))
|
||||
|
||||
def test_default_read_only_and_no_battery_boards(self):
|
||||
self.assertTrue(self.call()['available'])
|
||||
self.assertFalse((self.fixture/'state.json').exists())
|
||||
for board in ('f50','v50','unknown'):
|
||||
self.assertFalse(self.call(board=board)['supported'])
|
||||
self.assertEqual(self.call('pause',board=board)['error'],'charge_unavailable')
|
||||
self.assertEqual((self.charger/'charge_type').read_text().strip(),'Fast')
|
||||
|
||||
def test_limit_hysteresis_and_persistence(self):
|
||||
self.write(self.battery/'capacity',90)
|
||||
self.assertTrue(self.configure()['stopped'])
|
||||
self.assertEqual((self.charger/'charge_type').read_text(),'N/A')
|
||||
self.write(self.battery/'capacity',75)
|
||||
self.assertTrue(self.call('apply')['stopped'])
|
||||
self.write(self.battery/'capacity',70)
|
||||
self.assertFalse(self.call('apply')['stopped'])
|
||||
self.assertEqual((self.charger/'charge_type').read_text(),'Fast')
|
||||
self.assertTrue(self.call()['enabled'])
|
||||
|
||||
def test_manual_pause_resume_and_boot_apply(self):
|
||||
self.assertTrue(self.call('pause')['paused'])
|
||||
(self.fixture/'state.json').unlink()
|
||||
self.write(self.charger/'charge_type','Fast')
|
||||
self.assertTrue(self.call('apply')['stopped'])
|
||||
self.assertEqual((self.charger/'charge_type').read_text(),'N/A')
|
||||
self.assertFalse(self.call('resume')['stopped'])
|
||||
|
||||
def test_charge_once_returns_to_limit_after_real_full(self):
|
||||
self.write(self.battery/'capacity',95)
|
||||
self.assertTrue(self.configure()['stopped'])
|
||||
self.assertFalse(self.call('full_once')['stopped'])
|
||||
self.write(self.battery/'capacity',100)
|
||||
self.write(self.charger/'status','Charging')
|
||||
self.assertTrue(self.call('apply')['full_once'])
|
||||
self.write(self.charger/'status','Full')
|
||||
full=self.call('apply')
|
||||
self.assertFalse(full['full_once']);self.assertTrue(full['stopped'])
|
||||
|
||||
def test_disable_limit_releases_owned_pause(self):
|
||||
self.write(self.battery/'capacity',90)
|
||||
self.configure()
|
||||
result=self.call('configure',dict(enabled='0',start='70',stop='80'))
|
||||
self.assertFalse(result['stopped'])
|
||||
self.assertEqual((self.charger/'charge_type').read_text(),'Fast')
|
||||
|
||||
def test_bad_input_does_not_change_config_or_hardware(self):
|
||||
initial=(self.config/'mu300-charge').read_bytes()
|
||||
for body in [dict(enabled='1',start='80',stop='80'),dict(enabled='1',start='1',stop='80'),
|
||||
dict(enabled='1',start='70',stop='101'),dict(enabled='1;reboot',start='70',stop='80'),
|
||||
dict(enabled=True,start='70',stop='80')]:
|
||||
self.assertFalse(self.call('configure',body)['ok'])
|
||||
self.assertEqual((self.config/'mu300-charge').read_bytes(),initial)
|
||||
self.assertEqual((self.charger/'charge_type').read_text().strip(),'Fast')
|
||||
|
||||
def test_otg_source_keeps_pause_until_power_sink_returns(self):
|
||||
self.call('pause')
|
||||
self.write(self.charger/'usb_type','SDP [ACA]')
|
||||
result=self.call('resume')
|
||||
self.assertTrue(result['pending'])
|
||||
self.assertEqual((self.charger/'charge_type').read_text(),'N/A')
|
||||
self.write(self.charger/'usb_type','[SDP] ACA')
|
||||
self.assertFalse(self.call('apply')['stopped'])
|
||||
self.assertEqual((self.charger/'charge_type').read_text(),'Fast')
|
||||
|
||||
def test_unavailable_battery_is_not_a_percentage(self):
|
||||
self.write(self.battery/'capacity','invalid')
|
||||
self.assertIsNone(self.call()['capacity'])
|
||||
self.assertEqual(self.call('pause')['error'],'charge_unavailable')
|
||||
|
||||
def test_real_watch_receives_events_and_checks_soc_without_events(self):
|
||||
docker=['docker','exec',self.container]
|
||||
subprocess.run(docker+['/bin/sh','-c','mkdir -p /var/run/ubus; /sbin/ubusd >/tmp/charge-ubus.log 2>&1 &'],check=True)
|
||||
for attempt in range(30):
|
||||
if subprocess.run(docker+['ubus','list'],capture_output=True).returncode==0:break
|
||||
time.sleep(.1)
|
||||
else:self.fail('Fixture ubus did not start')
|
||||
self.write(self.battery/'capacity',90)
|
||||
self.configure()
|
||||
command=('echo $$ > /fixture/watch.pid; exec env MU300_CHARGE_CONFIG=/fixture/config '
|
||||
'MU300_CHARGE_SYS=/fixture/power MU300_CHARGE_STATE=/fixture/state.json '
|
||||
'MU300_CHARGE_TYPEC=/fixture/typec MU300_CHARGE_DEVICE=u30air '
|
||||
'/usr/bin/ucode /usr/libexec/unisoc-modem/charge-watch.uc')
|
||||
watcher=subprocess.Popen(docker+['/bin/sh','-c',command],stdout=subprocess.PIPE,stderr=subprocess.PIPE)
|
||||
def wait_for(predicate,seconds):
|
||||
deadline=time.monotonic()+seconds
|
||||
while time.monotonic()<deadline:
|
||||
if watcher.poll() is not None:
|
||||
self.fail(watcher.communicate()[1].decode())
|
||||
if predicate():return
|
||||
time.sleep(.1)
|
||||
self.fail('Charge policy did not react in time')
|
||||
try:
|
||||
wait_for(lambda:(self.fixture/'watch.pid').exists(),3)
|
||||
# Wait only in the fixture for the listener registration.
|
||||
time.sleep(.3)
|
||||
self.write(self.battery/'capacity',70)
|
||||
subprocess.run(docker+['ubus','send','mu300.charge','{}'],check=True)
|
||||
wait_for(lambda:(self.charger/'charge_type').read_text()=='Fast',3)
|
||||
# Real FGU percentages do not generate regular change events.
|
||||
self.write(self.battery/'capacity',90)
|
||||
wait_for(lambda:(self.charger/'charge_type').read_text()=='N/A',33)
|
||||
finally:
|
||||
if (self.fixture/'watch.pid').exists():
|
||||
subprocess.run(docker+['/bin/busybox','kill','-TERM',(self.fixture/'watch.pid').read_text().strip()],check=False)
|
||||
watcher.communicate(timeout=5)
|
||||
self.assertEqual(watcher.returncode,0)
|
||||
|
||||
|
||||
if __name__=='__main__':unittest.main()
|
||||
Reference in new issue
Block a user