feat: backport event-driven MU300 services and boot optimizations

Integrate native AT and system service ownership, event-driven recovery and dashboard RPCs, boot and PCIe improvements, manual dual-SIM controls, U30 Air LEDs and shared TTL controls.

Fix event timeout misclassification and include regression coverage, build integration and hardware validation reports.
This commit is contained in:
kanoqwq committed 2026-10-23 21:28:24 +08:00
1 parent 04294c7be9
commit f0b5ad43df
153 files changed
+11134 -3477

No files matched your search

+9
View File
@@ -14,6 +14,15 @@
differences in the model profiles, and do not call an offline test a successful
hardware validation.
# Backport architecture
- Fully replace a migrated operation or keep its original implementation until
the rewrite is complete. Do not add availability/version probes that silently
select an older backend, RPC or algorithm after the new one fails.
- Keep platform/model choices explicit. Validate required dependencies and
report failures directly; retain safety checks and recovery within the chosen
implementation.
# Local builds and release packaging
- Read `docs/LOCAL-BUILD.zh-CN.md` before a local build or release. Use the
+26 -7
View File
@@ -7,7 +7,8 @@
export PATH=/bin:/sbin HOME=/root TERM=vt100
mount -t proc proc /proc
mount -t sysfs sysfs /sys
echo 7 > /proc/sys/kernel/printk
# Errors stay on UART; informational records stay in dmesg.
echo 4 > /proc/sys/kernel/printk
# the custom kernel has devtmpfs; fall back to tmpfs + mknod for safety
if ! mount -t devtmpfs -o mode=0755 devtmpfs /dev; then
mount -t tmpfs -o mode=0755 tmpfs /dev
@@ -20,6 +21,9 @@ fi
pmsg_major=$(awk '$2=="pmsg"{print $1}' /proc/devices)
[ -n "$pmsg_major" ] && [ ! -e /dev/pmsg0 ] && mknod /dev/pmsg0 c "$pmsg_major" 0
# Start entropy initialization without blocking PID 1.
if [ -c /dev/random ]; then head -c 1 /dev/random >/dev/null 2>&1 & fi
log() {
echo "<3>MU300-LINUX: $*" > /dev/kmsg
[ -c /dev/pmsg0 ] && echo "MU300-LINUX: $*" > /dev/pmsg0
@@ -161,13 +165,19 @@ detect_linux_slot() {
return 1
}
find_partitions() {
for n in $(seq 1 20); do
# Port the readiness-driven eMMC wait from liuwang97/boot-speed. Keep the
# original twenty-second bound even when this busybox lacks usleep.
local attempts=20 scan_every=1 fast_wait=0
if usleep 0 2>/dev/null; then
attempts=200; scan_every=10; fast_wait=1
fi
for n in $(seq 1 "$attempts"); do
for u in /sys/class/block/mmcblk*p*/uevent; do
grep -qx PARTNAME=misc "$u" 2>/dev/null && misc=/dev/$(basename "$(dirname "$u")")
done
[ -b "$misc" ] && break
sleep 1
mdev -s
if [ "$fast_wait" = 1 ]; then usleep 100000; else sleep 1; fi
[ $((n % scan_every)) != 0 ] || mdev -s
done
[ -b "$misc" ] || misc=
detect_linux_slot || { bootdev=; return 1; }
@@ -282,7 +292,7 @@ setup_usb_gadget() {
[ -z "$udc" ] && for u in /sys/class/udc/*; do [ -e "$u" ] && { udc=$(basename "$u"); break; }; done
log "stage=udc udc=${udc:-none} available=$(ls /sys/class/udc 2>/dev/null | tr '\n' ',')"
persist
sleep 1
# UDC discovery above is the readiness condition.
# Never rebind the gadget from a shell running on its own ACM console: the console dies with the unbind and the
# rebind never runs, which leaves the device with no USB at all until it is power-cycled.
log "stage=usb-bind-start"
@@ -585,6 +595,12 @@ if [ "$root_mounted" = 1 ] && rootdir=$(pick_root) && [ -n "$rootdir" ]; then
*) [ -z "$sd_root" ] || echo "$sd_root" > /run/mu300-root-dev ;;
esac
echo "$DEVICE" > /run/mu300/device
# Parallel page-cache warmup; retain normal procd module loading and failsafe.
prefetch=
if [ -d "$rootdir/lib/modules/$(uname -r)" ]; then
(cd "$rootdir/lib/modules/$(uname -r)" && exec cat -- *.ko) >/dev/null 2>&1 </dev/null &
prefetch=$!
fi
init=/sbin/init
[ -x /newroot/lib/systemd/systemd ] && init=/lib/systemd/systemd
# Mainline cpufreq is now modular so an updated rootfs can read a saved
@@ -600,8 +616,11 @@ if [ "$root_mounted" = 1 ] && rootdir=$(pick_root) && [ -n "$rootdir" ]; then
fi
log "stage=switch-root root=$rootdir init=$init os=$(sed -n 's/^PRETTY_NAME=//p' /newroot/etc/os-release)"
persist
kill $(jobs -p) 2>/dev/null
for p in /proc/[0-9]*; do [ "${p#/proc/}" = 1 ] || kill -9 "${p#/proc/}" 2>/dev/null; done
for child in $(jobs -p); do [ "$child" = "$prefetch" ] || kill "$child" 2>/dev/null; done
for p in /proc/[0-9]*; do
p=${p#/proc/}
[ "$p" = 1 ] || [ "$p" = "$prefetch" ] || kill -9 "$p" 2>/dev/null
done
# Trial guard, only in images built with --trial-guard SECONDS (tools/flash-trial.sh experiments, never an
# install): the timer above ends here, and a trial kernel that boots but never brings up USB (6.18 on the U30
# Air) left a device that only failing five boots by hand brought back. So one more timer outlives
+9
View File
@@ -0,0 +1,9 @@
# AT 终端等待调整
`mu300-modemd` 在正常回复后的每次命令前等待通道安静,原值为 100 ms,现为 50 ms。超时后的 1000 ms 隔离、最大排空时间、单一物理 owner、SIM 序列互斥和原有重开条件不变。前端 AT RPC 设置 `nobatch`,避免交互命令额外等待合批。
网页记录的是 HTTP/RPC、脚本、命令队列和模组响应的总时间。用户反馈的 209–226 ms 不能全部归因于模组;本次确认并减少了固定排空等待及合批等待,没有将页面数字改成较小的虚假值。
在已有 `mu300-event-tests` 原生测试环境运行 `test_modemd`,35 项全部执行通过,包括新增的 50 ms 正常派发测试、迟到回复与超时、短信事件、SIM 缓存、互斥和 ubus 收集。日志:`out/build-logs/20261023-081022-modem-at50-native-93057/command.log`。最初宿主机缺少 ucode 的运行跳过了测试,未算作成功验证;上述结果来自实际执行的容器测试。
本轮没有连接 MU300 实机,没有断言其网页或基带往返已降至 50 ms,也没有修改设备、构建发行包或提交 Git。需要后续实机验证端到端延迟及长期运行稳定性。
+57
View File
@@ -0,0 +1,57 @@
# 蜂窝 TTL 页面移植与验证
## 范围
页面参考 `dikeckaan/mu300-linux` 上游 `eab1802f` 的
`openwrt/luci-app-mu300/htdocs/luci-static/resources/view/mu300/ttl.js`。
保留 MIT 许可,随应用安装到 `/usr/share/licenses/unisoc-ttl/MIT`。
E5 与 MU300 使用相同的页面、JSON 适配器、规则引擎和服务脚本。
- 入口:蜂窝 → TTL,提供 64、65、128、自定义 1–255 和关闭。
- 默认关闭;设置保存在 `/etc/mu300/ttl.conf`,兼容 MU300 已有 CLI 配置。
- 应用启动、WAN 重连、系统重启均重新应用保存的设置。
- LuCI 包安装注册服务,移除前清理规则;E5 公共 UI staging 和 MU300
rootfs 构建同时注册启动项。Ubuntu 原有 CLI 保留,OpenWrt CLI 转交同一引擎。
- 中、英、土三语;提交期间禁止重复点击,失败和断线明确提示。
## 规则与约束
本次 OpenWrt 实现明确使用 nftables,不运行 tc 能力探测,也不在错误后切换后端。
只修改 `inet mu300_ttl` 表,仅匹配蜂窝出口 `sipa_eth*`,同时设置 IPv4 TTL
及 IPv6 hop limit。批量替换规则为一个 nft 事务,不刷新其他表。
flow offloading 会绕过 postrouting,启用 TTL 时必须关闭软件和硬件流量卸载。
只记录由本功能从 1 改为 0 的选项,关闭时恢复这些选项;用户原本关闭的选项
保持关闭。该性能影响在应用设置前可见。fw4/uci/nft 出错不能返回成功。
使用 BusyBox 支持的 `flock -n` 互斥;第二个写入立即返回忙碌,用户可以重试。
新值只有在应用成功后才原子保存,规则失败不覆盖此前保存的值。
## 自动化验证
两仓库各运行 `python3 openwrt/tests/ttl.py -v`,每仓库 9 项通过:
IPv4/IPv6 规则作用域、输入校验、保留原先关闭的卸载选项、原子规则失败、
fw4 reload 失败后重试、uci 失败、进程重启恢复、默认关闭、并发互斥。
两仓库各运行 `node openwrt/tests/dashboard-ttl.js`,覆盖三语、非法输入、
重复提交、失败提示、保存后刷新及电源卡片实际渲染代码。
E5 公共 staging 测试通过,覆盖六个机型配置。
## 实机验证与边界
2026-10-23,仅在经过 SSH host key、机型和 eMMC 身份核对的 E5 上部署。
真实 RPC 读取成功;TTL 64 的 IPv4/IPv6 规则成功创建、读取、删除;
蜂窝 IPv4 ping 3/3,规则计数器实际增加 3 个包。测试后 TTL 关闭,规则清除。
没有建立 IPv6 外部连接,故不把 IPv6 语法/安装验证称为 IPv6 数据面验证。
MU300 本轮只有自动化和构建路径检查,没有连接其硬件部署。
E5 的卸载选项原本未开启,卸载关闭/恢复分支本轮通过隔离测试验证。
## 电源卡片
E5 同步 MU300 现有的电量条及带正负号的电池净电流,不将 USB 在线当成
正在充电。无电池时显示 USB/未知,隐藏电量条。电压统一保留两位小数,
修正 ucode 浮点序列化后出现 `3.7999999999999998 V` 的显示问题。
本轮实机返回 Charging、净电流 +12 mA;未进行拔 USB 后的放电实测。
本次未组装新的系统/安装器发布包,未提交或推送工作区更改。
@@ -0,0 +1,313 @@
# liuwang97 分支移植核查
当前架构以文末第六批为准:已移植的 OpenWrt 操作直接使用新实现,前四批新增的版本探测、自动后端切换和旧实现接管已删除。前四批保留为历史验证记录,不是当前运行/恢复指南。当前维护说明见 [MODEMD.md](MODEMD.md)。
2026-10-23 核查结论:可以移植,但需要按功能回移植并处理本地接口差异,不能直接整分支合并,也不能把无文本冲突等同于功能兼容。两个固定分支的适用优化已按本地功能完成处理,并接入 OpenWrt 构建路径;当前实现、明确不采用的行为变化及最终验证见第六批。尚未实机验证启动时间、功耗及硬件恢复行为。
后续实机补充:#373 已在用户连接的 U30 Air / 7.2.8 部署并验证 USB cluster-idle
唤醒、卸载恢复和重新加载,见 [实机报告](U30AIR-LPINTC-LIVE-20261023.zh-CN.md)。
随后按用户要求完成整批部署:207 份运行时、7.2.8 新内核及 202 个模块,完成冷启动、
看板/浏览器 RPC、AT 独占、daemon 恢复、小核调度和蜂窝联网验证,见
[完整实机报告](U30AIR-FULL-BACKPORT-LIVE-20261023.zh-CN.md)。功耗、其他机型及系统
suspend 仍未实测;物联卡不具备本次短信收发实测条件。
## 固定的核查版本
| 角色 | 提交 |
| --- | --- |
| 本地 `clean-tf-7.2` | `04294c7be924180ba69229725c67036e28a9b1cc` |
| 对方 `cpu-load` | `ccf89bb65e283f1c609f507f4c51585b929b6e99` |
| 对方 `boot-speed` | `1fb42bebd75a0dfdfa9493cf4d1069e430ad7f1e` |
| 两个优化分支的共同基线 | `3280409500ea21a639bac22c1e11c090a64d49e1` |
来源:[cpu-load](https://github.com/liuwang97/mu300-linux/tree/ccf89bb65e283f1c609f507f4c51585b929b6e99)、[boot-speed](https://github.com/liuwang97/mu300-linux/tree/1fb42bebd75a0dfdfa9493cf4d1069e430ad7f1e)。对方 `main` 仍在较早版本,不能用 main 与优化分支之间的整段历史作为待挑选集合;那会混入大量上游更新。应先围绕共同基线后的优化提交分析,再为必要依赖单独选取提交。
本地仅新增 `refs/remotes/liuwang97/*` 引用,没有修改 origin/upstream 配置、工作分支或现有提交历史。核查开始时本地工作区干净。
## 候选内容及迁移条件
| 范围 | 主要提交 | 核查结果 |
| --- | --- | --- |
| C AT I/O 桥 + ucode 调度 | `e054f410` | 有完整实现和测试。桥持有 SIPC 描述符,调度器重启不关闭端口;保留原 FIFO/答案文件兼容接口。需适配本地 AT 初始化、额外通道、短信池和各机型启动条件。 |
| rpcd 常驻状态与小区解析 | `e054f410` | 用 ucode 解析和常驻 rpcd 方法减少页面刷新引发的进程。必须对照现有 LuCI JSON、ACL、API 超时、SIM 范围及 APN/短信功能;不能只复制前端调用。 |
| 合并按键、LED、温控观察 | `e054f410`、`ccf89bb6` | `mu300-sysd` 与新 keys helper 通过事件联动。对方使用 `/etc/mu300/sysd` 可选启用,并保留轮询兜底;本地没有相同的 mu300-power 服务布局,需将本地 U30 Air 充电、低电保护及用户策略接入。 |
| 短信、NDP、数据观察等减进程 | `e054f410` | 适合分项移植。对方部分文件位于 `openwrt/luci-overlay/opt/mu300/bin`,本地短信在 `rootfs/overlay/opt/mu300/bin`,NDP 在 `openwrt/overlay/opt/mu300/bin`。目录不同只是一部分,接收池和缓存语义也必须保留。 |
| 早期记录器降开销 | `374ed7bf` | 小核亲和、日志尾部及分阶段采样间隔可以独立评审;减少采样意味着诊断时间分辨率有变化。 |
| 内核、initramfs、无线启动顺序 | `ed5063e7`、`c3566b8e`、`cd36c245` | 可分开移植。保留本地 TF 选择、动态槽位、安装/卸载及缩容事务保护;需实测 USB 枚举、Wi-Fi 初始化、重连及回退。 |
| 首轮 kmodloader 跳过 | `95c3f641` | 通过临时 bind mount 的自移除脚本跳过 procd 的 modules-boot 扫描。必须核对本地两条内核发行线的 modules-boot 与 modules.d 覆盖;不宜无条件启用。 |
| AT 计时回退 | `bc83e4ee`、`8ec04d68` | 对方已经撤回前面的部分 `/proc/uptime` 计时修改。移植应使用分支最终状态,不能只挑最初的提速提交。 |
| 热事件与调度配置 | `91c70ea8` | 增加 UCLAMP 与 THERMAL_NETLINK。配置变化需要重编相应内核;不能只替换用户态就宣称温控事件路径可用。 |
| USB gadget os_desc 生命周期 | `aca08bd6`、`1fb42beb` | 用户态保留描述符与内核解绑清空指针是配套修复,应与本地近期 NCM TX 修复共同回归,不能覆盖后者。 |
## 已有的 PCIe 修复不要反向覆盖
对方共同基线之前的 `89ce5073abba84201902ab52b75bf700aaa804b5` 明确注明其 RX push 修改来自本地 `2d3f7438`,属于我们已做过的修复。当地维护分支的 EDMA、Wi-Fi PCIe/RX 文件还包含其他后续调整,因此不能用对方整文件覆盖。
需要分别核对 EDMA 完成描述符交付、RX refill 恢复、空闲中断及启动时链路等待。优化分支中的 PCIe 启动改动主要是避免等待尚未上电的端点,不等同于已经验证所有 PCIe 中断或待机功耗问题。
## 三方应用检查
以两个优化分支共同基线分别导出最终 diff,在干净本地 HEAD 执行 `git apply --check --3way`:
- cpu-load:59 个变化文件,无法干净应用,存在冲突和缺失路径。
- boot-speed:14 个变化文件,有 7 个文件报告内容冲突,包括 init、硬件启动、AT 和数据路径。
- `--check --3way` 在 boot-speed 这次检查中虽然返回 0,仍打印 `with conflicts`;核查同时分析诊断,未把返回 0 误认为可无冲突 cherry-pick。
应用检查没有真正应用 patch、写入冲突标记或改动业务代码。原始 patch、诊断和版本清单在 git 忽略的 `work/liuwang97-audit-20261023/`。
## 已执行测试
从固定的 cpu-load 提交仅导出 C 桥和测试所需的文件到调查目录,使用 WSL 主机编译器运行作者的真实测试:
- 19 项 C 桥行为测试通过:PTY 收发、FIFO、半行提示、TX 超时、SIPC ENODATA/非终端行为、客户端更换与阻塞、断开仍保持描述符、队列上限、单实例、退出以及空闲不唤醒。
- 1 项构建接线测试在补齐导出的安装/构建脚本后通过。前两次完整调用的该项因调查目录缺少脚本失败,属于导出夹具不完整,并非已发现的上游产品缺陷;日志保留。
测试经现有 `tools/build-release.py run` 记录在 `out/build-logs/`,没有克隆内核、创建 Docker volume、组装 rootfs、生成安装包或访问设备。没有运行 ucode 调度器、rpcd、新电源/短信服务的完整测试,也没有测量本地设备启动时间或电流;C 桥的测试通过不代表这些路径已经验证。
## 效果与兼容边界
对方 FINDINGS 205–208 包含 U30 Air 的 CPU tick、启动和事件实验,具有参考价值,但不能推广成我们所有机型的实测结果。其实现也保留了取舍:例如短信安全同步由高频改为较长间隔,漏通知后的最长发现时间会增加;充电状态没有可靠 uevent 时仍保留 30 秒检查,电池状态另有安全兜底。迁移必须明确这些延迟,而不是把“无轮询”当作独立目标。
推荐分成 AT 桥/调度、rpcd 状态、系统事件、电源与内核启动四批,每批保留来源提交信息,建立独立回归并保持可回退。涉及 SIPC owner 的切换只能在冷启动时选择,不能在运行中的调制解调器上随意重开通道。保留本地安装器、Magisk、TF、双内核发行线、机型配置和既有恢复流程,不恢复已经取消的机型支持。
## 维护分支移植进度(2026-10-23)
### 已实现并接入
- C 桥与 ucode AT 调度从固定 cpu-load 版本移入维护目录,保留原 CLI/FIFO 接口。首次冷启动按组件可用性选择后端,并将选择固定在 `/run/mu300/at-backend`;已有活跃 shell owner 的系统不会因升级新增第二个读者。
- 保留本地 NR6/7 通道、双卡 NR3 归属、U30 sbuf 前置条件和禁止重开/respawn 的规则。ucode 可重启接管 C 桥;它退出时保留物理 owner 标记。
- 直接短信仍按物理 SIM 写入原有自定义池;NR6/7 归属 SIM0,NR3/4/5 归属 SIM1。PDU 只走 spooler stdin,不出现在事件及日志中。
- 新增原生 SIM/注册状态缓存,保持 `registration.sh` 的文件及事件协议,保留未供电 SIM、PIN/PUK、忙碌和热插卡语义。V50 网络灯仅在对应硬件节点存在时通知。
- 原有 LuCI 采集入口继续使用。新增按需 ubus 采集适配了本地号码刷新、启动身份缓存、只读 CSCS/COPS、完整 LTE 邻区频段、NR 原生数组与 n77/n78 歧义、QoS 校验、V50 代际回写保护;现已由原看板 RPC 的刷新入口优先调用常驻采集,保留旧服务和自定义适配器回退。
- 两条 rootfs 组装路径、通用安装构建、发布及 TF/Magisk 包检查均接入新组件。ARM64 静态 helper 已编译到登记输入路径,676304 字节;源码/二进制哈希、ELF 架构与静态链接检查阻止旧输入混入。
- keys helper 合入 `-u` 内核事件订阅,保留本地 `-c` 充电等待行为;溢出和截断要求消费者重新检查状态。合并 sysd 已在 OpenWrt 冷启动路径接入,缺少依赖或旧组件被禁用时保留旧服务;Ubuntu systemd 路径不切换。
- early-recorder 合入小核亲和选择及 dmesg 缓冲优化,保留本地动态 Linux 槽、持久化位置及原采样间隔。
- 从 boot-speed 移入 USB NCM/RNDIS `os_desc_table` 解绑清空修复,保持本地 NCM 忙碌定时重试补丁;启用 UCLAMP/THERMAL_NETLINK 编译配置。内核未重编,现有设备尚不包含这些内核改动。
### 本轮验证
所有有编译产物的测试/构建均通过 `tools/build-release.py run`,没有组装安装包或刷写设备。ucode 测试在现有 OpenWrt ARM64 基础镜像的临时运行容器内使用真实 ucode/uloop/socket/ubus,调制解调器应答由夹具提供。
| 验证 | 最终结果 | 日志目录(均位于 `out/build-logs/`) |
| --- | --- | --- |
| AT 客户端、初次打开及 C 桥 | 32 项通过 | `20261023-021144-event-at-regression-75444` |
| 新旧充电等待及 keys 事件解析 | 6 项通过 | `20261023-021348-event-keys-regression-76093` |
| 原有 SIM 事件、短信池、U30 启动与构建边界,含新组件选择与指纹 | 38 项通过 | `20261023-021740-event-local-regression-76221` |
| 真实 ubus 按需采集、mux 中止、号码/身份、缓存及解析 | 15 项通过 | `20261023-021806-event-ucode-regression-78495` |
| 最终构建接线、指纹及启动布局 | 7 项通过 | `20261023-022035-event-final-wiring-78526` |
| recorder 小核拓扑与缺失节点降级 | 1 项通过 | `20261023-022105-event-recorder-regression-78656` |
| ARM64 静态桥交叉编译及指纹 | 通过 | `20261023-020842-event-at-arm64-75384` |
| 7.2.8 NCM/RNDIS 实际解绑清理代码 | 两种功能的重复解绑测试通过 | `20261023-021712-event-usb-descriptors-76173` |
| 原 NCM 定时重试及 TX/完成生命周期 | 含 10000 次忙碌重试通过 | `20261023-021721-event-usb-ncm-regression-76195` |
最初的全量基线为 867 项,34 个失败、39 个错误、33 个跳过,并非全绿;其中包括将需显式内核参数的脚本当 unittest 模块加载、缺少本地内核夹具,以及既有测试/宿主环境问题。保留原日志 `20261023-015340-liuwang-baseline-82063`,不将它们统计成移植通过项,也没有为得到全绿而删除用例。迁移过程还发现并修复了 ucode 正则语法、函数声明顺序和 JSON 空白导致身份缓存未命中;相关失败日志保留,以上列出修复后的通过结果。
尚未进行设备功能、启动时间、中断计数或功耗实测;6.18 内核修复也未编译验证。测试容器的包安装属于临时测试环境,未加入设备系统载荷。
### 第一批结束时尚待迁移
完整 rpcd 常驻系统快照、页面状态事件调用、其余 initramfs/PCIe 启动优化仍需继续。NDP/数据观察已在第四批按本地语义接入。不能将当前迁移称为两个优化分支的完整移植。尤其不直接采用对方较长的短信兜底间隔,不无条件跳过首轮 kmodloader,也不覆盖本地安装/卸载、动态 A/B、分区事务或已有 PCIe 中断修复。
## 第二批:短信事件与常驻采集接入
- `mu300-smsd` 接入根据 cpu-load 事件等待方式适配的 `lib/sms-events.sh`。不替换现有短信导入、原始 PDU 保存、CNMA 确认和三次失败回退逻辑;继续使用 300 秒兜底归档,不采用对方的 1800/600 秒间隔。
- 消费者只接收自己的物理组:SIM0 的 NR0/1/2/6/7,SIM1 的 NR3/4/5;原生 SIM 缓存事件同样按槽过滤。其他组及普通注册事件不移动归档截止时间,也不触发反复扫描日志。
- 初次等待前立即处理已有 spool,导入失败保留原文件且不发 CNMA,事件流退出自动恢复旧轮询;进程退出清理其监听子进程。正常空闲等待仍保留原安全归档期限,不会按事件次数提前或延后计时。
- 原 `mu300dash status/cells` 保持接口与刷新间隔,内部优先使用新增的 `mu300.modem.collect`。选择 SIM 的参数不可被旧版 `cell` 方法静默忽略,旧服务不支持新方法时回退原 worker;自定义输出目录/AT 适配器也保留旧入口。
- 新采集协议的每个请求都原子添加 SPACTCARD,避免把“当前上网卡”当作“用户正在查看的卡”;SIM1 不回退 NR1,缓存及身份目录与本地 sim-scope 相符。完整阶段保留早期信号、邻区完成以及最终身份结果发布。
- shell/native 采集器互相识别活动锁,避免原脚本误把常驻 daemon 当死进程;切卡代际检查、用户锁设置窗口和 AT 互斥均继续生效。无应答会发布错误并停止后续身份/号码查询。
这一批仍只验证离线夹具及真实 ucode/ubus 运行时,没有打包、重编内核或访问设备。
### 第二批最终验证
| 验证 | 结果 | 日志目录(`out/build-logs/`) |
| --- | --- | --- |
| 原生采集、SIM 作用域、短信事件与导入失败重试、监听退出、注册解析 | 46 项通过 | `20261023-023749-resident-events-final-80284` |
| 原看板、短信容量/池、SIM/AT 边界兼容 | 63 项通过 | `20261023-024438-resident-events-compatibility-final-91050` |
| 实际 ARM64 C 桥 + ucode + 原 CLI,排队请求接管、描述符不关闭、CMT 隐私 | 1 项通过 | `20261023-024240-modem-pipeline-real-80380` |
早期真实管线用例曾把“输出文件已打开”误作“写入已完成”,修正测试等待条件后通过;原失败日志保留。未测试任意已经发往基带、结果未知的命令自动重放,这类命令不能盲目重试。
## 第三批:系统服务合并与常驻网速采样
- 新增 ucode `mu300-sysd`,将按键、LED 到期检查、温控放入一个事件循环。沿用本地 U30 双击、普通机型单击、长按热点/关机、五秒检查、原厂内核只告警、主线紧急关机及按 policy 管理用户频率上限,不引入对方额外限频或较长温控间隔。
- keys/helper 用 `-u power_supply,extcon` 接收内核事件,LED 仍由原 helper 判断用户样式和超时。首次冷启动固定 sysd/legacy 选择,旧组件已被用户禁用时不会借合并服务重新启用。新增单实例锁、正常退出清理及死 PID 接管;旧启动入口按同一选择跳过相应循环,防止两个按键读者或温控写者。
- 编译 keys ARM64 静态二进制到登记输入(661064 字节),与 AT bridge 共用构建配方、源码/二进制指纹及架构/静态链接检查。没有生成固件或桌面包。
- `mu300rates.rates` 常驻 rpcd,和原 `dashboard-rates` 共用采样模块。保留当前 WAN 优先、双卡实际网口、原字段、时间基准和重置识别;不采用对方返回整个 `/proc/net/dev` 的协议。只增加固定只读方法授权,无任意路径输入。旧 rpcd 走原入口,页面刷新才重新探测原生对象。
- APK 与直接 rootfs 两条路径都新增 rpcd ucode 依赖并设置 0644 插件权限。真实运行发现 Windows 挂载文件的可写权限会导致 rpcd 拒绝加载,已修复构建权限。
- initramfs 的 eMMC 等待移入更细就绪检查;仍等待实际 misc,再使用原动态槽位判断。支持 usleep 时每 100 ms 检查,缺失或不支持时保持原一秒检查,两个分支均保留原约二十秒上限及 mdev 扫描预算,不复制对方在 usleep 不可用时可能累计二百秒的回退。
| 验证 | 结果 | 日志目录(`out/build-logs/`) |
| --- | --- | --- |
| 原按键/温控测试复用 + 实际 ARM64 keys/ucode,互斥/退出/接管、连续升降温 | 9 项通过 | `20261023-031120-sysd-runtime-deadlines-3150` |
| 启动回退、充电等待、keys 事件、源指纹、原 AT、A/B、eMMC 就绪与超时 | 34 项中 33 通过、1 跳过 | `20261023-031315-sysd-boot-regression-3843` |
| 原生/兼容网速切换、页面调度、计数重置、JS 语法及原看板边界 | 8 项通过 | `20261023-031656-rates-frontend-regression-6548` |
| 真实 rpcd 载入插件、重复采样、兼容 CLI 同一身份、危险路径拒绝,以及 24 项网口夹具与原看板后端夹具 | 2 项集成测试通过 | `20261023-031831-rates-final-compatibility-7459` |
跳过项需要未随仓库分发的原厂 U30 loader。开发中发现并修复温控定时器变量遗漏,保留初次失败日志;新测试验证连续定时周期,避免只测单轮。最初网速模块语法和插件权限失败也保留诊断记录,不作为通过项。没有实机功能或功耗测试,不能声称已降低设备待机电流。
第三批结束时没有套用对方完整 NDP 脚本:它删除了本地邻居路由行为,并改变部分兜底间隔;第四批分别适配事件等待,保留本地路由逻辑。
## 第四批:NDP 与数据看守事件接入
- 根据固定 cpu-load 版本的事件观察方式新增 `ndp-events.sh`、`data-events.sh`,保留本地实际路由操作与恢复判定。不采用对方将兜底延长到 300 秒及路由策略替换的部分:NDP 仍每 10 秒安全检查,数据看守仍每 30 秒检查。这里减少的是等待子进程并提前响应事件,不能据此声称已有同等的空闲 CPU/功耗降幅。
- NDP 监听地址、路由及邻居事件。保留多前缀、邻居 /128、metric 1024、仅撤销离开前缀、三次弃用 RA 和原自愈行为。稳定快照不包含包/引用计数,避免流量被误认为路由变化;吸收自身写入产生的通知,阻止自触发循环。写入期间的新地址和明确删除分别补测,不能被写后快照吞掉。
- 三次弃用 RA 仍按原 10 秒间隔进行,不能因事件密集而连续发完。监听退出/不支持 `ip monitor`、缺少 read 超时或内核表不可读时恢复原轮询,并清理自己的监听进程。
- NDP 复用现有 `mu300-sim-env` 的上网卡与自定义网口映射,修复原固定 sipa_eth0 的路径;配置或已提交槽位变化时刷新映射,未变输入只进行 shell 文件读取,不重复启动 UCI/机型查询。切卡、卡槽状态未知时停止操作;设备名仍经原 mapper 和路径字符检查,不作为任意 sysctl 路径输入。
- 数据看守的事件只唤醒原有检查,不直接重拨或重置射频。仅当前卡 nr0/nr3 的 URC 可触发基带刷新,其他卡及命令应答不触发;SIM 事务事件会让原主循环重新解析上网卡。活动 PDP 地址变化仍请求原地续租,忙碌/空应答不当作断线,保留用户关闭数据及 pending/switching 门控。
- 断线后的第二次确认仍等待原间隔,不能被一串 NO CARRIER/CGEV 事件提前消耗重试预算;无关事件也不能推迟安全期限。Bash 5.3 回归发现异常退出会在 EXIT 前展开局部变量,已将锁清理状态提升至进程范围,并核对 PID 后清理,避免丢失锁路径或删除其他进程替换的锁。
- 两条 rootfs 路径已有共享 lib 拷贝,TF 包验证新增三个库的存在;没有修改桌面安装器、打包产物、Android 分区或设备。
| 验证 | 结果 | 日志目录(`out/build-logs/`) |
| --- | --- | --- |
| dash/Bash 网络行为、双卡切换/回滚、SIM 隔离、网络灯,含实际只读 iproute2 订阅 | 69 项通过 | `20261023-033711-network-events-host-final-27217` |
| ARM64 OpenWrt ash/Bash 5.3、真实 ucode/ubus、完整看守函数与 NDP 进程 | 45 项中 44 通过、1 跳过 | `20261023-033553-network-events-arm64-verified-27188` |
ARM64 跳过项是需显式启用的宿主只读 netlink 订阅检查,已在上一行 WSL 的 iproute2 5.15 中执行。路由/AT 应答及所有潜在网络写操作均使用私有文件或命令夹具,不是实机验证。完整看守测试验证 SIM2 作用域、原地 renew、用户数据关闭、监听退出与替换锁保护;NDP 用例验证运行中切到 SIM2、邻居变化、自己的路由事件不循环、写入期间到达的新地址、删除竞态、计数变化不触发及 RA 间隔。
失败记录保留:初次 ARM64 回归暴露 NDP 写后快照竞态,后续增加确定性并发用例;Bash 5.3 回归暴露 EXIT 局部变量问题,修复后重跑通过。ubus 禁止伪造 `ubus.object.remove`,移除测试改用真实退出 modemd 产生事件。测试容器安装额外 ip-full 时其 libelf 下载校验失败,没有绕过校验;因此不把 ARM64 原生 ip-full 订阅算作通过,实际订阅参数另由 WSL 原生 iproute2 验证。未修改正式依赖源或生成固件。
## 第五批:移除新增的多实现切换
按维护要求,已迁移的操作完整使用新实现;尚未完整迁移的操作保持原写法,不通过运行时探测拼接两套实现。这条规则已写入本仓库 AGENTS.md。
- OpenWrt AT init 只启动 C bridge/ucode。删除旧 shell owner 分支、后端选择标记和禁用标记;必需模块缺失、已有物理 owner 时直接报错,不热切另一套读者。机型布局、U30 sbuf、原 SIM 启动失败处理和原 CLI/FIFO 协议保留。
- OpenWrt 只启用 sysd,删除旧 buttons init 和 post 内的 thermalguard 分支,以及新增的 sysd-service 选择库。Ubuntu 原有 systemd 平台入口保留。
- 页面网速只调用 native rates RPC;后台小区刷新只请求 native collect。删除失败后改调旧 RPC/后台 worker 的代码,失败显示明确的读取错误。原 live-signal 和完整 dashboard-info 尚未整体重写,继续作为各自独立操作的原实现,不充当 native collect 的替代路径。
- OpenWrt SMS/data/NDP 的监听或依赖失败会报错退出,交给同一服务的正常监督处理,不改跑轮询后端。SMS 的平台传输由启动入口明确指定,Ubuntu 原 CLI 默认传输仍保留;周期安全校验、重试间隔、SIM 隔离、用户开关及射频/ACK 恢复规则未删。
- ucode 必需 ubus/UCI 模块改为直接导入;静态 helper 构建要求已指定/安装的 ARM64 编译器,移除找不到编译器后自动切 Docker 的分支。
- 原有测试已按新的实例布局验证物理 owner、通道/短信槽位、显式故障和不启动其他实现;没有删除这些行为覆盖。维护指南移除过时的后端切换/禁用标记说明。
| 验证 | 结果 | 日志目录(`out/build-logs/`) |
| --- | --- | --- |
| 原 CLI、双卡/冷启动、短信池/容量、服务布局、NDP、页面与错误展示 | 135 项通过 | `20261023-035041-native-only-final-regression-54864` |
| ARM64 ucode/ubus、事件故障、按键/温控、实际 helper 生命周期与 native rpcd | 45 项中 44 通过、1 项跳过 | `20261023-034425-native-only-runtime-35538` |
| modem 全部行为与真实 C bridge/FIFO/CLI 管线 | 26 项通过 | `20261023-034804-native-only-modem-pipeline-54835` |
ARM64 跳过项仍为显式宿主只读 netlink 检查,宿主测试已执行。首次综合回归中旧 U30 init 夹具仍依赖已删除的 shell service 布局,改为验证 native 实例、四个通道及 sbuf/no-reopen 后通过。保留失败日志 `20261023-034624-native-only-compatibility-35567`。所有设备应答/写入使用夹具;没有实机操作、固件/安装器构建或打包。
完整系统快照、同步 live-signal 的整体重写及剩余启动优化仍需继续;这些操作在完整替换前维持其原实现。
## 第六批:剩余优化逐项处理
范围仍是前述两个固定提交,不覆盖本地动态 A/B、安装/卸载事务、APN、
双卡、充电及已有 PCIe/EDMA 修复。没有生成固件发布包、安装器或操作实机。
| 优化项 | 当前实现及取舍 |
| --- | --- |
| 完整系统快照 | 新增 `mu300.dash` / `mu300status` 常驻 RPC,完整替换 `dashboard-info` 的 Shell 采集。直接读 proc/sys、UCI、ubus、rtnetlink、nl80211 和 statvfs;APN、热点复用本地模块,无 AT、shell 子进程或配置写入。保留原 JSON 字段、双卡查看范围、当前网口、DNS、客户端、充电、流量和动态启动槽位。 |
| 同步实时信号 | `mu300.modem.signal` 异步应答本次采集,独立临时 round,保留物理通道池和 SIM 代际检查,不读旧缓存冒充实时值、不覆盖后台缓存。12 秒应答截止后保留未结束 AT 的通道占用,避免重试造成重叠。 |
| 短信通知读取 | 新增按物理槽位的 `sms_head`,原生池仅签名变化时获取消息列表,失败不推进签名;查看槽位改变时忽略旧签名响应。显式配置的外部短信适配器继续按原周期读取自身列表,不假定其存储格式。首次基线、消息方向、通知预览保持原功能。 |
| 服务小核亲和性 | 新增 `mu300-service-cpus` 一次性 cpuset 设置,支持 `little/all` 保存及启动应用;检测实际容量和在线核心,不写 CPU 热插拔、DVFS 或 IRQ。依赖失败明确报错。 |
| 电源及充电优化 | 本地已经由 `charge.uc` / `charge-watch.uc`、power_supply hotplug、sysd、内核 charger 驱动实现事件读取及原生策略;保留本地显式用户选择、OTG 门控、低电及温控规则。对方 `mu300-power` 的自动关 Wi-Fi/射频、eco 下线核心和充电阈值策略与本地功能不同,不引入另一套电源所有者。 |
| LED 减进程 | 保留机型灯组、硬件呼吸、告警互斥、用户亮度/超时;将重复 cat/cut 和超时配置 sed 管线改为内建读取。sysd 的五秒安全期限不改。 |
| 流量减进程 | 本地 `traffic` / `traffic-core.uc` 已是常驻 ucode/uloop、直接读取计数、原子检查点和原生日期计算,达到同类优化目的;不再复制对方 Shell 计账循环,保留双 SIM 账本、时区/DST、清空事务及原持久化频率。 |
| ADB 与 USB 用户态 | 本地已无对方 `mu300-adbd` 常驻轮询服务,不重新引入;initramfs gadget 原本就保留 OS descriptors。USB 网络模式/角色继续走本地入口,内核 os_desc 生命周期修复继续保留。 |
| initramfs 启动 | UART 降到错误级输出(完整记录仍在 dmesg)、异步启动随机池初始化、并行预读模块、移除 UDC 已就绪后的固定一秒。保留动态槽位、分区准备、正常模块加载和恢复路径;预读进程单独跨 switch_root 保留。 |
| Wi-Fi 启动 | board 检查及 regdb/country 先于 PHY/WLAN;Wi-Fi 先于额外模块/zram。配置未改变且所有启用接口实际就绪时保留现有 AP;检查所有配置接口,不固定猜 wlan0。未就绪仍执行原来的单次 down/up 修复,不启用用户关闭的无线电。 |
| SIPC / 数据启动 | CP 输出和 broker owner 改为 200 ms 就绪检查,原 60/90 秒预算不变;native radio-ready 改为 200 ms 检查。SIPA delegate 保留实际 packet attach 门控,按真实经过时间限时,握手日志出现即结束等待。没有缩短 SIM 上电后必要等待或改写射频顺序。 |
| PCIe 初次探测 | 仅 probe 的短链路检查及 DesignWare 初始等待开关,分别适配 6.18/7.2 的不同错误处理;configure/resume 保留完整训练等待,原 MSI 清理和 EDMA/RX 修复不覆盖。 |
### 明确不采用的行为改变
- 不跳过 `modules-boot.d` 扫描,不屏蔽 failsafe 按键等待:这会改变模块加载及故障恢复保证;使用并行预读减少冷读开销。
- 不延长短信/NDP/数据看守/温控的既有安全期限,不复制对方低频检查或额外限频策略。
- 不加入版本探测、旧 RPC 接管或事件失败转轮询;CLI/Ubuntu 的原有显式平台入口不充当 OpenWrt 新实现的失败替代。
这些是维护本地行为所作的明确决定,不列为未完成移植项。启动时间、功耗、USB/PCIe
唤醒和各机型硬件功能仍须实机验证,不能沿用对方测量数字作为本分支结论。
### 最终验证(第六批)
| 范围 | 结果 | 日志 |
| --- | --- | --- |
| 原功能、启动顺序、分区等待、灯效、双卡、网络、USB、Node 页面调度及短信通知 | 168 项中 133 通过、35 跳过 | [宿主回归](../out/build-logs/20261023-043505-backport-final-verification-12442/command.log) |
| 实际 ARM64 ucode/ubus/rpcd、完整快照、APN/电池/短信兼容、CLI 保存与重放、modem、keys/sysd 及 rates | 72 项中 71 通过、1 跳过 | [原生综合验证](../out/build-logs/20261023-044200-native-final-runtime-35675/command.log) |
| 最后增补原生所有者保护后的完整 modem 及真实 C bridge/FIFO/CLI 管线 | 34 项全部通过 | [所有权与管线回归](../out/build-logs/20261023-044606-native-owner-regression-35702/command.log) |
| 6.18.54 与 7.2.8 的 Image、DTB、内核模块及 vendor 模块编译 | 两条发行线通过,复用既有源码/对象缓存 | [编译日志](../out/build-logs/20261023-041739-backport-kernel-lines-11950/command.log) |
| Image/config/全部模块 SHA-256 及实际 UCLAMP/THERMAL_NETLINK 配置 | 6.18.54 共 194 个模块、7.2.8 共 201 个模块全部通过 | [产物核验](../out/build-logs/20261023-044837-backport-kernel-evidence-35728/command.log) |
宿主跳过项包括需要原生 ucode 或专用未分发夹具的检查;不是全部仓库测试都已执行或全绿。
本次关键原生路径另在 ARM64 容器执行,唯一跳过的 Node 短信通知用例已在宿主通过。
静态 ARM64 helper 的源码/二进制指纹在宿主回归前检查通过;`git diff --check` 通过。
回归中发现并处理:
- 系统快照的浮点网速格式、Windows 写文件产生的 CRLF 执行问题;新增 Unix 换行入口检查。
- 实时信号回调的声明顺序;新测试实际执行请求、缓存隔离、SIM 代际中断及并发拒绝。
- `/proc/<pid>/cmdline` 的 NUL 分隔处理影响采集锁识别。现在直接识别本进程,并正确拆分其他进程参数;同进程多请求及外部采集器持锁均已验证。
- 原生 AT 请求的锁所有者是常驻 daemon,不能按一次性 CLI 的墙钟期限回收或杀死。新增明确保护,并通过将测试锁期限设为过期来验证本进程和另一个原生所有者都保持存活;不修改宿主时钟。
- 连接数仅在旧内核没有标量计数器时分块扫描,避免将大连接表一次读入内存;覆盖跨 4096 字节边界的计数。
- 夹具中的 DHCP 剩余时间会自然跨秒,原“不相关字段完全一致”断言有时间竞态。固定该夹具为过期租约,另增按快照时间计算剩余时间的测试,没有删除计时功能验证。
- 最初的静默 AT 夹具会把分号子命令的空响应转为 ERROR,并没有制造预期的阻塞。截止回调用实际 uloop 运行,测试副本只将 12 秒常量压缩到 200 ms,验证及时应答、保留在途读的通道占用、结束后释放以及不再发送后续 AT;正式运行仍为 12 秒。
- BusyBox standalone ash 可绕过 PATH 中的同名 applet 夹具。分区等待/启动测试改用夹具的绝对路径,避免执行真实延时或 mdev。
原失败日志保留,未通过删用例或忽略错误得到最终通过。编译仍有既有 vendor/Mali、PCIe
未使用函数等警告,不将编译通过当作硬件验证。没有重新生成 rootfs/APK/安装器/发行压缩包,
没有访问或刷写用户设备,也没有测量实机启动耗时、中断次数或待机电流。
## 新提交 PR 核对:#371、#372、#373
按 2026-10-23 读取的 PR head 固定比对;没有 cherry-pick,也没有用旧 main
覆盖本地文件。比较以各 PR 自身提交序列和此前固定移植源为准,避免将其基线中的
安装器、内核版本、翻译等无关差异当作新优化。
| PR / 固定 head | 比较结果与处理 |
| --- | --- |
| [#371](https://github.com/dikeckaan/mu300-linux/pull/371) `af2f37e41124eff4393b01f7d44bb092d225646e` | 启动运行逻辑与前述 boot-speed 移植源一致。整理后的差异为 FINDINGS 编号及 PCIe 补丁移到 `6.18/0028`;该补丁与本地 `6.18/0024` 的 Git blob 完全一致。保留本地 7.2 专用错误路径适配,以及已明确保留的 failsafe 和正常模块扫描,不重复引入。 |
| [#372](https://github.com/dikeckaan/mu300-linux/pull/372) `f5528dd82d94466bdf9ec9ae8a79174ea54f5d0d` | CPU、常驻 daemon 和事件驱动逻辑已覆盖;重排中的文档编号变化不影响运行。末尾为测试修正:本地短信 watcher 已使用原生 Promise,SIM/失败重试有独立测试;短信与 NDP 已有实际事件夹具。补齐 `each_shell()` 生成器关闭时的 GeneratorExit 清理,并验证 skip 仍是 skip、真实失败仍报告失败,不吞掉断言。 |
| [#373](https://github.com/dikeckaan/mu300-linux/pull/373) `85d25c4b03ecaa2d3d6775b2505f09ed7b812860` | 新增、此前未包含。移入 `ums9620_lpintc` 模块,接入本地共享 `build-modules.sh` 和 `extra-modules`,覆盖 OpenWrt/systemd 的 flat/extra 模块布局;不改已有 thermal、modem、SIPA 加载顺序。 |
### LP_AP_INTC 适配与证据边界
来源是 liuwang97 的 PR #373 及其中 FINDINGS 218:作者在 U30 Air 原厂
`sml_a.img + 0x114d8` 中确认 TF-A 唤醒表;其固件未给 USB、IPA 和 PCIe
对应中断开放 cluster-pd 唤醒。该 PR 没有给出可在本地复核的完整固件版本或哈希,
因此这里只将原厂表和延迟测量标为上游证据,不能推广为所有机型的实测结论。
本地 UMS9620 clock driver 的 AON 寄存器和 `ap-intc0..7-eb` 位号与之相符。
- 仅接受实际 DT 的 `sprd,ums9620`;保留按实际 AON clock gate 排除关闭块的规则。
- 只增加 GIC 已启用的 SPI,使用 deferrable work 采集后来启用的驱动中断;不下线 CPU、
不改频率或无线电,不停用深度 idle,不引入新的用户态轮询服务。
- 休眠前撤销本模块增加的位、恢复后重加、卸载时撤销;原有和其他所有者设置的位保留。
- 本地额外收紧错误处理:任一已启用 INTC 映射失败,释放全部已映射资源并返回错误,
不以部分修复冒充成功。未检测到模块的 vendor 5.4 入口维持原路径。
- 保留此前用户明确指定的 `mu300-lowlatency` CPU0 idle 策略;没有借此 PR 自动取消。
在该策略仍生效时,不能照搬上游允许 CPU0 cluster-pd 的功耗或延迟数字。
实际生产 C 源码由寄存器夹具直接编译运行,覆盖 USB/IPA/PCIe 位映射、后来启用的中断、
重复读取幂等、GIC 禁用后不误删、三次 suspend/resume、卸载恢复、时钟关闭块不访问、
错误 SoC、无 GIC、映射失败清理及零周期限界。所有 MMIO 均为测试内存,未加载模块到
宿主内核或设备。另执行真实 Shell 加载片段,检查 flat/extra、已加载跳过、5.4 缺模块及
加载失败提示。
新增模块在既有 6.18.54、7.2.8 源码/对象缓存中通过原构建器编译,并通过模块 BTF、
Image/config/全模块哈希及现有 KVM/container/eBPF 配套检查;没有重新编译 Image,
没有构建 rootfs、安装器或发行包。系统 suspend、实际唤醒次数和延迟尚待本地实机验证。
| 验证 | 日志 |
| --- | --- |
| 首轮生产 C 寄存器测试:4 项通过 | [MMIO 回归](../out/build-logs/20261023-050400-pr373-mmio-regression-35758/command.log) |
| 6.18.54 新增模块编译与配套校验 | [6.18 编译](../out/build-logs/20261023-050503-pr373-kernel-618-35847/command.log) |
| 7.2.8 新增模块编译与配套校验 | [7.2 编译](../out/build-logs/20261023-050539-pr373-kernel-72-35874/command.log) |
| 新增寄存器/加载用例、测试结果保护、启动顺序、分区等待及构建边界:30 项中 29 通过、1 跳过 | [最终相关回归](../out/build-logs/20261023-050937-pr371-373-final-check-56505/command.log) |
| 修复旧测试隔离后的温控、TTL、USB:13 项通过 | [测试隔离最终回归](../out/build-logs/20261023-051010-pr373-final-isolation-59695/command.log) |
扩展回归的首轮 69 项中有 7 个失败、1 个错误、1 个跳过,完整日志保留在
`20261023-050631-pr371-373-regression-35903`。调查确认 BusyBox standalone ash
绕过 PATH 中的 `poweroff`、`id`、`i2cget/i2cset` 夹具:生产脚本未因该 PR 改动,
测试却执行到了宿主 applet。测试改为在私有副本中绑定这些命令的模拟绝对路径,并检查
待替换调用确实存在;没有改生产关机、权限检查或 USB 充电路径。受影响 13 项全部重跑
通过,其余相关 30 项单独重跑,初轮另外 26 项设备按键、LED、NFC 用例已通过且未修改。
本次 69 项覆盖合计 68 项通过,唯一跳过为宿主没有 ucode 的 Wi-Fi readiness 检查;
该检查在前一批 ARM64 原生验证中已通过,本次未重复运行。不能据此声称整个仓库所有
测试或实机功能都已验证。
首次双版本调用在 Shell 参数传递时丢失版本变量,被现有 Image/config 校验拒绝;
失败日志保留在 `20261023-050413-pr373-kernel-modules-35787`。改为分别传入两个
固定版本后通过,没有绕过校验;误建的空输出目录已用非递归 rmdir 删除。
+155
View File
@@ -0,0 +1,155 @@
# Native OpenWrt services
The C bridge and ucode modem/system service cores originate from
liuwang97/mu300-linux `ccf89bb65e283f1c609f507f4c51585b929b6e99`
(cpu-load), adapted to this branch's channel layout and policies.
OpenWrt has one implementation per migrated operation. It requires the packaged
native helpers and ucode modules; missing dependencies are reported as errors.
There is no old-image probe, automatic backend selection, disable-marker mode,
or alternate worker launched after an RPC failure. Ubuntu retains its original
platform services. This is an explicit platform boundary, not a recovery path.
* `mu300-atd-io` owns SIPC descriptors; `mu300-modemd` can restart without
closing them. CLI/FIFO clients retain their interfaces. The init service
rejects an existing physical owner instead of hot-switching to another one.
Model layouts preserve NR6/7, NR3 ownership and U30 sbuf/no-reopen rules.
* Background LuCI cell refresh calls `mu300.modem.collect` with explicit string
slot `0`/`1` and mode `full`/`fast`. SIM1 uses NR4 and its own cache/identity
directory. The original 1/5-second TTLs and staged output remain. The existing
synchronous live-signal CLI remains the implementation of the separate
`signal` operation; it is never selected as a replacement for failed native
background collection. The complete system snapshot still uses the original
`dashboard-info` until that operation is fully rewritten.
* The rates page calls only `mu300rates.rates` in rpcd. The `dashboard-rates`
CLI imports the same sampler. WAN selection, counters, ifindex, boot ID and
monotonic timestamp remain; plugin permissions are fixed during installation.
* OpenWrt `mu300-sysd` replaces its old buttons/thermal service entries. Local
button actions, U30 double-click, five-second checks, vendor cooling policy,
owned frequency caps and mainline emergency shutdown remain. Ubuntu still
runs its original buttons/thermal services.
* OpenWrt SMS init explicitly sets `MU300_SMS_TRANSPORT=ubus`; Ubuntu uses its
existing `urc-log` transport. A lost ubus listener is an error, never a switch
to log polling. Physical SIM filtering, spool/import/ACK, five-second failed
import retry and 300-second archive checks remain. PDU contents are not logged
or included in events. Stock CNMI rejection/ACK recovery is retained.
* OpenWrt data watch requires ubus events and retains the original recovery
decisions and 30-second safety interval. User data-off, switching gates,
active-SIM resolution, in-place renew and two confirmed detach observations
remain. Listener/service loss fails the task for normal procd supervision.
* NDP requires ip-full and its event/SIM-mapping libraries. Stable kernel
snapshots absorb self-generated notifications; concurrent addresses and
deletions trigger a new pass. Ten-second checks, neighbour pins, metrics and
paced withdrawal RAs remain. Missing tables or monitor loss are errors.
No device/boot-time/current measurement is implied by the automated tests.
Build the ARM64 static helper into the registered input directory using:
```sh
python3 tools/build-release.py run --label atd-io -- sh tools/atd-io/build.sh /path/to/registered/inputs/tools/atd-io
```
The builder requires an installed AArch64 compiler (or an explicit `CC`). Missing
compilers fail the build; the script does not select another environment. Source/binary hashes and ELF checks reject a stale,
wrong-architecture or dynamically linked helper during release checks. Both
rootfs assemblers copy the helper; OpenWrt also installs the ucode modules.
No desktop installer payload changes are required.
## The bridge protocol (mu300-atd-io <-> its client)
A unix stream socket, `-s PATH` (default `/run/mu300-modem/io.sock`), mode 0600 in a 0700 directory. One client at a
time: a new connection replaces the old one (a restarted modemd is never locked out by a stale connection). Records
are lines of printable ASCII ending in `\n`, fields separated by one space; payloads are uppercase hex (`2B43...`),
so nothing a modem or a client sends can break the framing. Channel names are `[a-z0-9_-]{1,16}`.
Client to bridge:
| record | meaning |
|---|---|
| `OPEN NAME DEVICE [READY]` | own DEVICE as channel NAME: open it (O_RDWR, O_NOCTTY, O_NONBLOCK; raw termios where it is a tty) now, else try again every 200 ms until it opens or the channel is CLOSEd. READY is optional, `sbuf:SBUF`: before each attempt the line `SBUF, state: 1,` must be in `/dev/sipc_sbuf` (the second SIM group's channels have a node before the modem side is up, FINDINGS 186). Repeating an OPEN for a channel that exists with the same device changes nothing and answers its STATE. |
| `FIFO NAME PATH` | own the request FIFO of channel NAME: create PATH (mode 0600; an existing FIFO is reused, anything else is replaced), open it O_RDWR and O_NONBLOCK, and forward its complete lines. Repeats change nothing. |
| `TX NAME HEX` | write the bytes to the channel, all of them (waiting up to 2 s for it to take them). |
| `REOPEN NAME` | close the channel's descriptor and open the device again (then the OPEN retry rule). |
| `CLOSE NAME` | close and forget the channel or FIFO NAME. |
| `PING TOKEN` | answered with `PONG TOKEN`. |
Bridge to client:
| record | meaning |
|---|---|
| `HELLO VERSION PID` | the first record of every connection (VERSION is 1) |
| `STATE NAME DEVICE STATE` | after HELLO for every channel and FIFO it holds, and on every change: `open`, `pending`, `eof`, `closed` |
| `OPENFAIL NAME ERRNO` | the first failed attempt of a pending open (one per pending period) |
| `RX NAME HEX` | one line from the channel: the bytes before `\n`, one trailing `\r` removed; empty lines too. A line longer than 8192 bytes goes out in 8192-byte pieces. |
| `RXP NAME HEX` | bytes without a newline that have waited 300 ms (a prompt such as `> `) |
| `REQ NAME HEX` | one complete line from the channel's FIFO, without its `\n` |
| `TXERR NAME ERRNO` | a TX that could not be written whole |
| `EOF NAME` | a terminal read 0 bytes or failed (a pty whose other side closed): the descriptor is closed and the channel is `eof`; it is not reopened by itself. A SIPC channel is not a terminal and never sends this: nothing to read (EAGAIN, ENODATA, EBUSY) is just that, and any other error, a read of 0 bytes or a hangup keeps it open and out of the poll for 1 s, since closing it would silence it until a reboot |
| `DROPPED NAME COUNT` | records that did not fit the queue while no client was connected |
| `PONG TOKEN` | |
While no client is connected the bridge keeps reading every channel (an unread SIPC ring only fills up) and queues
RX/RXP/REQ/STATE records, 1024 per channel and 256 KiB in all, the oldest dropped first; they follow HELLO and the
STATE lines on the next connection. The bridge never exits because of its client; SIGTERM closes everything and ends
it. It does not fork into the background (procd supervises it).
## modemd
* Brokers: the channel layout `mu300-atd`'s init script chose (`start_single_sim`: atd on nr1 with nr0's URCs, atd2 on nr2, additional nr3–7 per local policy;
`start_sim2`: atd/atd2/atd4/atd5 on nr1/nr2/nr4/nr5 with the URCs of nr0 and nr3, no reopen, the sbuf condition)
is handed to modemd as one argument per broker; the init script keeps every other decision (the SIM slot, the
dual-SIM fallbacks, the warm-up instances).
* Per broker: `$DIR/cmd` (the FIFO, via the bridge), `$DIR/owner/pid` (the bridge's pid, whose command line has
`mu300-atd`), `$DIR/urc/*.log` (capped at MU300_AT_URC_MAX, 64 KiB), and the request rule of `mu300-at`: the line
`T ANSWER-FILE COMMAND`, the answer file `$DIR/answer.<pid>` written whole (`.part`, then renamed), and the same
checks (`one_request`, the timeout range, the answer file's name).
* A command: drain first (quiet for 0.05 s after a clean reply, for 1 s otherwise; at most 3 s, 25 s after an
unanswered command), write it with `\r`, collect until a final result code (`OK`, `ERROR`, `+CME ERROR`, `+CMS ERROR`,
`CONNECT`, `NO CARRIER`) or T + 1 s. Lines in a drain go to the channel's own URC log (never the command's echo,
which can hold a secret). `+CMT:` frames go to `mu300-cmt-spool` on its stdin, never into a reply or a log.
* URC channels: every line to its log, validated `+ECIND` to `mu300.sim-change`, CEREG/scoped replies to the native passive cache, and a ubus event
`mu300.modem.urc` (`{ "channel": "nr0", "line": "..." }`; `+CMT` frames and lines that can carry a secret are not
sent).
* The reopen rule: five unanswered commands in a row, the last reopen more than 300 s ago, and the live URC log quiet
for 240 s; never with MU300_AT_DISABLE_REOPEN.
* ubus `mu300.modem`: `at { cmd, timeout, channel }` (answered when the reply is in), `status`, `cell { mode }`
(start a collection round now unless one is running or the cache is fresh; answers at once), `urc` events.
* The panel's collection (`unisoc-modem/cell`'s rounds) runs inside modemd when the status plugin asks for it, with
the same commands, files and JSON, without a process per round.
## Resident dashboard and service placement
OpenWrt's LuCI readers use `mu300status.status/cells/sysinfo/sms_head`,
`mu300rates.rates` and `mu300.modem.signal`. Read ACLs expose only those fixed
methods, not arbitrary AT access. Missing native objects produce an error; no
RPC/backend probing starts an old worker. The compatibility RPC and
`dashboard-info` CLI use the same implementations.
`mu300.dash` imports the existing public APN and hotspot modules. It reads
procfs/sysfs, UCI, netlink and bounded ubus replies directly, without shell
subprocesses. SMS notifications read a per-SIM pool signature first; message
lists are read only after a change. Explicitly configured external SMS adapters
retain their own list polling; their storage format is never guessed. This does not change SMS import/ACK policy.
Live signal requests use private rounds inside modemd and never overwrite the
background caches. The existing physical-channel pool and SIM switch/epoch
checks apply. A live reply has a 12-second deadline. If an AT read is already
queued, a timed-out caller receives an error while that round retains its pool
until the pending read finishes; it cannot free a channel into overlapping work.
`mu300-service-cpus` is an OpenWrt one-shot service. Its `little` setting places
procd services on online CPUs of the lowest reported capacity. `all` removes
that cpuset restriction. Run `mu300-service-cpus all` or
`mu300-service-cpus little` as root to apply and save the choice;
`mu300-service-cpus get` reports it. The setting is stored in
`unisoc_modem.main.services_cpus`. It changes no CPU online state, frequency,
voltage, interrupts or charging policy. Unsupported/missing cgroup requirements
are reported as errors.
Native collector/client locks identify the current process directly and split
other processes' NUL-separated argv before checking ownership. A native request
holds its client lock until completion: a wall-clock deadline from the CLI lock
format must never reclaim or kill a live modemd owner, including another daemon.
+56
View File
@@ -0,0 +1,56 @@
# U30 Air 开机电池灯轮换
用户反馈启动加速后看不到电池灯红、白、蓝轮换。检查当前源码和部署前备份的
initramfs `/init`,均未找到该机型的 RGB 开机轮换实现;U30 Air 的 `led-status boot`
分支只设置网络灯和电量灯。这能确认当前入口缺少轮换,不能证明优化删除了旧灯效,
也没有把启动变快导致 bootloader 灯效变短的猜测写成结论。
## 修改
在共享 rootfs 的 `mu300-led` 中增加仅 U30 Air 使用的开机轮换操作,
`u30air-led-status boot` 启动轮换。电池灯的 PMIC 通道为 `sc27xx:red`、
`sc27xx:green`(实际白色)、`sc27xx:blue`,沿用现有已确认的机型接线。
- 每帧使用现有 LED 互斥锁,休眠时释放锁;通过随包 BusyBox 的 `usleep` 控制间隔,
不依赖 OpenWrt 精简版 `sleep` 支持小数。
- 电池事件继续记录正常电量和充电状态,开机轮换期间不覆盖 RGB 帧。
网络和 Wi-Fi 灯仍独立更新;亮度、电池灯开关和休眠设置仍生效。
- 既有 `mu300-post` 开机完成通知或蜂窝 online 通知结束轮换,恢复正常电池显示。
每个 worker 使用独立 token,每帧在锁内复核;旧 worker 不能在交接或重新开始后写灯。
- 温度告警取消开机轮换并保留优先权。轮换仅在启动阶段运行,不增加常驻轮询。
- 共享打包和更新路径会携带这两个 rootfs 文件;无需重编内核或图形安装器。
## 验证
相关测试 31 项:30 通过,1 项需要 ucode 的既有无线测试在本轮主机环境跳过。
覆盖 RGB 帧、事件刷新、正常电量交接、旧 token、worker 退出、灯光开关和亮度、
温度告警优先级,以及原有充电呼吸灯、超时、网络灯、V50 灯和启动顺序检查。
已部署到用户连接的 U30 Air,实机逐帧采样确认出现 `(255,0,0)`、`(0,255,0)`、
`(0,0,255)`;停止后 worker 退出。设备配置及 Android boot A 的 SHA-256 不变。
随后实际重启:SSH 重新可达,WAN 正常,热点在内核启动约 20.78 秒进入转发状态,
没有新的 BUG/Oops/WARNING/panic。正常状态为 online-5g;蓝色电池灯恢复硬件充电
呼吸曲线,开机 token 和 worker 均已消失。实际肉眼观感仍需用户确认。
- [自动化回归](../out/build-logs/20261023-055937-u30-boot-led-regression-81514/command.log)
- [实机灯色与交接](../out/build-logs/20261023-055950-u30-boot-led-live-91352/command.log)
- [实际重启](../out/build-logs/20261023-060002-u30-boot-led-coldboot-91371/command.log)
原始采样位于忽略目录 `work/boot-led/`;部署前脚本备份保留在设备
`/mnt/mu300-disk/.mu300/backups/boot-led-20261023/`。完整部署清单同步两个新源码哈希。
本次没有构建发布包,也没有修改 Android 启动镜像、userdata、GPT 或 NV。
## 充电低电量颜色补充
按用户补充的 U30 Air 灯光行为,充电且电量低于 10% 时使用红色硬件呼吸灯;
10% 至 49% 仍为蓝色,50% 起仍为白色。充满常亮、拔线、非充电电量提示和其他
机型不改。此处低电量规则的依据是用户反馈,未额外宣称已从原厂驱动中复核。
25 项相关回归全部通过,新增检查 0%、9%、10%、49%、50% 及颜色往返切换、
亮度、灯光关闭和拔线后 FGU 状态滞后的情况。已部署单个共享脚本并刷新当前
电池灯,无需重启;实机尚未降至低于 10%,低电量红色呼吸尚待实际电量验证。
- [低电量回归](../out/build-logs/20261023-060252-u30-low-charge-led-91419/command.log)
- [部署及当前电池状态](../out/build-logs/20261023-060316-u30-low-charge-led-live-2513/command.log)
旧脚本保留在设备 `/mnt/mu300-disk/.mu300/backups/low-charge-led-20261023/`。
@@ -0,0 +1,128 @@
# U30 Air:完整移植部署与实机验证
后续热点启动专项修复已部署:消除监管库加载前约 20 秒的无效等待,热点可用从约
41 秒提前至 21 秒,用户手机已确认连接上网。见 [Wi-Fi 启动报告](U30AIR-WIFI-BOOT-20261023.zh-CN.md)。
2026-10-23,用户明确要求把整批改动部署到连接的 U30 Air,包含之前移植的
启动、常驻服务及事件驱动优化,不限于 PR #373。本文记录完整部署后的状态;
此前只部署 LP_AP_INTC 的记录见 [单模块报告](U30AIR-LPINTC-LIVE-20261023.zh-CN.md)。
## 部署完成范围
实际 DT 的 `charger_policy_service` 和 `mu300-device` 均确认 U30 Air;维护连接
绑定核对后的 SSH 主机公钥及 USB 身份,不依靠管理 IP 猜设备。Android 为 A,
OpenWrt 为 B,独立内置 `mmcblk0p76` 上的 OpenWrt 25.12.5。没有格式化、缩扩容
或变更安装方式。
- 已部署并逐一 SHA-256 核对 **207 份运行时文件**,包含本仓库共享脚本/库、
OpenWrt 服务与网络入口、LuCI 代码、RPC/ACL、ucode 模块、静态 AT bridge 和按键 helper。
- 已通过原 `upstream/make-bundle.sh` 使用已核验产物生成部署用内核包,并通过当前
`mu300-update boot` 安装 **7.2.8 #56**、**202 个模块**及当前 `boot/init` 的
generic ramdisk。使用本机原有 boot header、AVB 尾及设备 ramdisk,启动分区回读通过。
- 启动优化已实际运行:PCIe 初次探测等待、模块预读、随机池初始化、UART 输出级别、
USB 固定等待删除、eMMC 就绪探测、Wi-Fi 顺序和 SIPC/数据就绪检查。
- `mu300-modemd`、`mu300-atd-io`、`mu300-sysd`、原生快照/网速、SMS/data/NDP
事件监听及服务小核调度均已运行;OpenWrt 的旧 buttons init 和 post 内旧 thermalguard
入口已移除。原 CLI 与显式平台入口保留,没有失败时自动切旧后端。
- PR #373 模块保留并在本次重启后加载。原有 CPU0 lowlatency 策略保留,没有因部署而
擅自改变用户选择的 idle、频率、充电或无线电策略。
本次没有构建 GUI、完整 rootfs 或发行压缩包;生成的内核部署包仅用于实机维护。
## 旧版本缺失依赖的处理
设备未部署用户前一天的更新。初次按当前 Git 差异安装的 39 份文件没有覆盖旧设备缺失的
`sms-pool.sh`,导致 AT 服务在入口加载时明确失败,蜂窝 WAN 未起来。
该次启动属于失败记录,不计作验证通过,也没有临时启用旧 broker。
随后对当前仓库完整运行时做核对:补齐另外 9 份缺失/过期文件,涉及 SMS pool/CMT
spool、dual-radio、短信/toolkit/VPN、SMS forwarding、相应 VPN init 和 settings 页面;
207 份文件最终全部与本地源一致。该问题来自旧设备的部署基线,当前 rootfs 构建流程
本身会携带完整共享库。补齐后重新冷启动,所有八路物理 AT/URC 描述符正常打开。
## 启动实测
先在原版本执行一次重启建立基线,再部署后复核。表内时间来自内核 uptime 和实际
`bootmark`,不是电脑侧进度估计;SIM、网络、APN 和充电配置保持一致。
| 时间点 | 原系统 | 完整部署后的最终冷启动 |
| --- | --- | --- |
| initramfs devfs 就绪 | 2.24 s | 0.36 s |
| 模块加载完成 | 3.66 s,26 个成功、0 失败 | 0.61 s,26 个成功、0 失败 |
| 早期 USB DHCP 就绪 | 5.14 s | 1.17 s |
| switch_root | **5.17 s** | **1.20 s** |
| Android vendor 服务入口 | 13.64 s | 8.02 s |
| AT 服务入口 | 15.95 s | 10.01 s |
| RIL 握手完成 | 18.72 s | 12.54 s |
| 蜂窝注册完成 | 33.76 s | 26.69 s |
| PDP 激活 | 37.28 s | 27.57 s |
| 蜂窝地址就绪 | **37.33 s** | **27.69 s** |
switch_root 提前 3.97 秒;蜂窝地址提前 9.64 秒,约 25.8%。另一轮补齐后的启动
记录为地址 28.08 秒,也已正常联网;其电脑侧观察器因 SSH 恢复早于 configfs 身份节点
发布而退出,未把那轮 SSH 可用时刻作为有效测速。观察器已修正为等待同一路径身份就绪,
最终冷启动重新通过,没有降低设备身份校验条件。
电脑从发出 reboot 到 SSH 可用为 42.33 → 35.14 秒,包含 bootloader 和电脑网络
恢复时间,与上述内核时间起点不同。这里只报告一次原版本基线和完成后的两轮启动,
不声称多次统计结果或所有网络环境都能达到相同收益;蜂窝注册仍受运营商影响。
## 功能、恢复与副作用检查
| 项目 | 实机结果 |
| --- | --- |
| 版本一致性 | 207 份运行时文件、202 个模块 SHA-256 全部匹配;实际运行新 #56 内核。 |
| AT 所有权 | NR1/2/4/5/6/7 六个命令通道和 NR0/3 两个 URC 通道全为 open;扫描 `/proc/*/fd` 确认八路均仅由同一个 C bridge 持有。 |
| 实时读取及兼容 CLI | 原生实时信号 RPC 成功;原 `mu300-at` 在 daemon-only 模式下读取 CSQ 成功,没有直接打开 tty 作为测试捷径。 |
| daemon 恢复 | 仅向 ucode modem daemon 发送 TERM,正常由 procd 拉起;新 PID 接回原 bridge,bridge PID/物理通道所有者不变,WAN 保持 up,CLI 再读成功。没有重启完整 AT 服务或重置射频。 |
| 看板和流量 | 原生 sysinfo/status/cells、rates、sms_head 可用;WAN、热点及 modem alive 均正常。15 次设备端 sysinfo 调用平均 38.75 ms、最大 66.66 ms(包含启动 ubus 客户端)。未采集同条件旧 RPC 耗时,因此不声称本机页面 CPU 的具体提速倍数。 |
| 浏览器接入 | 用独立测试登录会话走 HTTP `/ubus`,实际调用 status、rates、sms_head 全部成功;HTTP 返回的 common.js 与本地源 SHA-256 相同,测试会话已清理。 |
| 小核调度 | 重启后 procd services 的有效 cpuset 为 `0-3`,读取的保存模式为 little;没有 CPU 下线或 DVFS 改写。 |
| 事件监听 | SMS 的两槽监听、data 的 ubus listener、NDP 的 ip monitor 均运行,旧 shell AT owner 和旧 thermalguard 不再运行。 |
| 联网 | LAN/蜂窝 WAN 均 up,热点实际处于 up;指定蜂窝接口访问 generate_204 得到 HTTP 204。 |
| 内核状态 | 最终冷启动及恢复测试无新 BUG、Oops、WARNING 或 Kernel panic。 |
| 配置与 Android 保护 | Android `boot_a` 全分区及 network/wireless/unisoc_modem/unisoc_apn/mu300-charge 的 SHA-256 前后一致。 |
20 秒无页面轮询的 CPU 采样中,全部 CPU 的非 idle/iowait 时间合计 149 ticks,
`CLK_TCK=100`,约为单核 7.45%。这是**包含内核、网络栈和全部进程**的整机统计,
不是 mu300 常驻服务单独 CPU,也没有同条件原版本 CPU 基线;不能与上游 0.3%
用户态数字直接比较。
## 未验证范围
- 用户使用物联卡,无法进行短信收发实测;这里只验证接收服务、事件监听及状态接口。
不注入模拟短信到真实消息池,不冒充真实收信通过。
- 没有实际切换 SIM、重置蜂窝、拨打电话、改变充电策略,或操作 NV/校准分区。
- 没有人工实体按键、NFC 读写或长时间 Wi-Fi 客户端流量测试;不以 daemon 存活替代这些实测。
- 系统 suspend/恢复、长期待机功耗/续航、其他机型和 6.18 仍未实机验证。
LP_AP_INTC 的本机 USB/cluster-idle 测试仍见单模块报告。
## 备份与证据
设备侧原文件、原模块、配置及启动元数据归档、boot B 原镜像位于:
```text
/mnt/mu300-disk/.mu300/backups/full-native-20261023/
```
电脑双份校验备份、完整文件清单及私有原始观测保存在
`work/full-live/`;归档可能含设备配置,应作为备份保管,不上传公共仓库。
配置正文、短信正文、SSH 密码及测试会话 token 未写入公开报告。
当前 `mu300-update rollback-boot` 的 prev.body/vbmeta/footer 也保留;需要回滚整批时必须
同时恢复旧运行时和旧配套模块,不能仅退 boot 而混用不同版本依赖。
| 阶段 | 日志 |
| --- | --- |
| 原构建器生成内核部署包 | [kernel bundle](../out/build-logs/20261023-052152-full-u30air-kernel-bundle-61089/command.log) |
| 双端备份、初始暂存与导入检查 | [backup/stage](../out/build-logs/20261023-052245-full-u30air-backup-stage-61969/command.log) |
| 更新前冷启动基线 | [baseline](../out/build-logs/20261023-052445-full-u30air-baseline-boot-61990/command.log) |
| 内核、模块、启动分区和运行时部署 | [deploy](../out/build-logs/20261023-052555-full-u30air-deploy-62013/command.log) |
| 完整依赖核对和补齐 | [runtime reconciliation](../out/build-logs/20261023-052955-full-u30air-runtime-complete-62060/command.log) |
| 功能、AT 描述符、daemon 恢复、CPU 及联网测试 | [hardware validation](../out/build-logs/20261023-053307-full-u30air-hardware-validation-62095/command.log) |
| 最终完整冷启动 | [final cold boot](../out/build-logs/20261023-053350-full-u30air-final-coldboot-62117/command.log) |
| 最终浏览器 HTTP API 和重启后状态复核 | [browser API](../out/build-logs/20261023-053536-full-u30air-browser-api-final-62157/command.log) |
保留失败记录:初次差异部署缺短信库的蜂窝启动失败、观察器遇到暂未发布的 configfs
身份路径、以及 HTTP 测试会话销毁权限与测试脚本预期不同。前两者分别通过补齐完整依赖、
等待原身份路径解决;会话清理由已核对的 SSH 维护连接执行,仅清理测试自身的会话。
修正后重新执行对应验证,不把失败日志隐藏或解释为已经通过。
+86
View File
@@ -0,0 +1,86 @@
# U30 Air:LP_AP_INTC 实机部署与验证
本文保留先前单模块部署阶段的记录。后续已完成整批运行时、内核及启动优化部署,
当前设备状态见 [完整移植实机报告](U30AIR-FULL-BACKPORT-LIVE-20261023.zh-CN.md)。
2026-10-23,经用户授权,在 USB 连接的 U30 Air 上部署并测试
[liuwang97 的 PR #373](https://github.com/dikeckaan/mu300-linux/pull/373) 本地适配。
本次仅部署 `ums9620_lpintc` 及其开机加载入口,没有部署其他常驻服务、更新内核、
重启设备或生成发布包。
## 设备与部署范围
- 实际机型:`mu300-device` 返回 `u30air`,原厂 DT 的 `charger_policy_service`
节点存在;SoC compatible 为 `sprd,ums9620`。
- 系统:OpenWrt 25.12.5,`r33051-f5dae5ece4`,ARM64,运行内核 `7.2.8`。
- 管理连接:电脑 `192.168.77.200` 经 USB 连接 `192.168.77.1`;`br-lan` 包含
`usb0`、`wlan0`。部署使用核对后的 SSH 主机公钥、USB 身份及实际 DT,日志不公开序列号。
- 使用已编译、匹配 7.2.8 的模块,正常 `insmod`,没有强制忽略版本或符号检查。
模块 SHA-256:`c2dd4e8261e7de8110d7bc6161ce3d58a9555024ec31ea4d8065bb62649a8989`。
- 持久路径:`/lib/modules/7.2.8/ums9620_lpintc.ko`。仅向设备原有
`/opt/mu300/bin/extra-modules` 插入该模块的加载段,没有用仓库整份脚本覆盖设备版本。
原脚本备份在 `/etc/mu300/backup/lpintc-20261023/extra-modules.before`,电脑也保留一份。
开机入口已写入并检查 Shell 语法;本次没有重启,因此不将持久化部署写成“已验证重启后加载”。
## USB 延迟对比
电脑使用 Windows .NET ICMP,同一地址、每秒一次,统计真实 RTT;计时分辨率为
1 ms,返回 0 ms 仅代表小于该计时精度,不代表真实传输没有耗时。测试没有触碰电脑网卡或路由。
| 条件 | 收包/发包 | 平均 RTT | 中位 RTT | 最大 RTT |
| --- | --- | --- | --- | --- |
| 原始 CPU0 idle 全部禁用,未加载模块 | 20/20 | 0 ms(精度下限) | 0 ms | 0 ms |
| 暂时允许 CPU0 所有 idle 状态,未加载模块 | 30/30 | 12.37 ms | 0 ms | 67 ms |
| 允许相同 idle 状态,加载模块 | 30/30 | 0.8 ms | 1 ms | 1 ms |
| 恢复原始 CPU0 策略,保留模块 | 20/20 | 0 ms(精度下限) | 0 ms | 0 ms |
共 100 次 ping,无丢包。该短时间 USB 测试支持“模块修复本机允许 cluster-pd 时的
长尾延迟”,不能据此推断功耗、所有负载或所有机型的延迟。加载模块后的独立 5 秒检查,
CPU0 的 `cluster-pd` 使用计数从 1223 增至 1315(增加 92 次),证明没有靠禁用该
idle 状态得到测试结果。
原始 CPU0 三个 idle 状态的 `disable` 均为 1。对比期间临时改为 0,电脑侧 finally
和设备侧超时脚本负责恢复;所有测试结束均恢复为 1。没有改写既有 `mu300-lowlatency`
策略或启动配置。
## 寄存器、加载和副作用检查
首次加载读到原始 INTC0–7 掩码依次为:
```text
f5085c00 2080b9fc 00000000 00000000 00000000 00000000 00000000 00000040
```
与上游记录的 U30 Air TF-A 表一致。模块实际增加 INTC2 `00040000`、INTC4
`00044700`、INTC5 `01fe0000`、INTC6 `02d40018`;刷新周期为 5 秒。
正常卸载后重新加载,八组原始掩码逐一完全一致,验证卸载没有遗留本模块增加的位。
- 模块加载、卸载、重新加载通过;上传与持久文件 SHA-256 一致。
- 测试前后 boot ID 一致,没有重启;无新增 BUG、Oops、WARNING 或 Kernel panic。
- `/etc/config/network`、`wireless`、`unisoc_modem` 的 SHA-256 前后一致。
- LAN 和蜂窝 WAN 均保持 up;没有执行 AT、切 SIM、拨号、短信或充电配置操作。
- 没有写 boot、misc、分区表、userdata、TF、NV 或校准数据。
## 未验证范围
设备当前运行内核实际为 `# CONFIG_SUSPEND is not set`、
`# CONFIG_PM_DEBUG is not set`;`/sys/power/state` 为空,`pm_test` 和 `mem_sleep`
接口不存在。因此没有尝试 `mem` 或假称系统休眠回调已通过;cluster-pd 的 cpuidle
唤醒与整机 suspend 是不同路径。当前本机验证不覆盖 6.18、其他机型、Wi-Fi/PCIe
实际流量下的唤醒、长期稳定性或续航测量。
其他 CPU、modem、系统快照及启动优化尚未部署到这台设备,不将此次结果扩大为整批移植的实机通过。
## 证据与撤回
电脑原始 RTT CSV、设备回读和恢复记录位于忽略目录
`work/pr373-u30air-live-20261023/`,不包含 SSH 密码。
- [部署及 USB A/B 测试日志](../out/build-logs/20261023-051408-pr373-u30air-hardware-61007/command.log)
- [设备能力和卸载掩码复核](../out/build-logs/20261023-051649-pr373-u30air-final-probe-61036/command.log)
- [模块启用时的 cluster-pd 计数及最终状态](../out/build-logs/20261023-051728-pr373-u30air-idle-proof-61053/command.log)
需要撤回时,仅针对该 U30 Air:卸载 `ums9620_lpintc`,恢复上述备份的
`extra-modules` 并移走新增模块文件即可;不需要恢复系统分区或用户数据。恢复脚本前应核对
之后是否又有其他维护任务修改该加载脚本,避免覆盖后续修改。
@@ -0,0 +1,64 @@
# U30 Air 手动双卡管理
2026-10-23。此次修改取代旧的 U30 单活动射频、开机选卡及首次联网检查流程。
原先导入、移植及射频报告中关于该旧流程的描述属于历史行为,以本文为准。
## 原因与行为
用户报告切卡按钮持续灰色。已在绑定 SSH 主机公钥、USB 身份及实际设备树的
U30 Air 上复现:`hot=1`、当前 SIM1 已联网,但旧原生控制器返回 `available=0`,
网页因此禁用切卡。开启热切换选项并不能让已运行的普通启动自动成为原生双卡启动。
现在 U30 使用 F50/V50 的共享双卡初始化、数据卡选择及回读事务:
- 默认允许两张卡射频,已有的明确射频开关文件仍优先。手动关闭的卡不会被升级打开。
- 数据卡选取只改变数据通路,欠费、无信号或注册慢均不自动切回另一张卡。
选取/回读/持久保存失败时仍恢复原选择;这是失败恢复,不是按联网质量自动选卡。
- U30 的目标卡射频若已被用户关闭,需要先手动开启,再切换上网卡。
- 移除热切换开关、单独下次开机选卡和首次联网检查,使用同一个持久选卡配置。
原 `u30_sim_hot` 等旧设置不再参与运行,新能力迁移标记为 `u30_dual_version=1`。
- 原 `mu300-data-sim-u30`、`mu300-sim-u30` 名称仅作为共享手动控制器的兼容入口。
删除旧 cold-start/warmup 控制器及其配置库,同步更新两个打包检查入口。
- 保留 U30 专有 SBUF 就绪条件、持久 SIPC owner、禁止直接打开/失败重开通道、
不重启物理桥的约束。通道归属、早期网络配置回放及射频互斥没有移交给网页。
- 旧控制器仍在运行的设备必须正常重启再切换服务,禁止原地重新打开物理通道。
常驻采集、网络恢复和 NDP 均从当前共享选卡配置取槽位,不再让旧开机 pin 覆盖选卡。
## 自动化验证
- 手动双卡、F50 数据卡事务、初始化、分卡 RF、配置迁移、原生服务布局共
**63 项通过**,另含 Node 的 SIM 页面测试及 V50 四种物理卡布局。
[日志](../out/build-logs/20261023-071350-u30-manual-dual-sim-38234/command.log)。
- NDP 4 项、蜂窝地址恢复 15 项、常驻 RPC 兼容 2 项通过。
[日志前半](../out/build-logs/20261023-071548-u30-dual-sim-runtime-48164/command.log)。
- 实际 ucode/ubus 下,默认选卡、显式查看另一卡、无效槽位及切卡互斥 3 项通过。
新用例发现并修复函数声明顺序问题;快照断言改为 fast 模式实际生成的 `sig.json`。
[最终日志](../out/build-logs/20261023-071730-u30-dual-collector-final-50527/command.log)。
- 最终 Node 页面及 Shell/打包入口语法检查通过。
[日志](../out/build-logs/20261023-071933-u30-sim-final-ui-syntax-50587/command.log)。
Windows `git diff --check` 通过;没有修改 Git 所有权设置来绕过 WSL Git 错误。
- 旧单活动栈 cold/hot 测试随对应实现删除,由当前手动双卡行为及恢复用例取代。
没有保留失败时回到旧算法的运行分支。
## 此台 U30 Air 的实测
CP 读回为 `MOCORTM_V2_23A_W25.03.2_Debug`、`QogirN6Pro_PS`,
基带 `5G_MODEM_V2_23A_W25.03.2`,固件日期 `01-14-2025 10:14:02`。
两卡均实际返回 `CPIN: READY`。这不同于仅以相似机型或默认 AOSP 行为推断能力。
部署前逐个备份相关文件及选卡/RF 配置,上传并回读核验 15 个运行文件;删除三个
已退出生产路径的旧控制文件。随后正常重启一次,没有刷写内核、misc 或分区。
部署清单和本地维护备份位于 `work/u30-manual-dual/`,不含发布包。
- 冷启动后约 25 秒检查:两卡 `CFUN: 1`,`ready: true`,SIM1 已联网。
首次初始化曾报告一次 SIM 存在性未就绪,该轮停止;原 netifd 重试后成功,
没有添加射频重置或自动选择其他卡来掩盖此状态。
- 实际通过 `mu300dash` 异步作业切到 SIM2,保存选择并回读一致。
当时 SIM2 暂无数据连接,等待后仍维持用户选择。
- 通过相同作业切回 SIM1,随后恢复联网。
- SIM2 手动关闭时回读 `CFUN: 2`,手动开启后回读 `CFUN: 1`。
最后两卡仍为 `CFUN: 1`,RF 保存值 `1 1`,原 SIM1 上网选择和联网均已恢复。
本次没有验证 SIM2 实际上网、双卡并行通话/短信或长期功耗,也不能将本机结果推广为
所有 U30 基带版本均已验证。旧版本“同时启用可能失败”的记录不能抹去;本轮仅确认
上述实际固件可以正常双卡开启。没有重建 rootfs、安装器或发布压缩包,也没有提交。
+112
View File
@@ -0,0 +1,112 @@
# U30 Air 回归检查(2026-10-23)
## 范围与结论
本轮检查已连接的 U30 Air,以及当前 MU300 仓库的事件服务、看板和板级策略。
实机通过固定 SSH 主机密钥、机型和既有设备身份核验后,只读检查;没有重启、
切卡、开关射频、修改配置、拨号或安装固件。测试中的服务接管、断连、切卡和
失败恢复在隔离容器内执行,不是实体基带故障注入。
当前实机功能检查通过,但部署版本与最新源码不一致;隔离测试发现并修复了
共享事件等待的超时误判。因此不能将当前实机结果表述为“最新版全部实机验证
通过”。本轮没有打包、提交或覆盖此前其他任务的修改。
## 实机结果
- 六路 AT 命令通道和两路 URC 通道均打开,桥接连接正常;检查 `/proc/*/fd`,
八个物理 AT 设备均由同一 C bridge 持有,没有第二个物理 AT owner。
- `mu300status` 看板系统快照、两卡状态、短信计数和 `mu300rates` 速率接口通过。
只检查短信数量,不读取或记录短信正文。
- 经实际 HTTP `/ubus` 登录调用系统信息、模组状态、速率和短信计数均成功;
临时登录会话已注销。SIM、数据卡及射频控制的只读 RPC 均无错误。
- 当前 WAN、热点、基带均为工作状态;快照包含 CPU、内存、电源、无线、LAN、
WAN、流量等数据。内核日志未发现 BUG、Oops、panic 或 use-after-free。
- 经当前 WAN 发出 3 次 IPv4 ping,3/3 返回,0% 丢包;没有重新拨号。
- 检查前后 18 份配置及保护文件 SHA-256 一致。
10 秒空闲采样:C bridge PSS 932 KiB,modemd 869 KiB,网络恢复服务 342 KiB,
两路短信服务共 375 KiB,sysd 784 KiB,NDP 服务 210 KiB;上述服务合计约
3.43 MiB。bridge、modemd、网络恢复及短信服务均为 0 CPU tick;sysd 1 tick、
NDP 7 tick,设备时钟为每秒 100 tick。该短时采样不代表待机功耗或长期负载测试。
## 部署版本差异
回归开始时依据既有部署清单核对 204 个当前仍有源码的文件,其中 7 个已部署文件与最新
源码不同:`mu300-modemd`、`mu300-ttl`、RPCd `mu300dash`、LuCI 菜单、RPCd ACL、
`common.js` 和 `home.js`。新增的 TTL 页面尚不存在于设备上。
实机 `mu300-modemd` 正常命令前等待仍为 100 ms,当前源码已改成 50 ms;
不能声称此设备已经验证了最新 AT 延迟优化或 TTL 页面。此差异使部署一致性检查
明确失败,未将其忽略或改成通过。后续部署应按共享更新路径完整同步相应脚本、
页面、菜单、ACL 和依赖,而非只替换网页文件。
本轮新增的三处事件等待修复也尚未部署到实机。
## 自动化验证
| 运行 | 结果 | 本机日志目录(`out/build-logs/` 下) |
| --- | --- | --- |
| 原生 ARM64 ucode、ubus、C helper 联合回归 | 112 项:108 通过、1 失败、3 跳过 | `20261023-110409-u30air-native-final-22798` |
| 数据卡事务,宿主 Linux 多 shell | 11 项通过 | `20261023-110238-u30air-shell-regression-8035` |
| 射频、U30 适配、灯效、热点、电源、启动及服务入口 | 64 项:58 通过、6 跳过 | `20261023-110302-u30air-board-regression-9890` |
| 失败项所属事件总线模块重跑 | 9 项通过 | `20261023-111021-u30air-watchdog-recheck-22865` |
| 失败场景独立重复复现 | 10 轮通过 | `20261023-110910-u30air-watchdog-investigation-22833` |
| TTL 后端与实际 iproute2 监听语法 | 10 项通过 | `20261023-111108-u30air-ttl-netlink-22894` |
板级回归中因缺少 ucode 而跳过的 5 项电源用例和 1 项无线就绪用例,已在上述
ARM64 联合回归实际执行通过。该联合回归跳过的两项 Node 测试,已直接运行
`dashboard_sms_watch.js`、`dashboard_resident_rates.js` 通过;只读 netlink 监听
用例也已在最后一组实际执行通过。跳过本身没有计入通过数。
Windows Node 直接执行 7 个测试脚本通过:SIM 控件、短信刷新、速率、TTL 页面、
页面刷新调度、快捷控制和充电设置;检查实际页面代码,覆盖隐藏/卸载后停止刷新、
延迟响应丢弃、RPC 错误、重复请求及共享设置状态。19 个看板脚本语法检查通过。
原生组包括正常/迟到/超时 AT 回复、50 ms 派发、短信隐私与事件、SIM 缓存恢复、
单 owner、温控定时器、看板/RPCd 数据、事件监听器死亡和用户选择保护。
真实源码匹配的 ARM64 C bridge 与 CLI/ucode 在 PTY 上完成联合测试,包含
ucode 退出接管期间保留物理描述符及排队请求;C bridge 和按键 helper 均核对
静态 AArch64 格式、源码指纹和二进制指纹。没有在实体 AT 通道注入测试回复。
### 已复现并修复:等待超时误报监听器断开
原生组有一次 `test_whole_watchdog_respects_explicit_user_data_off` 失败:测试
看守进程提前退出,退出码为 1。首次混合运行中该项曾通过;后来连续 10 轮独立
复现与事件总线完整模块重跑均通过。继续延长测试,约 20 秒后再次复现。
加入临时跟踪后,确认 `read` 返回 142(Bash 的 SIGALRM 超时),事件监听进程
仍存活、stderr 为空,但 `/proc/uptime` 的整秒值仍比截止时间小 1。代码把这一
超时边界误判为监听器断开,导致看守进程退出;期间没有发出 AT 或恢复拨号。
跟踪日志:`20261023-111229-u30air-watchdog-trace-23210/command.log`。
修复 `data-events.sh`、`sms-events.sh`、`ndp-events.sh` 中同样的判断:142 保留
原截止时间继续等待;EOF、监听器死亡、模组移除仍为错误,不切换旧后端、不改变
用户关闭数据的选择、不修改射频或重连策略。
已增强该测试的诊断:进程意外退出时输出 stderr,避免只有“1 is not None”。
新增 `test_event_deadlines.py`,确定性模拟超时返回 142 而粗粒度时钟尚未到期,
验证不延长原截止时间,并验证 EOF 仍立即失败。宿主多 shell 运行 2 项通过,日志
`20261023-111352-u30air-deadline-boundary-23239/command.log`。初始失败记录保留,
不将其混同为通过;修复后的运行结果另外记录。
第一轮修复后回归中 27 项通过,另 1 项实际 iproute2 测试因测试容器缺失
`libelf.so.1` 失败,并非事件等待断言失败。仅向容器补齐依赖,未修改设备;
依赖从已核验的 U30 Air 只读取得,SHA-256 为
`4f3fa7563bf767a8f9acbd090e4a99e86c3394bd7c9bf6b8459a3baf40ff6e3e`。
补齐后容器 `ip -V` 正常,版本为 iproute2 6.18.0。
补齐测试环境后的最终相关回归:28 项全部通过、无跳过,覆盖上述确定性边界、
真实 ubus 数据/短信事件、监听器死亡、模组移除、保留用户关闭数据、NDP 事件和
实际 iproute2 订阅;日志为
`20261023-111600-u30air-event-fix-final-23401/command.log`。
同一运行随后延长观察 45.34 秒,输入 86 次网络事件:看守进程始终存活、
没有 AT/拨号调用、监听器 stderr 为空;使用带诊断输出的当前事件库副本。
此前该场景约 20 秒就退出,修复后的这轮未再出现。
实机诊断、配置摘要和版本比对保存在本机 `work/u30air-regression/`;
其中敏感摘要不纳入版本库。
## 未验证项目
本轮未进行真实 SIM 热插拔、切卡、短信收发、通话、蓝牙、休眠唤醒、拔 USB、
低电量充电呼吸灯或整机重启计时;这些不能用隔离测试代替。
当前联网与热点状态正常,不等于重新测量了从开机到联网/热点就绪的时间。
+3
View File
@@ -32,6 +32,9 @@
## U30 Air 原生双卡
以下记录为历史实现。2026-10-23 已改为共享手动双卡管理,见
[当前行为及实测](U30AIR-MANUAL-DUAL-SIM-20261023.zh-CN.md)。
原生冷启动和热切换脚本来自上游 [0d520f4](https://github.com/dikeckaan/mu300-linux/commit/0d520f4),按本仓库的接口适配。
- U30 Air 同一时间只启用一张卡的射频;不能照搬 V50 同时启动两个射频的流程。
+65
View File
@@ -0,0 +1,65 @@
# U30 Air 热点启动延迟修复
2026-10-23,完整服务/内核移植部署后,用户反馈热点出现仍较慢。已定位、修复共享
启动脚本,并在同一台 U30 Air / OpenWrt 25.12.5 / 7.2.8 #56 部署验证。
## 已确认原因
启动打点显示 `regdb-load` 从内核 uptime 9.44 秒运行至 29.79 秒,耗时 20.35 秒;
后续模块索引几乎不耗时,WCN 在约 30.4 秒开始加载,热点约 41 秒进入 AP-ENABLED。
原设置为 CN、5 GHz、36 信道、VHT80,不是 DFS CAC 等待。
这台实际运行内核设置为 `# CONFIG_FW_LOADER_USER_HELPER is not set`,
`/sys/class/firmware` 不存在。旧 `regdb-load` 仍为 regulatory.db 及其签名分别等待
sysfs 请求节点,造成一段根本不可能满足的等待。之后正常 `iw reg reload` 成功,
并非数据库或签名损坏。
## 修复范围
- 共享 `rootfs/overlay/opt/mu300/bin/regdb-load` 在 firmware sysfs class 不存在时
跳过请求节点等待,仍执行原来的 `iw reg reload`,仍由内核验证监管数据库签名。
- 有该 class 的内核保留数据库、签名的原交接及有界等待;reload 失败仍重试并报错。
没有通过失败切换其他后端、跳过签名、改国家码或放宽信道规则。
- OpenWrt/Ubuntu 使用同一脚本,进入现有共享构建和更新载荷,不做 U30 特例。
- 在 `mu300-hw`、`wifi-start` 增加一次性启动阶段打点,记录监管库、索引、驱动、
额外模块、配置及 NFC 阶段,便于继续诊断;没有增加常驻轮询。
- 只部署三个脚本;本次没有重新编译内核、GUI、完整 rootfs 或发行包。
## 实机结果
| 时间点 | 修复前 | 修复后 |
| --- | --- | --- |
| board 检查完成 | 9.44 s | 9.36 s |
| 监管库准备阶段完成 | 29.79 s | 9.71 s |
| 该阶段耗时 | **20.35 s** | **0.35 s** |
| WCN 驱动开始加载 | 约 30.4 s | 10.37 s |
| WLAN 驱动就绪 | 35.43 s | 15.39 s |
| 热点 AP-ENABLED / wlan0 桥转发 | 约 **41 s** | 约 **21 s** |
热点提前约 20 秒。阶段耗时来自 `bootmark` 的内核 uptime;AP 的状态由 hostapd
日志和内核 wlan0 forwarding 事件交叉核对,不将 `wifi up` 命令返回当作 AP 已就绪。
这是本次设备的冷启动观测,不作为其他机型或长期统计结果。
用户已用手机确认**能连接热点并上网**。同时复核:
- 国家码仍是 CN,36 信道、80 MHz;监管域正常。
- 蜂窝地址就绪 27.74 秒,WAN 和热点同时 up;原生 modem 的六个命令通道均 open。
- network、wireless、unisoc_modem、unisoc_apn、mu300-charge 以及 Android boot A
的 SHA-256 均与完整部署前备份一致。
- 无新 BUG、Oops、WARNING 或 Kernel panic;三个部署文件均与当前源码 SHA-256 相符。
## 自动化验证及备份
7 项相关测试全部通过,覆盖无 firmware helper 时零等待、数据库与签名均在 reload
之前完整交接、reload 失败仍有界重试报错、启动顺序、可用热点不重启、不可用热点的
既有单次复核、Unix 换行及既有恢复路径。测试的 sysfs、文件和命令均为私有夹具,
没有用模拟交接冒充实际签名验证或手机联网验证。
- [自动化回归](../out/build-logs/20261023-054646-wifi-regdb-final-regression-62478/command.log)
- [修复前启动打点](../out/build-logs/20261023-054217-wifi-boot-profile-62173/command.log)
- [修复后冷启动](../out/build-logs/20261023-054432-wifi-regdb-fixed-coldboot-62458/command.log)
私有原始观测位于 `work/full-live/wifi-start-baseline.json`、
`work/full-live/wifi-fixed-evidence.json`;部署前脚本和最终校验在 `work/wifi-boot/`。
设备备份目录为 `/mnt/mu300-disk/.mu300/backups/wifi-start-20261023/`。
完整部署清单已同步三个新哈希;原有启动分区和整批运行时备份继续保留。
+4 -3
View File
@@ -513,8 +513,9 @@ docker build -q -t mu300-ubuntu:24.04 "$TOP/rootfs" >/dev/null
docker run --rm mu300-ubuntu:24.04 cat /bin/busybox > "$WORK/busybox"; chmod +x "$WORK/busybox"
docker run --rm -v "$TOP/tools":/src:ro -v "$WORK/tools":/o mu300-kbuild sh -c '
gcc -O2 -static -o /o/logdw/logdw /src/logdw/logdw.c &&
gcc -O2 -static -o /o/bt-init/mu300-bt-init /src/bt-init/mu300-bt-init.c &&
mkdir -p /o/keys && gcc -O2 -static -o /o/keys/mu300-keys /src/keys/mu300-keys.c'
gcc -O2 -static -o /o/bt-init/mu300-bt-init /src/bt-init/mu300-bt-init.c'
sh "$TOP/tools/keys/build.sh" "$WORK/tools/keys"
sh "$TOP/tools/atd-io/build.sh" "$WORK/tools/atd-io"
# the VPN engines, as tools/make-release.sh puts them into the published images (without them mu300-vpn only
# fails with "xray: not found")
[ -s "$WORK/sing-box" ] || sh "$TOP/tools/fetch-sing-box.sh" "$WORK/sing-box"
@@ -540,7 +541,7 @@ case " $OSES " in *" ubuntu "*) reuse ubuntu || {
# shellcheck disable=SC2086
docker run --rm -v "$B":/w -v "$WORK/out/modules":/kmods:ro -v "$WORK/out":/kout:ro -v "$WORK/firmware":/firmware:ro \
-v "$WORK/android-subset":/android-subset:ro -v "$WORK/tools/logdw/logdw":/logdw:ro \
-v "$WORK/tools/bt-init/mu300-bt-init":/bt-init:ro -v "$WORK/tools/keys/mu300-keys":/keys:ro -v "$WORK/sing-box":/sing-box:ro -v "$WORK/xray":/xray:ro \
-v "$WORK/tools/bt-init/mu300-bt-init":/bt-init:ro -v "$WORK/tools/keys/mu300-keys":/keys:ro -v "$WORK/tools/atd-io/mu300-atd-io":/atd-io:ro -v "$WORK/sing-box":/sing-box:ro -v "$WORK/xray":/xray:ro \
-v "$WORK/hev-socks5-tunnel":/hev-socks5-tunnel:ro $gpuargs mu300-ubuntu:24.04 bash /w/assemble.sh >/dev/null
mv "$B/mu300-ubuntu-24.04-rootfs.tar.gz" "$WORK/mu300-ubuntu.tar.gz"; rm -rf "$B"; } ;;
esac
+16 -8
View File
@@ -124,19 +124,19 @@ ls "$IN/out/modules"/*.ko >/dev/null 2>&1 || {
}
# The optional ones decide whether the image can use the modem, Wi-Fi, the GPU or the VPN at all. Missing ones
# used to be skipped silently, which produces an image that boots and then does nothing useful.
for o in firmware android-subset android-gpu-subset tools/logdw/logdw tools/bt-init/mu300-bt-init tools/keys/mu300-keys tools/gpu/cltest busybox upstream/out/modules; do
for o in firmware android-subset android-gpu-subset tools/logdw/logdw tools/bt-init/mu300-bt-init tools/keys/mu300-keys tools/atd-io/mu300-atd-io tools/gpu/cltest busybox upstream/out/modules; do
[ -e "$IN/$o" ] && echo " + $o" || echo " - $o (missing: the image is built without it)"
done
# shellcheck disable=SC2046
docker run --rm --platform linux/arm64 \
-v "${MU300_RELEASE_JSON:-$TOP/work}":/in/release.json:ro \
-v "$TOP/rootfs/overlay/opt/mu300":/in/opt-mu300:ro -v "$TOP/openwrt/overlay":/in/overlay:ro \
-v "$TOP/rootfs/overlay/opt/mu300":/in/opt-mu300:ro -v "$TOP/rootfs/overlay/usr/share/ucode/mu300":/in/ucode-mu300:ro -v "$TOP/openwrt/overlay":/in/overlay:ro \
-v "$TOP/openwrt/patches/fw4-sipa-offload.patch":/in/fw4-sipa-offload.patch:ro \
-v "$TOP/openwrt/patches/wifi-scripts-no-dfs.patch":/in/wifi-scripts-no-dfs.patch:ro \
-v "$TOP/boot/module-order.txt":/in/module-order.txt:ro -v "$IN/out/modules":/in/modules:ro \
$(opt out/modules.builtin modules.builtin) $(opt out/modules.builtin.modinfo modules.builtin.modinfo) \
$(opt firmware firmware) $(opt android-subset android-subset) $(opt android-gpu-subset android-gpu-subset) \
$(opt tools/logdw/logdw logdw) $(opt tools/bt-init/mu300-bt-init bt-init) $(opt tools/keys/mu300-keys keys) $(opt tools/gpu/cltest cltest) \
$(opt tools/logdw/logdw logdw) $(opt tools/bt-init/mu300-bt-init bt-init) $(opt tools/keys/mu300-keys keys) $(opt tools/atd-io/mu300-atd-io atd-io) $(opt tools/gpu/cltest cltest) \
$(opt busybox busybox) $(mainline_opt modules mainline-modules) $(plugin_opt) -v "$ROOTFS_DIR":/out -v "$REGDB":/in/regdb:ro \
$(mainline_opt modules.builtin mainline-modules.builtin) $(mainline_opt modules.builtin.modinfo mainline-modules.builtin.modinfo) \
-v "$THEME_APK":/in/luci-theme-aurora.apk:ro \
@@ -164,7 +164,7 @@ apk_retry update >/dev/null
# i2c-tools, gpiod-tools: mu300-usb (the charger of the U30 Air) and mu300-nfc (its NFC tag)
apk_retry add --allow-untrusted /in/wifi-sae/*.apk >/dev/null
# The cipher capability helper needs the section omitted by reduced iw builds.
apk_retry add iwinfo wireless-regdb iw-full bash ip-full coreutils-stty openssl-util curl ca-bundle msmtp ucode ucode-mod-fs ucode-mod-ubus ucode-mod-uci ucode-mod-uloop ucode-mod-socket \
apk_retry add iwinfo wireless-regdb iw-full bash ip-full coreutils-stty openssl-util curl ca-bundle msmtp luci-base rpcd-mod-ucode ucode ucode-mod-fs ucode-mod-ubus ucode-mod-uci ucode-mod-uloop ucode-mod-nl80211 ucode-mod-rtnl ucode-mod-socket \
i2c-tools gpiod-tools flock ttyd luci-app-ttyd luci-i18n-ttyd-zh-cn luci-i18n-ttyd-tr python3 >/dev/null
apk_retry add --allow-untrusted /in/block-mount-mu300.apk >/dev/null
apk_retry add --allow-untrusted /in/luci-theme-aurora.apk >/dev/null
@@ -189,6 +189,8 @@ printf "127.0.0.1\tlocalhost\n\n::1\tlocalhost ip6-localhost ip6-loopback\nff02:
printf "mu300\n" > $R/etc/hostname # the real one comes from uci (etc/uci-defaults/90-mu300)
cp -a /in/opt-mu300 $R/opt/mu300
cp -a /in/overlay/. $R/
mkdir -p $R/usr/share/ucode/mu300
cp -a /in/ucode-mu300/. $R/usr/share/ucode/mu300/
chmod 0755 $R/etc/uci-defaults/95-disable-ap-uapsd
chmod 0755 $R/etc/init.d/unisoc-battery $R/etc/hotplug.d/power_supply/80-unisoc-battery
mkdir -p $R/etc/mu300
@@ -199,13 +201,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
chmod 0755 $R/opt/mu300/bin/mu300-lowlatency
for helper in mu300-data-sim-u30 mu300-sim-u30 mu300-sim2-start mu300-sim2-warmup u30air-led-status; do
chmod 0755 $R/opt/mu300/bin/mu300-lowlatency $R/opt/mu300/bin/wifi-ready $R/opt/mu300/bin/mu300-service-cpus $R/etc/init.d/mu300-service-cpus
chmod 0755 $R/etc/init.d/mu300-sysd
for helper in mu300-data-sim-u30 mu300-sim-u30 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; }
[ -s "$R/opt/mu300/lib/sms-pool.sh" ] || { echo "missing shared SMS pool library" >&2; exit 1; }
chmod 0755 $R/etc/hotplug.d/power_supply/70-mu300-led
chmod 0755 $R/opt/mu300/bin/mu300-platform-config
@@ -243,8 +245,12 @@ if [ -d /in/luci-plugin ]; then
ucode $R/usr/libexec/unisoc-modem/filter-wifi-ciphers $R
chmod 0755 $R/etc/init.d/unisoc-cpu $R/etc/init.d/unisoc-cpu-cores $R/usr/libexec/rpcd/unisoc-cpu-cores
chmod 0600 $R/etc/config/unisoc_apn
chmod 0755 $R/etc/init.d/unisoc-ttl $R/etc/hotplug.d/iface/92-unisoc-ttl $R/etc/uci-defaults/98-unisoc-ttl
chmod 0755 $R/etc/uci-defaults/97-unisoc-upgrade-policy
chmod 0755 $R/etc/init.d/unisoc-modem-ui $R/etc/init.d/unisoc-sms-forward $R/etc/init.d/unisoc-traffic $R/etc/hotplug.d/net/90-unisoc-usb-host $R/etc/hotplug.d/iface/90-unisoc-usb-host $R/usr/libexec/rpcd/mu300dash $R/usr/libexec/unisoc-modem/*
# rpcd refuses world-writable plugins from a Windows bind mount.
chmod 0644 $R/usr/share/rpcd/ucode/*.uc $R/usr/share/ucode/mu300/*.uc
chroot "$R" /usr/bin/ucode -e 'import * as dash from "mu300.dash"; import * as rates from "mu300.rates"; import * as placement from "mu300.service-cpus";'
mkdir -p $R/usr/lib/lua/luci/i18n
cp -a /in/luci-plugin/lmo/. $R/usr/lib/lua/luci/i18n/
# The source-tree install does not run the package postinst. Register only
@@ -270,6 +276,7 @@ fi
[ -e /in/logdw ] && { cp /in/logdw $R/opt/mu300/bin/logdw; chmod 755 $R/opt/mu300/bin/logdw; }
[ -e /in/bt-init ] && { cp /in/bt-init $R/opt/mu300/bin/mu300-bt-init; chmod 755 $R/opt/mu300/bin/mu300-bt-init; }
[ -e /in/keys ] && { cp /in/keys $R/opt/mu300/bin/mu300-keys; chmod 755 $R/opt/mu300/bin/mu300-keys; }
[ -e /in/atd-io ] && { cp /in/atd-io $R/opt/mu300/bin/mu300-atd-io; chmod 755 $R/opt/mu300/bin/mu300-atd-io; }
# full static busybox for the tools OpenWrt busybox leaves out (od, timeout, mountpoint, losetup, rfkill, telnetd)
if [ -e /in/busybox ]; then
cp /in/busybox $R/opt/mu300/bin/busybox; chmod 755 $R/opt/mu300/bin/busybox
@@ -298,7 +305,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-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
for s in mu300-accounts mu300-cpu-driver mu300-service-cpus mu300-vendor mu300-charge-mode mu300-hw mu300-post mu300-toolkit mu300-atd mu300-network-recovery mu300-modem-log mu300-wifi-client mu300-sysd 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
@@ -310,6 +317,7 @@ if [ -d /in/luci-plugin ]; then
ln -sf ../init.d/unisoc-sms-forward $R/etc/rc.d/S$n"unisoc-sms-forward"
n=$(sed -n "s/^START=//p" $R/etc/init.d/unisoc-traffic)
ln -sf ../init.d/unisoc-traffic $R/etc/rc.d/S$n"unisoc-traffic"
ln -sf ../init.d/unisoc-ttl $R/etc/rc.d/S97unisoc-ttl
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-cores $R/etc/rc.d/S99unisoc-cpu-cores
+20 -2
View File
@@ -2,7 +2,7 @@ include $(TOPDIR)/rules.mk
PKG_NAME:=luci-app-mu300
PKG_VERSION:=1.2.0
PKG_RELEASE:=20
PKG_RELEASE:=23
PKG_LICENSE:=MIT
PKG_MAINTAINER:=MU300 Linux contributors
PKGARCH:=all
@@ -14,7 +14,7 @@ define Package/luci-app-mu300
CATEGORY:=LuCI
SUBMENU:=3. Applications
TITLE:=Unisoc modem control center
DEPENDS:=+luci-base +rpcd +jsonfilter +curl +ca-bundle +openssl-util +msmtp +ucode +ucode-mod-fs +ucode-mod-ubus +ucode-mod-uci +ucode-mod-uloop
DEPENDS:=+luci-base +firewall4 +nftables-json +flock +rpcd +rpcd-mod-ucode +jsonfilter +curl +ca-bundle +openssl-util +msmtp +ucode +ucode-mod-fs +ucode-mod-ubus +ucode-mod-uci +ucode-mod-uloop +ucode-mod-nl80211 +ucode-mod-rtnl
endef
define Package/luci-app-mu300/description
@@ -24,6 +24,8 @@ define Package/luci-app-mu300/description
endef
define Package/luci-app-mu300/conffiles
/etc/mu300/ttl.conf
/etc/mu300/ttl.offload-off
/etc/mu300/sim-radio
/etc/config/unisoc_modem
/etc/config/unisoc_apn
@@ -40,6 +42,7 @@ define Package/luci-app-mu300/install
$(INSTALL_DIR) $(1)/www
$(CP) ./htdocs/. $(1)/www/
$(CP) ./root/. $(1)/
chmod 0644 $(1)/usr/share/rpcd/ucode/*.uc $(1)/usr/share/ucode/mu300/*.uc
chmod 0755 $(1)/etc/init.d/unisoc-cpu-cores $(1)/usr/libexec/rpcd/unisoc-cpu-cores $(1)/usr/libexec/unisoc-modem/cpu-cores
chmod 0600 $(1)/etc/config/unisoc_apn
chmod 0755 $(1)/etc/uci-defaults/97-unisoc-upgrade-policy
@@ -47,6 +50,7 @@ define Package/luci-app-mu300/install
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/*
chmod 0755 $(1)/etc/init.d/unisoc-ttl $(1)/etc/hotplug.d/iface/92-unisoc-ttl $(1)/etc/uci-defaults/98-unisoc-ttl
$(INSTALL_DIR) $(1)/usr/lib/lua/luci/i18n
$(CP) ./lmo/. $(1)/usr/lib/lua/luci/i18n/
endef
@@ -54,6 +58,7 @@ endef
define Package/luci-app-mu300/postinst
#!/bin/sh
[ -n "$${IPKG_INSTROOT}" ] || {
ucode -e 'import * as dash from "mu300.dash"; import * as rates from "mu300.rates";' || exit 1
/usr/libexec/unisoc-modem/refresh-config
chmod 0600 /etc/config/unisoc_apn
state=$$(uci -q get unisoc_modem.main.state_dir 2>/dev/null)
@@ -69,6 +74,8 @@ define Package/luci-app-mu300/postinst
rm -f /tmp/luci-indexcache /tmp/luci-modulecache/* 2>/dev/null
uci -q get luci.languages.tr >/dev/null || uci set luci.languages.tr='Türkçe'
uci commit luci
/etc/init.d/unisoc-ttl enable
/etc/init.d/unisoc-ttl start || exit 1
/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
@@ -84,6 +91,17 @@ define Package/luci-app-mu300/postinst
exit 0
endef
define Package/luci-app-mu300/prerm
#!/bin/sh
[ -n "$${IPKG_INSTROOT}" ] || {
if [ "$$1" = remove ]; then
/usr/libexec/unisoc-modem/ttl-engine off || exit 1
/etc/init.d/unisoc-ttl disable
fi
}
exit 0
endef
define Package/luci-app-mu300/postrm
#!/bin/sh
[ -n "$${IPKG_INSTROOT}" ] || {
@@ -53,13 +53,13 @@ function simSelector(root) {
select.onchange=function() { selectViewedSlot(select.value); location.reload(); };
}).catch(function() {});
}
var callRates = rpc.declare({ object: 'mu300dash', method: 'rates', nobatch: true, expect: { '': {} } });
var callCells = scopedRpc({ object: 'mu300dash', method: 'cells', nobatch: true, expect: { '': {} } });
var callStatus = scopedRpc({ object: 'mu300dash', method: 'status', nobatch: true, expect: { '': {} } });
var callSignal = scopedRpc({ object: 'mu300dash', method: 'signal', nobatch: true, expect: { '': {} } });
var callSysinfo = rpc.declare({ object: 'mu300dash', method: 'sysinfo', nobatch: true, expect: { '': {} } });
var callRates = rpc.declare({ object: 'mu300rates', method: 'rates', nobatch: true, expect: { '': {} } });
var callCells = scopedRpc({ object: 'mu300status', method: 'cells', nobatch: true, expect: { '': {} } });
var callStatus = scopedRpc({ object: 'mu300status', method: 'status', nobatch: true, expect: { '': {} } });
var callSignal = scopedRpc({ object: 'mu300.modem', method: 'signal', nobatch: true, expect: { '': {} } });
var callSysinfo = rpc.declare({ object: 'mu300status', method: 'sysinfo', nobatch: true, expect: { '': {} } });
var callAct = scopedRpc({ object: 'mu300dash', method: 'act', params: [ 'op', 'arg' ], expect: { '': {} } });
var callAt = scopedRpc({ object: 'mu300dash', method: 'at', params: [ 'cmd' ], expect: { '': {} } });
var callAt = scopedRpc({ object: 'mu300dash', method: 'at', nobatch: true, params: [ 'cmd' ], expect: { '': {} } });
var callAtHist = scopedRpc({ object: 'mu300dash', method: 'at_history', expect: { '': {} } });
var callLockGet = scopedRpc({ object: 'mu300dash', method: 'lock_get', nobatch: true, expect: { '': {} } });
var callLockFresh = scopedRpc({ object: 'mu300dash', method: 'lock_get', nobatch: true, params: [ 'fresh' ], expect: { '': {} } });
@@ -89,6 +89,7 @@ function waitLockJob(started, active) {
check();
});
}
var callSmsHead = scopedRpc({ object: 'mu300status', method: 'sms_head', nobatch: true, expect: { '': {} } });
var callSmsList = scopedRpc({ object: 'mu300dash', method: 'sms_list', params: [ 'page' ], expect: { '': {} } });
var callSmsShow = scopedRpc({ object: 'mu300dash', method: 'sms_show', params: [ 'id' ], expect: { '': {} } });
var callSmsSend = scopedRpc({ object: 'mu300dash', method: 'sms_send', params: [ 'num', 'text' ], expect: { '': {} } });
@@ -104,6 +105,8 @@ var callForwardTest = rpc.declare({ object: 'mu300dash', method: 'forward_test',
var callTrafficGet = scopedRpc({ object: 'mu300dash', method: 'traffic_get', expect: { '': {} } });
var callTrafficSet = scopedRpc({ object: 'mu300dash', method: 'traffic_set', params: [ 'payload' ], expect: { '': {} } });
var callTrafficClear = scopedRpc({ object: 'mu300dash', method: 'traffic_clear', nobatch: true, params: [ 'confirm' ], expect: { '': {} } });
var callTtlGet = rpc.declare({ object: 'mu300dash', method: 'ttl_get', expect: { '': {} } });
var callTtlSet = rpc.declare({ object: 'mu300dash', method: 'ttl_set', params: [ 'value' ], expect: { '': {} }, nobatch: true });
var callUsbGet = rpc.declare({ object: 'mu300dash', method: 'usb_get', expect: { '': {} } });
var callUsbSet = rpc.declare({ object: 'mu300dash', method: 'usb_set', params: [ 'kind', 'value', 'scope', 'auto' ], expect: { '': {} } });
var callUsbNetList = rpc.declare({ object: 'mu300dash', method: 'usb_net_list', expect: { '': {} } });
@@ -113,6 +116,28 @@ 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 = {
"另一项 TTL 操作正在执行,请稍后重试": ["Another TTL operation is running; please retry shortly", "Başka bir TTL işlemi çalışıyor; biraz sonra yeniden deneyin"],
"当前设置": ["Current setting", "Geçerli ayar"],
"固定为 %d": ["Fixed at %d", "%d olarak sabit"],
"保持不变(默认)": ["Not changed (default)", "Değiştirilmedi (varsayılan)"],
"生效规则": ["Rule in force", "Etkin kural"],
"流量卸载": ["Flow offloading", "Akış hızlandırma"],
"已启用": ["Enabled", "Etkin"],
"已禁用": ["Disabled", "Devre dışı"],
"蜂窝网络 TTL": ["Cellular TTL", "Mobil veri TTL"],
"设为 %d": ["Set %d", "%d ayarla"],
"设置": ["Set", "Ayarla"],
"关闭 TTL": ["Turn off TTL", "TTL kapat"],
"请输入 1 至 255 的整数": ["Enter an integer from 1 to 255", "1 ile 255 arasında tam sayı girin"],
"设置会保留到重启后;默认关闭。": ["Settings persist after reboot; disabled by default.", "Ayarlar yeniden başlatmada korunur; varsayılan kapalıdır."],
"操作失败:%s": ["Failed: %s", "Başarısız: %s"],
"管理连接已断开": ["Management connection lost", "Yönetim bağlantısı kesildi"],
"无法读取 TTL 设置": ["Cannot read TTL settings", "TTL ayarı okunamadı"],
"无法应用 TTL 设置": ["Cannot apply TTL settings", "TTL ayarı uygulanamadı"],
"TTL 无效": ["Invalid TTL", "Geçersiz TTL"],
"设置蜂窝出口数据包的 TTL 和 IPv6 跳数限制;仅影响蜂窝网络,不改变 Wi-Fi 或 USB 局域网。": ["Set the TTL and IPv6 hop limit of cellular outbound packets. Local Wi-Fi and USB traffic are unchanged.", "Hücresel çıkışın TTL ve IPv6 atlama sınırını ayarlar. Yerel Wi-Fi ve USB trafiğini değiştirmez."],
"启用后会关闭防火墙流量卸载,可能降低转发性能;关闭 TTL 后恢复由本功能修改的卸载设置。": ["Enabling TTL disables firewall flow offloading and may reduce forwarding performance. Turning TTL off restores offloading settings changed by this feature.", "TTL etkinleştirilince akış hızlandırması kapatılır; performans düşebilir. Kapatıldığında bu özelliğin değiştirdiği ayarlar geri yüklenir."],
"自动模式兼容性": ["Automatic mode compatibility", "Otomatik mod uyumluluğu"],
"机型默认": ["Model default", "Model varsayılanı"],
"全制式自动(134,含 2G)": ["All-RAT auto (134, includes 2G)", "Tüm teknolojiler otomatik (134, 2G dahil)"],
@@ -1780,17 +1805,25 @@ function notify(title, message, opts) {
}
/* 新短信监视(每个页面 render 时调用一次,内部单例):
* 每 5 s 读一次本地池第 1 页(纯文件读,不打 AT),首次只记基线;
* 每 5 s 读取本地池签名,仅变化时读取第 1 页;首次只记基线;
* 之后出现更大的消息 id 且为收件(mt)时,按手机通知样式弹出
* 「发件人 + 预览」。池子被清空(id 回落)时静默重建基线。 */
var smsWatch = null;
function watchSms() {
if (smsWatch) return;
smsWatch = { seen: [null,null], inflight: false };
smsWatch = { seen: [null,null], heads: [null,null], inflight: false };
window.setInterval(function() {
if(document.hidden || smsWatch.inflight)return;
var slot=Number(selectedSlot()); smsWatch.inflight=true;
Promise.resolve(callSmsList(1)).catch(function() { return {}; }).then(function(r) {
Promise.resolve(callSmsHead()).then(function(head) {
if (!head || head.error) throw new Error(head && head.error || 'Unable to read SMS state');
if (Number(selectedSlot()) !== slot) return null;
if (head.adapter === true) return callSmsList(1);
var signature = JSON.stringify(head);
if (smsWatch.heads[slot] === signature) return null;
return callSmsList(1).then(function(list) { smsWatch.heads[slot] = signature; return list; });
}).then(function(r) {
if (!r) return;
r = r || {};
var msgs = r.msgs || [], max = 0;
msgs.forEach(function(m) {
@@ -1807,7 +1840,7 @@ function watchSms() {
});
smsWatch.seen[slot] = max;
}
}).finally(function(){smsWatch.inflight=false;});
}).catch(function() { /* Keep the baseline: retry the same read on the next tick. */ }).finally(function(){smsWatch.inflight=false;});
}, 5000);
}
@@ -1877,7 +1910,7 @@ return baseclass.extend({
callForwardSet: callForwardSet, callForwardTest: callForwardTest, callForwardClear: callForwardClear,
callTrafficGet: callTrafficGet, callTrafficSet: callTrafficSet,
callTrafficClear: callTrafficClear,
callUsbGet: callUsbGet, callUsbSet: callUsbSet,
callTtlGet: callTtlGet, callTtlSet: callTtlSet, callUsbGet: callUsbGet, callUsbSet: callUsbSet,
callUsbNetList: callUsbNetList, callUsbNetAdd: callUsbNetAdd,
carrierName: carrierName, qLabel: qLabel, qCol: qCol, qScore: qScore,
esc: esc, fmtBatteryCurrent: fmtBatteryCurrent, fmtBytes: fmtBytes, fmtTrafficBytes: fmtTrafficBytes, fmtRate: fmtRate, fmtUptime: fmtUptime, PLMN_CN: PLMN_CN,
@@ -45,7 +45,7 @@ function attach(root) {
var disposed=false, pending=false, flags=null, supported=[true,true], readRevision=0;
root.innerHTML='<h3></h3><p class="mud-note"></p><div data-radios></div><p role="status" aria-live="polite"></p>';
root.querySelector('h3').textContent=M.translate('SIM 射频');
root.querySelector('.mud-note').textContent=M.translate('分别控制每张卡的射频并记住设置。关闭后该卡无法通话、收发短信或上网;不会自动切换到另一张卡。') + ' ' + M.translate('SIM2 默认关闭射频;手动开启或主动切换到 SIM2 会开启并记住选择。已有明确的射频设置和 SIM2 上网选择会保留。');
root.querySelector('.mud-note').textContent=M.translate('分别控制每张卡的射频并记住设置。关闭后该卡无法通话、收发短信或上网;不会自动切换到另一张卡。');
var buttons=[], result=root.querySelector('[role=status]'), rows=root.querySelector('[data-radios]');
rows.style.cssText='display:grid;gap:12px;margin:16px 0';
[0,1].forEach(function(slot) {
@@ -622,10 +622,10 @@ return view.extend({
M.v('batt-bar').style.width = (batteryPct == null ? 0 : batteryPct) + '%';
if (p.present && p.capacity != null) {
M.set('batt', p.capacity + '%');
M.set('batt-l', (p.status || '--') + (p.volt != null ? ' · ' + p.volt + ' V' : '') + ' · ' + M.fmtBatteryCurrent(p.ua) + (p.usb ? ' · USB' : ''));
M.set('batt-l', (p.status || '--') + (Number.isFinite(p.volt) ? ' · ' + p.volt.toFixed(2) + ' V' : '') + ' · ' + M.fmtBatteryCurrent(p.ua) + (p.usb ? ' · USB' : ''));
} else {
M.set('batt', p.usb ? 'USB' : '--');
M.set('batt-l', '电源' + (p.volt != null ? ' · ' + p.volt + ' V' : ''));
M.set('batt-l', '电源' + (Number.isFinite(p.volt) ? ' · ' + p.volt.toFixed(2) + ' V' : ''));
}
M.set('model', i.model || '--');
M.set('fwos', i.fw || '--');
@@ -10,9 +10,9 @@ var getV50=rpc.declare({object:'mu300dash',method:'v50_sim_get',nobatch:true,exp
var start=rpc.declare({object:'mu300dash',method:'data_sim_set',params:['target'],nobatch:true,expect:{'':{}}});
var status=rpc.declare({object:'mu300dash',method:'data_sim_status',params:['id'],nobatch:true,expect:{'':{}}});
var errors={dual_sim_unavailable:'当前配置不支持双卡切换',invalid_sim:'SIM 卡槽无效',modem_busy:'另一项模组操作正在执行',sim_read_failed:'无法核验当前上网卡',sim_not_ready:'目标 SIM 尚未就绪',data_disconnect_failed:'旧数据连接未停止,已取消切换',sim_switch_failed_restored:'切换失败,已恢复原上网卡',sim_rollback_failed:'切换失败且恢复不完整,请检查 SIM 和信号',storage_failed:'设置保存失败'};
errors['Enable the target SIM radio before switching']='请先开启目标 SIM 的射频,再切换上网卡';
errors.dual_boot_required='双卡尚未共同初始化,请重启后检查状态';
Object.assign(errors,{v50_board_unknown:'无法识别 V50 硬件版本,未更改选卡',v50_card_unsupported:'此功能仅适用于 V50',v50_card_unavailable:'此硬件版本没有所选 SIM',v50_mux_unavailable:'SIM 选择驱动尚未就绪,请更新内核并重启',v50_card_power_failed:'SIM 电源切换未完成',v50_mux_write_failed:'SIM 硬件选择失败'});
Object.assign(errors,{"Enable hot switching first": "请先启用双卡热切换", "Persistent dual-SIM brokers unavailable; reboot first": "双卡通道尚未准备完成,请先重启", "Unknown active SIM; reboot first": "当前上网卡状态未知,请重启", "Unexpected radio state; reboot first": "射频状态异常,请先重启", "No card answers in the target SIM position; nothing was changed": "目标卡槽未检测到 SIM,未进行切换", "The target SIM is locked by its PIN; nothing was changed": "目标 SIM 需要 PIN,未进行切换", "Target SIM got no data within the time; previous SIM restored": "目标卡未建立数据连接,已恢复原卡", "Target SIM has no data yet and the previous SIM had none either; staying on the target, boot default unchanged": "两卡均暂无数据连接,保留当前选卡,开机默认卡未更改", "Active SIM has no data; use default for next-boot selection": "当前卡暂无数据连接,可单独保存为下次开机默认卡", "Cannot stop WAN": "无法停止蜂窝连接,已取消切换", "Interrupted switch; reboot first": "上次切卡被中断,请先重启", "Network locks are being applied": "网络锁定正在应用,请稍后再试", "Previous SIM restored but WAN could not be started": "已恢复原卡,但蜂窝连接未能启动", "Resume the modem before switching": "请先恢复基带运行再切卡", "SIM control is busy": "另一项 SIM 设置正在执行", "SIM switched but the boot default could not be saved": "上网卡已切换,但开机默认卡保存失败", "Switch failed; previous SIM restored": "切卡失败,已恢复原卡", "Switch failed; radio state unknown, reboot required": "切卡失败且射频状态未知,需要重启", "Target SIM got no data and the previous one could not be restored; reboot required": "目标卡无数据且原卡恢复失败,需要重启", "Target SIM got no data; previous SIM restored but WAN could not be started": "目标卡无数据,已恢复原卡但蜂窝连接未启动", "The modem is busy; nothing was changed, try again": "基带正忙,未进行切换,请重试", "The target SIM could not be powered; nothing was changed": "目标 SIM 无法上电,未进行切换", "Unknown radio state; reboot first": "射频状态未知,请先重启", "flock is required for SIM control": "缺少 SIM 互斥组件,请更新完整系统"});
function message(s){return M.translate(errors[s]||s);}
function el(tag,text,cls) { var n=document.createElement(tag); if(text!=null)n.textContent=text; if(cls)n.className=cls; return n; }
function card(n) { return n===0||n===1 ? 'SIM '+(n+1) : M.translate('未连接'); }
@@ -51,30 +51,11 @@ return view.extend({
row.append(label,select,button); controls.append(row);
var summary=el('div',null,'mud-sim-status'); summary.append(actual,connection,saved); controls.append(summary);
controls.append(el('p',M.translate('切换会短暂中断蜂窝网络,成功后作为开机默认上网卡;不会切换 USB 或 Wi-Fi。'),'mud-note'));
controls.append(el('p',M.translate(data[1].native ? 'U30 Air 每次仅启用一张卡的射频。目标卡无数据且原卡有数据时,会恢复原卡;开机默认卡只在连接成功后自动保存。' : '欠费或无信号不影响选卡;数据连接失败不会自动切回。'),'mud-note'));
var nativeBox=null, nativeHot=null, nativeSave=null, nativeNote=null, last=data[1];
if(data[1].native) {
nativeBox=el('div',null,'mud-data-sim'); panel.append(nativeBox);
nativeBox.append(el('h3',M.translate('U30 Air 原生双卡')));
var hotLabel=el('label',null,'mud-data-sim-controls'); nativeHot=el('input'); nativeHot.type='checkbox';
hotLabel.append(nativeHot,el('span',M.translate('启用双卡热切换(首次启用后需重启)'))); nativeBox.append(hotLabel);
nativeNote=el('p',null,'mud-note'); nativeBox.append(nativeNote);
nativeSave=el('button',M.translate('仅保存为下次开机默认卡'),'mud-btn'); nativeSave.type='button'; nativeBox.append(nativeSave);
nativeBox.append(el('p',M.translate('关闭热切换时仍可选择下次开机使用的 SIM。此设置不会立即切卡或重启。'),'mud-note'));
nativeHot.onchange=function(){configure('u30-hot-'+(nativeHot.checked?'1':'0'),nativeHot);};
nativeSave.onclick=function(){configure('u30-default-'+select.value,nativeSave);};
}
controls.append(el('p',M.translate('欠费或无信号不影响选卡;数据连接失败不会自动切回。'),'mud-note'));
var last=data[1];
function paint(r,initial) {
last=r;
button.disabled=data[0].slots!==2 || !r.ok || r.ready===false || !!self.busy;
if(nativeHot)nativeHot.checked=r.hot===1;
if(nativeNote) {
var ns=r.native_status||{}, note='';
if(ns.result==='reboot_required'||ns.result==='restarting')note='射频状态需要重启恢复,请保留当前开机默认卡';
else if(ns.fallback)note='上次双卡启动未完成,已回退 SIM1';
else if(r.hot===1 && r.ready===false)note='双卡通道尚未就绪;首次启用后请重启';
nativeNote.textContent=M.translate(note); nativeNote.hidden=!note;
}
actual.textContent=M.translate('当前上网卡')+':'+card(r.actual_sim);
saved.textContent=M.translate('开机默认')+':'+card(r.saved_sim);
connection.textContent=M.translate('数据连接')+':'+M.translate(r.data_connected?'已连接':'未连接');
@@ -134,11 +115,11 @@ return view.extend({
} else if(v50.error)panel.append(el('p',message(v50.error),'mud-note'));
button.disabled=data[0].slots!==2 || !data[1].ok || data[1].ready===false;
select.disabled=data[0].slots!==2 || !data[1].ok;
if(button.disabled && !data[1].native)panel.append(el('p',message(data[1].ready===false && data[0].slots===2?'dual_boot_required':'dual_sim_unavailable'),'mud-note'));
if(button.disabled)panel.append(el('p',message(data[1].ready===false && data[0].slots===2?'dual_boot_required':'dual_sim_unavailable'),'mud-note'));
function wait(id) {
return new Promise(function(resolve,reject) {
self.cancelWait=function(){reject(new Error('页面已关闭'));};
var deadline=performance.now()+(data[1].native?360000:240000);
var deadline=performance.now()+240000;
function next() {
if(!root.isConnected)return reject(new Error('页面已关闭'));
if(performance.now()>deadline)return reject(new Error('应用超时,请刷新确认模组状态'));
@@ -151,23 +132,12 @@ return view.extend({
next();
});
}
function configure(target,control) {
if(self.busy)return;
self.busy=true; control.disabled=true; button.disabled=true; select.disabled=true;
if(nativeHot)nativeHot.disabled=true;
if(nativeSave)nativeSave.disabled=true;
start(target).then(function(r){if(!r.ok||!r.id)throw new Error(r.error||'网络设置提交失败');return wait(r.id);})
.then(function(){M.toast('双卡开机设置已保存;需要时请手动重启',{type:'success'});})
.catch(function(e){if(root.isConnected)M.toast(message(e.message),{type:'error'});})
.finally(function(){self.busy=false;select.disabled=false;if(nativeHot)nativeHot.disabled=false;if(nativeSave)nativeSave.disabled=false;
if(root.isConnected)get().then(function(r){if(root.isConnected)paint(r,true);}).catch(function(){});});
}
button.onclick=function() {
if(self.busy)return;
var target=select.value; self.busy=true;
M.confirmBox('切换上网卡?',M.translate('目标卡槽')+':'+card(Number(target)),{danger:true}).then(function(yes) {
if(!yes || !root.isConnected)return;
M.busy(button,true); select.disabled=true; if(nativeHot)nativeHot.disabled=true; if(nativeSave)nativeSave.disabled=true;
M.busy(button,true); select.disabled=true;
var toast=M.toast('正在切换上网卡…',{type:'busy',timeout:0});
return start(target).then(function(r) {
if(!r.ok || !r.id)throw new Error(r.error||'网络设置提交失败');
@@ -175,7 +145,7 @@ return view.extend({
}).then(function() { M.selectViewedSlot(target); M.toast('上网卡切换完成',{type:'success'}); })
.catch(function(e) { if(root.isConnected)M.toast(message(e.message),{type:'error'}); })
.finally(function() { toast.close(); M.busy(button,false); select.disabled=false; if(root.isConnected)return get().then(function(r){if(root.isConnected)paint(r,true);}).catch(function(){}); });
}).finally(function(){self.busy=false; if(nativeHot)nativeHot.disabled=false; if(nativeSave)nativeSave.disabled=false; button.disabled=last.ready===false;});
}).finally(function(){self.busy=false; paint(last,false);});
};
this.refresh=function() {
if(document.hidden||!root.isConnected||self.busy||self.inflight)return Promise.resolve();
@@ -0,0 +1,108 @@
'use strict';
'require view';
'require dom';
'require mu300.common as M';
// Page adapted from dikeckaan/mu300-linux, eab1802f (TTL view).
// Backend, lifecycle, localization and operation handling follow this tree.
var _ = M.translate;
return view.extend({
load: function() { return M.callTtlGet(); },
render: function(state) {
M.injectCss();
this.root = E('div', { 'class': 'mud' });
this.paint(state || {});
return this.root;
},
reload: function() {
var self = this;
return M.callTtlGet().then(function(st) { self.paint(st || {}); return st; });
},
/* run a ttl_set (a number from 1 to 255, or off) and show its result */
set: function(btn, value) {
var self = this;
if (self._pending) return Promise.resolve();
self._pending = true;
var controls = Array.from(self.root.querySelectorAll('button, input')).map(function(el) {
var wasDisabled = el.disabled;
el.disabled = true;
return [el, wasDisabled];
});
M.busy(btn, true);
return M.callTtlSet(String(value)).then(function(r) {
if (!r || r.ok !== 1) {
M.toast(_("操作失败:%s").format(M.translate(r && r.error || '无法应用 TTL 设置')), { type: 'error', timeout: 6000 });
return;
}
return self.reload().then(function(st) {
if (!st || st.ok !== 1) {
M.toast(_('无法读取 TTL 设置'), { type: 'error' });
return;
}
M.toast(_('已保存'), { type: 'success' });
});
}).catch(function() {
M.toast(_('管理连接已断开'), { type: 'error', timeout: 6000 });
}).finally(function() {
self._pending = false;
M.busy(btn, false);
controls.forEach(function(pair) { pair[0].disabled = pair[1]; });
});
},
paint: function(st) {
var self = this, ifs = st.iface || [];
if (st.ok !== 1) {
dom.content(this.root, E('div', { 'class': 'mud-note' }, [ M.translate(st.error || '无法读取 TTL 设置') ]));
return;
}
var rule = st.backend === 'nft' ? 'nftables' : '--';
var rows = [
[ _("当前设置"), st.enabled ? _("固定为 %d").format(st.value) : _("保持不变(默认)") ],
[ _("生效规则"), rule ]
];
if (st.offload === 0 || st.offload === 1)
rows.push([ _("流量卸载"), st.offload ? _("已启用") : _("已禁用") ]);
var card = E('section', { 'class': 'mud-card', 'id': 'mud-ttl' }, [
E('h3', {}, _("蜂窝网络 TTL")),
E('div', { 'class': 'mud-note' },
_("设置蜂窝出口数据包的 TTL 和 IPv6 跳数限制;仅影响蜂窝网络,不改变 Wi-Fi 或 USB 局域网。"))
].concat(rows.map(function(r) {
return E('div', { 'class': 'mud-r' }, [ E('span', { 'class': 'mud-k' }, [ r[0] ]), E('span', { 'class': 'mud-v' }, [ r[1] ]) ]);
})));
card.appendChild(E('div', { 'class': 'mud-note', 'id': 'mud-ttl-nft' },
_("启用后会关闭防火墙流量卸载,可能降低转发性能;关闭 TTL 后恢复由本功能修改的卸载设置。")));
var actions = E('div', { 'style': 'display:flex;gap:8px;flex-wrap:wrap;align-items:center;margin:10px 0' });
[ 64, 65, 128 ].forEach(function(n) {
var b = E('button', { 'class': 'mud-btn', 'id': 'mud-ttl-' + n }, [ _("设为 %d").format(n) ]);
b.addEventListener('click', function() { self.set(b, n); });
actions.appendChild(b);
});
var input = E('input', { 'type': 'number', 'min': '1', 'max': '255', 'step': '1', 'class': 'cbi-input-text',
'id': 'mud-ttl-value', 'style': 'width:6em', 'placeholder': '1-255' });
var custom = E('button', { 'class': 'mud-btn', 'id': 'mud-ttl-custom' }, _("设置"));
custom.addEventListener('click', function() {
var v = String(input.value).trim();
if (!/^[1-9][0-9]{0,2}$/.test(v) || +v > 255) {
M.toast(_("请输入 1 至 255 的整数"), { type: 'error' });
return;
}
self.set(custom, +v);
});
actions.appendChild(input);
actions.appendChild(custom);
var off = E('button', { 'class': 'mud-btn warn', 'id': 'mud-ttl-off', 'disabled': st.enabled ? null : '' }, _("关闭 TTL"));
off.addEventListener('click', function() { self.set(off, 'off'); });
actions.appendChild(off);
card.appendChild(actions);
card.appendChild(E('div', { 'class': 'mud-note' }, _("设置会保留到重启后;默认关闭。")));
dom.content(this.root, card);
}
});
@@ -0,0 +1,3 @@
#!/bin/sh
# Match the logical WAN, never alter another interface's rules.
case "$ACTION:$INTERFACE" in ifup:wan|ifupdate:wan) /usr/libexec/unisoc-modem/ttl-engine apply || logger -t unisoc-ttl 'Failed to apply saved TTL';; esac
@@ -0,0 +1,4 @@
#!/bin/sh /etc/rc.common
START=97
start() { /usr/libexec/unisoc-modem/ttl-engine apply; }
reload() { start; }
@@ -0,0 +1,2 @@
#!/bin/sh
/etc/init.d/unisoc-ttl enable
@@ -7,11 +7,9 @@
# The reply is one JSON line on stdout.
#
# Methods:
# status [refresh] system snapshot (mu300-dash-info, fast, no AT) + the cellular
# cache (mu300-dash-cell) with its age. A stale cache triggers a
# background refresh (setsid) - the call itself NEVER waits for AT:
# LuCI's /admin/ubus endpoint kills a call after 30 s, and an AT
# round inside a page request starves the dial watchdog (V50 lesson).
# status / cells compatibility clients of mu300status; stale cellular caches
# request an asynchronous round from mu300.modem.
# signal a newly completed native round, with a bounded response.
# act op [arg] mu300-dash-act; slow ops run detached via setsid and return
# immediately ("started":1), fast ones run inline.
# at cmd one raw AT command through mu300-at, with the same guards the
@@ -56,13 +54,7 @@ AT=${MU300_AT:-/usr/libexec/unisoc-modem/at}
DIR=${MU300_DASH_DIR:-/tmp/unisoc-modem}
SMS_JOB=$DIR/sms-job
SMS_JOB_T=110
CELL=$DIR/cell.json
SIGF=$DIR/sig.json
COLLECT_LCK=$DIR/collect.lck
FAST_LCK=$DIR/fast.lck
HIST=$DIR/at-history
TTL=${MU300_DASH_TTL:-5} # full tier: neighbours/QoS/operator
TTL_FAST=${MU300_DASH_TTL_FAST:-1} # serving tier: kick whenever older than 1 s (a fast round is ~300 ms)
MU300_AT_LOCK_WAIT=12
export MU300_AT_LOCK_WAIT
@@ -73,79 +65,20 @@ inp() { # inp JSONPATH [default] -> param value
}
esc() { printf '%s' "$1" | sed -e 's/\\/\\\\/g' -e 's/"/\\"/g' | tr -d '\r'; }
now() { date +%s; }
collecting() {
_p=$(cat "$COLLECT_LCK/pid" 2>/dev/null)
[ -n "$_p" ] && [ -d "/proc/$_p" ] &&
tr '\0' ' ' < "/proc/$_p/cmdline" 2>/dev/null | grep -q '/unisoc-modem/cell'
}
fast_busy() {
_p=$(cat "$FAST_LCK/pid" 2>/dev/null)
[ -n "$_p" ] && [ -d "/proc/$_p" ] &&
tr '\0' ' ' < "/proc/$_p/cmdline" 2>/dev/null | grep -q '/unisoc-modem/cell'
}
age_of() { [ -s "$1" ] && echo $(( $(now) - $(date -r "$1" +%s 2>/dev/null || echo 0) )) || echo -1; }
# Compatibility clients use the same native RPC implementations as LuCI.
m_status() {
local info cage sage busy=0 fbusy=0
if [ "${1:-}" = cells ]; then info=null
else info=$("$DASH/dashboard-info" 2>/dev/null); fi
[ -n "$info" ] || info='{"error":"dashboard-info failed"}'
cage=$(age_of "$CELL"); sage=$(age_of "$SIGF")
# two refresh tiers, both detached: the fast one keeps the serving-cell data
# within ~3 s of reality, the full one refreshes neighbours/QoS/operator.
# a full round in flight also writes the fast cache, so it counts for both.
# During a lock apply (SFUN restart) do not kick anything: the modem answers
# garbage mid-restart and the collectors would only burn the AT channel.
if [ -d /run/unisoc-modem-lock-apply ] || [ -d /run/unisoc-data-sim-switch ]; then busy=1; fbusy=1; fi
if collecting; then busy=1; fbusy=1; fi
fast_busy && fbusy=1
# A full round also refreshes sig.json. Prefer it when both tiers are stale;
# starting full and fast together doubles the AT burst for no benefit.
if { [ "$cage" -lt 0 ] || [ "$cage" -ge "$TTL" ]; } && [ "$busy" = 0 ]; then
setsid "$DASH/cell" >/dev/null 2>&1 &
busy=1; fbusy=1
elif { [ "$sage" -lt 0 ] || [ "$sage" -ge "$TTL_FAST" ]; } && [ "$fbusy" = 0 ]; then
setsid "$DASH/cell" fast >/dev/null 2>&1 &
fbusy=1
fi
printf '{"info":%s,"cell":%s,"sig":%s,"cell_age":%d,"sig_age":%d,"refreshing":%d}\n' \
"$info" \
"$([ -s "$CELL" ] && cat "$CELL" || echo null)" \
"$([ -s "$SIGF" ] && cat "$SIGF" || echo null)" \
"$cage" "$sage" "$busy"
local method=status
[ "${1:-}" != cells ] || method=cells
ubus -S -t 20 call mu300status "$method" "{\"slot\":\"${MU300_SIM_SLOT:-0}\"}" || {
printf '{"error":"Unable to read dashboard status"}\n'
return 1
}
}
# Live serving-cell snapshot for views where stale radio readings are actively
# misleading (notably the lock page hero). This intentionally uses an isolated
# temporary directory and returns the just-completed AT round, never cell.json
# or sig.json from an earlier request. The bounded nr6/nr7 pool keeps it off
# nr1 while limiting the number of concurrent modem collectors.
m_signal() {
# During a lock apply the protocol stack is restarting: live AT reads in
# that window return garbage or wedge, and rpcd died with a userspace
# segfault (sessions wiped -> LuCI login loop) on at least one live
# read's output. Serve the last snapshot until the apply finishes.
if [ -d /run/unisoc-modem-lock-apply ] || [ -d /run/unisoc-data-sim-switch ]; then
if [ -s "$SIGF" ]; then
cat "$SIGF"
else
printf '{"error":"正在应用网络锁定,暂无实时信号"}\n'
fi
return
fi
local live="$DIR/live.$$"
mkdir -p "$live" 2>/dev/null
# The output is deliberately uncached, but the modem channel is not
# unbounded parallel work. The collector claims one of the verified
# slot-0 nr6/nr7 channels and drops excess overlap immediately.
MU300_DASH_DIR="$live" MU300_DASH_LOCK_DIR="$DIR" \
"$DASH/cell" fast >/dev/null 2>&1
if [ -s "$live/sig.json" ]; then
cat "$live/sig.json"
else
ubus -S -t 25 call mu300.modem signal "{\"slot\":\"${MU300_SIM_SLOT:-0}\"}" || {
printf '{"error":"live signal read failed"}\n'
fi
rm -rf "$live"
return 1
}
}
m_act() {
@@ -484,6 +417,8 @@ do_list() {
"traffic_get": { "slot": "String" },
"traffic_set": { "payload": "String", "slot": "String" },
"traffic_clear": { "confirm": false, "slot": "String" },
"ttl_get": { },
"ttl_set": { "value": "String" },
"usb_get": { },
"usb_set": { "kind": "String", "value": "String", "scope": "String", "auto": "String" },
"apn_get": { },
@@ -522,6 +457,8 @@ call)
card=$(uci -q get unisoc_modem.main.data_sim); [ "$card" = 1 ] || card=0
printf '{"ok":1,"slots":%s,"saved_sim":%s}\n' "$slots" "$card"
;;
ttl_get) "$DASH/ttl" get ;;
ttl_set) "$DASH/ttl" set "$(inp '@.value')" ;;
apn_get) "$DASH/apn" get ;;
apn_set)
case $(inp '@.action') in
@@ -136,7 +136,7 @@ ims_number() {
# --------------------------------------------------------------- one collector
# the same "one owner, spare waits/takes over" pattern mu300-atd uses, so two
# kicks (page reload while a refresh runs) cannot interleave AT replies
alive() { [ -n "$1" ] && [ -d "/proc/$1" ] && tr '\0' ' ' < "/proc/$1/cmdline" 2>/dev/null | grep -q '/unisoc-modem/cell'; }
alive() { [ -n "$1" ] && [ -d "/proc/$1" ] && tr '\0' ' ' < "/proc/$1/cmdline" 2>/dev/null | grep -qE '/unisoc-modem/cell|mu300-modemd'; }
take_lock() { # take_lock DIRVAR - drop overlap, take over a dead holder
local lock=$1 owner
while ! mkdir "$lock" 2>/dev/null; do
@@ -1,385 +1,3 @@
#!/bin/sh
# mu300-dash-info -- the dashboard's system/network snapshot: ONE line of JSON on stdout.
#
# The LuCI home page (luci-app-mu300) polls this through the rpcd backend
# /usr/libexec/rpcd/mu300dash every few seconds. It reads only files and asks
# ubus/uci/iw, so it never touches the modem's AT channel - the cell readings
# live in mu300-dash-cell, which has its own cache and its own pace.
#
# CPU time and interface byte counters are "since boot" cumulative values; the
# page subtracts two consecutive snapshots to get CPU% and live rates, so the
# poll interval never skews the numbers.
#
# Every external call is wrapped in a hard timeout: netifd mid-reload or a wedged
# driver must not void the whole snapshot (the same lesson the V50 panel learned
# in the field - one hung call used to blank every readout on the page).
#
# Known traps this deliberately works around (docs/FINDINGS.md and the V50
# research archive):
# * loadavg is meaningless here - three vendor kernel threads sit in D state
# and pin it around 3.5 forever. It is not reported at all.
# * iw/iwinfo never report tx-power or a sane channel on the sprd WCN driver;
# SSID/channel come from uci instead.
# * thermal zones are matched by type, never by zone number.
export PATH="$PATH:/opt/mu300/bin:/opt/mu300/busybox-bin:/usr/libexec/unisoc-modem:/usr/sbin:/sbin"
DASH_NET_BIN=${MU300_DASH_BIN:-${0%/*}}
. "$DASH_NET_BIN/dashboard-network.sh"
BB=/opt/mu300/bin/busybox
[ -x "$BB" ] || BB=busybox
t3() { "$BB" timeout -s KILL 3 "$@" 2>/dev/null; } # external asks: netifd, uci, iw...
t2() { "$BB" timeout -s KILL 2 "$@" 2>/dev/null; }
# All callers except the device-tree fallback read one-line proc/sysfs text.
# A shell builtin avoids starting cat for every thermal zone, battery and
# interface counter (dozens of short-lived processes per snapshot).
rd() {
[ -r "$1" ] || return 0
IFS= read -r _rd < "$1" || :
printf '%s\n' "$_rd"
}
n_or_null() { case "$1" in ''|*[!0-9.-]*) echo null ;; *) echo "$1" ;; esac; }
f_or_null() { case "$1" in ''|*[!0-9.-]*) echo null ;; *) echo "$1" ;; esac; }
# JSON string escaping (and drop newlines: the output is one line).
# Avoid a sed+tr process pair for every hostname, address and client field.
CR=$(printf '\r')
NL=$(printf '\nx'); NL=${NL%x}
esc() {
local value=$1 out= ch
while [ -n "$value" ]; do
ch=${value%"${value#?}"}; value=${value#?}
case "$ch" in
"\\") out="$out\\\\" ;;
'"') out="$out\\\"" ;;
"$CR"|"$NL") ;;
*) out=$out$ch ;;
esac
done
printf '%s' "$out"
}
qs() { [ -n "$1" ] && { printf '"'; esc "$1"; printf '"'; } || printf 'null'; }
# ------------------------------------------------------------- temperature
# type -> label, the four zones this SoC actually has; hottest covers the rest
# Read all zone types in one pass instead of rescanning every zone four times.
named_temps() {
local z type temp seen_soc= seen_cpu= seen_nr= seen_brd=
local raw_soc= raw_cpu= raw_nr= raw_brd=
for z in /sys/class/thermal/thermal_zone*; do
[ -r "$z/type" ] || continue
type=; IFS= read -r type < "$z/type" || :
case "$type" in
soc-thmzone) [ -z "$seen_soc" ] || continue; seen_soc=1 ;;
apcpu0-thmzone) [ -z "$seen_cpu" ] || continue; seen_cpu=1 ;;
nr0-thmzone) [ -z "$seen_nr" ] || continue; seen_nr=1 ;;
board-thmzone) [ -z "$seen_brd" ] || continue; seen_brd=1 ;;
*) continue ;;
esac
temp=; [ -r "$z/temp" ] && IFS= read -r temp < "$z/temp" || :
case "$type" in
soc-thmzone) raw_soc=$temp ;;
apcpu0-thmzone) raw_cpu=$temp ;;
nr0-thmzone) raw_nr=$temp ;;
board-thmzone) raw_brd=$temp ;;
esac
done
awk -v soc="$raw_soc" -v cpu="$raw_cpu" -v nr="$raw_nr" -v brd="$raw_brd" '
BEGIN {
printf "%s %s %s %s", soc=="" ? "null" : sprintf("%.1f", soc/1000),
cpu=="" ? "null" : sprintf("%.1f", cpu/1000),
nr=="" ? "null" : sprintf("%.1f", nr/1000),
brd=="" ? "null" : sprintf("%.1f", brd/1000)
}'
}
temp_hottest() {
rd /sys/class/thermal/thermal_zone*/temp 2>/dev/null | sort -n | tail -n1 | awk '{printf "%.1f", $1/1000}'
}
# ------------------------------------------------------- a ubus scalar field
# the ubus CLI pretty-prints with spaces, so sed on the literal key; first match
# wins (the fields used here appear once, ipv4 before ipv6 in the address blocks)
jval() { printf '%s' "$1" | sed -n "s/.*\"$2\": *\"\{0,1\}\([^,\"}\]*\).*/\1/p" | head -n1; }
# ----------------------------------------------------------------- WAN (ubus)
cfg() { uci -q get "unisoc_modem.main.$1" 2>/dev/null || true; }
DATA_IFACE=$(cfg data_interface); DATA_IFACE=${DATA_IFACE:-wan}
DATA_IFACE6=$(cfg data_interface_v6); DATA_IFACE6=${DATA_IFACE6:-wan6}
WANJSON=$(t3 ubus call "network.interface.$DATA_IFACE" status)
WAN6JSON=$(t3 ubus call "network.interface.$DATA_IFACE6" status)
DATA_DEVICE=$(dash_data_device "$WANJSON" "$(cfg data_device)")
LAN_DEVICE=$(cfg lan_device); LAN_DEVICE=${LAN_DEVICE:-br-lan}
WIFI_DEVICE=$(cfg wifi_device); WIFI_DEVICE=${WIFI_DEVICE:-wlan0}
USB_DEVICE=$(cfg usb_device); USB_DEVICE=${USB_DEVICE:-usb0}
jaddr4() { printf '%s' "$1" | sed -n 's/.*"address": *"\([^"]*\)".*/\1/p' | head -n1; }
wan_dns_servers() {
# ubus pretty-prints arrays over multiple lines. Parse only the top-level
# active DNS list, never inactive.dns-server or the loopback resolv.conf.
# Reuse the two status snapshots: no additional RPC, AT request or cache.
local snapshot
for snapshot in "$@"; do
[ -n "$snapshot" ] || continue
jsonfilter -s "$snapshot" -e '@["dns-server"][*]' 2>/dev/null || :
done | awk 'NF && !seen[$0]++ { printf "%s%s", sep, $0; sep=", " }'
}
wan_up=$(dash_json "$WANJSON" '@.up')
[ "$wan_up" = "true" ] && wan_up=1 || wan_up=0
wan_uptime=$(dash_json "$WANJSON" '@.uptime')
wan_proto=$(dash_json "$WANJSON" '@.proto')
wan_ip4=$(jaddr4 "$WANJSON")
wan6_up=$(dash_json "$WAN6JSON" '@.up')
[ "$wan6_up" = "true" ] && wan6_up=1 || wan6_up=0
wan6_ip=$(t2 ip -6 addr show "$DATA_DEVICE" 2>/dev/null | awk '/inet6 [23]/{split($2,s,"/"); print s[1]; exit}')
wan_dns=$(wan_dns_servers "$WANJSON" "$WAN6JSON")
apn=$(dash_apn "$DASH_NET_BIN/apn" "${MU300_SIM_SLOT:-}")
# ------------------------------------------------------------------- system
NOW=$(date +%s)
read -r UPTIME _ < /proc/uptime
UPTIME=${UPTIME%%.*}
HOST=$(t3 uci -q get system.@system[0].hostname)
[ -n "$HOST" ] || HOST=$(rd /proc/sys/kernel/hostname)
MODEL=$(rd /tmp/sysinfo/model 2>/dev/null)
[ -n "$MODEL" ] || MODEL=$(cat /proc/device-tree/model 2>/dev/null | tr -d '\0')
FW=$(sed -n "s/^DISTRIB_DESCRIPTION='\(.*\)'$/\1/p" /etc/openwrt_release 2>/dev/null)
[ -n "$FW" ] || FW=$(uname -sr)
PRIVATE_FW=$(jval "$(rd /etc/unisoc-ota/current.json 2>/dev/null)" version)
[ -n "$PRIVATE_FW" ] || PRIVATE_FW=$(rd /etc/mu300/image-version 2>/dev/null)
[ -z "$PRIVATE_FW" ] || FW="$PRIVATE_FW ($FW)"
# /proc/stat first line: cpu user nice system idle iowait irq softirq steal ...
# busy = everything except idle+iowait; the page deltas this against the last poll
read -r _cpu _u _n _s _i _w _irq _sirq _st _rest < /proc/stat
CPU_TOTAL=$(( _u + _n + _s + _i + _w + _irq + _sirq + _st ))
CPU_IDLE=$(( _i + _w ))
CPUN=$(grep -c '^processor' /proc/cpuinfo)
# one freq pair per policy (big.LITTLE shows two; the page averages or shows both)
FREQS=
for p in /sys/devices/system/cpu/cpufreq/policy*/scaling_cur_freq; do
[ -r "$p" ] || continue
d=${p%/*}
FREQS="$FREQS{\"cur\":$(n_or_null "$(rd "$p")"),\"max\":$(n_or_null "$(rd "$d/cpuinfo_max_freq")")},"
done
FREQS=${FREQS%,}
MEM_T=$(awk '/^MemTotal/{print $2}' /proc/meminfo)
MEM_A=$(awk '/^MemAvailable/{print $2}' /proc/meminfo)
# df on / (the ext4 mu300root loop device)
DF=$(df -k / 2>/dev/null | awk 'NR==2{print $2, $3, $4}')
set -- $DF; DISK_T=$1; DISK_U=$2; DISK_A=$3
set -- $(named_temps)
T_SOC=$1; T_CPU=$2; T_NR=$3; T_BRD=$4
T_HOT=$(temp_hottest)
# ------------------------------------------------------------------- power
# Vendor kernels use battery; mainline UMP9620 uses sc27xx-fgu. The shared
# selector also excludes F50/V50's synthetic FGU, and validates 0..100 percent.
POWER_LIB=${MU300_POWER_LIB:-${0%/*}/power-supply.sh}
[ -r "$POWER_LIB" ] || POWER_LIB=/usr/libexec/unisoc-modem/power-supply.sh
. "$POWER_LIB"
PSY=${MU300_POWER_SUPPLY_DIR:-/sys/class/power_supply}
P_DIR=$(power_battery_dir) || P_DIR=
P_PRESENT=0 P_CAP= P_STATUS= P_V= P_I= P_USB=
if [ -n "$P_DIR" ]; then
P_PRESENT=1
P_CAP=$(rd "$P_DIR/capacity")
P_STATUS=$(rd "$P_DIR/status")
P_V=$(rd "$P_DIR/voltage_now")
P_I=$(rd "$P_DIR/current_now")
fi
# Mainline reports external power on bq256xx-charger, rather than usb/ac.
for d in "$PSY/usb" "$PSY/ac" "$PSY/bq256xx-charger" "$PSY"/*; do
case "${d##*/}" in usb|ac|bq256xx-charger) ;; *) case "$(rd "$d/type")" in USB*|Mains) ;; *) continue ;; esac ;; esac
case "$(rd "$d/online")" in 1) P_USB=1; break ;; 0) P_USB=0 ;; esac
done
P_V=$(n_or_null "$(awk -v v="$P_V" 'BEGIN{if(v+0>0)printf "%.2f",v/1000000}')")
P_I=$(n_or_null "$(awk -v v="$P_I" 'BEGIN{if(v!="")printf "%d",v}')")
# ------------------------------------------------------- interface counters
net_obj() { # net_obj IFACE -> {"rx":N,"tx":N,"up":0|1} or null
case "$1" in ''|*[!a-zA-Z0-9_.:-]*|.|..) echo null; return ;; esac
local d=/sys/class/net/$1
[ -d "$d" ] || { echo null; return; }
local rx tx up
rx=$(rd "$d/statistics/rx_bytes"); tx=$(rd "$d/statistics/tx_bytes")
case "$(rd "$d/operstate")" in up) up=1 ;; *) up=0 ;; esac
printf '{"rx":%s,"tx":%s,"up":%d}' "$(n_or_null "$rx")" "$(n_or_null "$tx")" "$up"
}
# ------------------------------------------------------------------- Wi-Fi
# configuration truth is uci (the driver reports nothing useful); per-client detail
# comes from the driver's station table, names and addresses from the DHCP leases.
# One ucode process selects the same AP as the switch and reads its radio.
# Key/value lines preserve quotes without evaluating untrusted SSID text.
W_SSID= W_CH= W_BAND= W_HT= W_COUNTRY= W_ENC= W_HIDDEN=
W_AVAILABLE=0 W_ENABLED=0 W_PENDING=0 W_ERROR= W_SECTION= W_RADIO= W_UP=0
WFIELDS=$(t3 "${MU300_DASH_BIN:-/usr/libexec/unisoc-modem}/hotspot" fields)
while IFS= read -r key && IFS= read -r val; do
case "$key" in
available) W_AVAILABLE=$val ;; enabled) W_ENABLED=$val ;;
pending) W_PENDING=$val ;; up) W_UP=$val ;; error) W_ERROR=$val ;;
section) W_SECTION=$val ;; radio) W_RADIO=$val ;;
device) WIFI_DEVICE=$val ;; ssid) W_SSID=$val ;;
channel) W_CH=$val ;; band) W_BAND=$val ;; htmode) W_HT=$val ;;
country) W_COUNTRY=$val ;; enc) W_ENC=$val ;; hidden) W_HIDDEN=$val ;;
esac
done <<EOF_WIFI
$WFIELDS
EOF_WIFI
# HE80 / VHT40 / HT20: retain the first two digits, as before.
W_WIDTH=; digits=$W_HT
while [ -n "$digits" ] && [ "${#W_WIDTH}" -lt 2 ]; do
ch=${digits%"${digits#?}"}; digits=${digits#?}
case "$ch" in [0-9]) W_WIDTH=$W_WIDTH$ch ;; esac
done
[ -n "$W_WIDTH" ] && W_WIDTH="$W_WIDTH MHz"
[ -n "$W_ENC" ] || W_ENC=none
W_HOSTAPD=0
HAPD=
[ -n "$WIFI_DEVICE" ] && [ "$W_AVAILABLE" = 1 ] && HAPD=$(t3 ubus call "hostapd.$WIFI_DEVICE" get_status 2>/dev/null)
printf '%s' "$HAPD" | grep -q '"status": *"ENABLED"' && W_HOSTAPD=1
[ -d "/sys/class/net/$WIFI_DEVICE" ] || W_UP=0
[ "$W_HOSTAPD" = 1 ] || W_UP=0
# SC2355 may report only associated MACs, with no station metrics. Count the
# association regardless of RSSI and emit after the COMPLETE block, not at
# the signal line. Whitespace splitting leaves the colons inside a MAC intact.
station_rows() {
awk '
function emit( a, n, i) {
n = split(mac, a, ":")
if (n != 6) return
for (i = 1; i <= n; i++)
if (a[i] !~ /^[[:xdigit:]][[:xdigit:]]$/) return
if (seen[mac]++) return
printf "%s|%s|%s|%s|%s\n", mac, sig, tx, rx, ct
}
/^Station[ \t]+/ { emit(); mac = tolower($2); sig = tx = rx = ct = ""; next }
/^[ \t]+signal:/ && $2 ~ /^-?[0-9]+([.][0-9]+)?$/ { sig = $2 + 0 }
/^[ \t]+tx bitrate:/ && $3 ~ /^[0-9]+([.][0-9]+)?$/ { tx = $3 " Mbit/s" }
/^[ \t]+rx bitrate:/ && $3 ~ /^[0-9]+([.][0-9]+)?$/ { rx = $3 " Mbit/s" }
/^[ \t]+connected time:/ && $3 ~ /^[0-9]+$/ { ct = sprintf("%d min", int($3 / 60)) }
END { emit() }'
}
W_CN=null; W_CLIST=; W_CLIENTS=
if W_STATIONS=$(t3 iw dev "$WIFI_DEVICE" station dump 2>/dev/null); then
W_CLIENTS=$(printf '%s\n' "$W_STATIONS" | station_rows)
W_CN=0
elif [ ! -d "/sys/class/net/$WIFI_DEVICE" ]; then
W_CN=0
fi
# Empty successful dumps also need hostapd on older SC2355 modules.
if [ -z "$W_CLIENTS" ] && [ -d "/sys/class/net/$WIFI_DEVICE" ] &&
[ -x /usr/libexec/unisoc-modem/wifi-hostapd-clients ]; then
if W_ASSOC=$(t3 ubus call "hostapd.$WIFI_DEVICE" get_clients 2>/dev/null); then
if W_FALLBACK=$(printf '%s' "$W_ASSOC" | /usr/libexec/unisoc-modem/wifi-hostapd-clients); then
W_CLIENTS=$W_FALLBACK
W_CN=0
fi
fi
fi
while IFS='|' read -r mac sig txr rxr ct; do
[ -n "$mac" ] || continue
line=$(awk -v m="$mac" 'tolower($2) == m { print $3 "|" $4; exit }' /tmp/dhcp.leases 2>/dev/null)
ip=${line%%|*}; host=${line#*|}
{ [ "$host" = "$line" ] || [ "$host" = '*' ]; } && host=
W_CLIST="$W_CLIST{\"mac\":\"$mac\",\"host\":$(qs "$host"),\"ip\":$(qs "$ip"),\"signal\":$(n_or_null "$sig"),\"tx\":$(qs "$txr"),\"rx\":$(qs "$rxr"),\"conn\":$(qs "$ct")},"
W_CN=$((W_CN + 1))
done <<EOF2
$(printf '%s\n' "$W_CLIENTS")
EOF2
W_CLIST=${W_CLIST%,}
LAN_LEASES=$(cat /tmp/dhcp.leases 2>/dev/null | wc -l)
# recent DHCP leases (host/ip/mac + remaining time) - shows devices that were
# here even when nobody is associated right now
NOWS=$NOW
LEASES=
while read -r exp mac ip host _cid; do
[ -n "$mac" ] || continue
[ "$host" = "*" ] && host=
left=$(( exp - NOWS ))
[ "$left" -lt 0 ] && left=0
LEASES="$LEASES{\"host\":$(qs "$host"),\"ip\":$(qs "$ip"),\"mac\":$(qs "$mac"),\"left\":$left},"
done < /tmp/dhcp.leases 2>/dev/null
LEASES=${LEASES%,}
LAN_IP=$(t2 ip -4 addr show "$LAN_DEVICE" 2>/dev/null | awk '/inet /{split($2,a,"/"); print a[1]; exit}')
# ---------------------------------------------------------------- modem/path
# the same liveness rule mu300-atd uses: the URC log on nr0 is written to as
# long as the modem is running, whatever it thinks of our commands
URCLOG=/run/mu300-at/urc/stty_nr0.log
if [ -f "$URCLOG" ]; then
AGE=$(( NOW - $(date -r "$URCLOG" +%s 2>/dev/null || echo 0) ))
[ "$AGE" -lt 240 ] && MODEM_ALIVE=1 || MODEM_ALIVE=0
else
MODEM_ALIVE=0
fi
ATD_OK=0; /usr/libexec/unisoc-modem/at --available >/dev/null 2>&1 && ATD_OK=1
[ "$MODEM_ALIVE" = 1 ] || MODEM_ALIVE=$ATD_OK
DATA_PAUSED=0; [ -e /run/mu300-mobile-data-down ] && DATA_PAUSED=1
# Constant-size counter works without CONFIG_NF_CONNTRACK_PROCFS. Only older
# platforms lacking this counter need the connection-table fallback.
# Missing/failed reads are unknown (null), never a made-up zero.
conntrack_count() {
local counter=${1:-/proc/sys/net/netfilter/nf_conntrack_count}
local table=${2:-/proc/net/nf_conntrack} count=
# sysctl proc handlers may return EOF after the first small read; ash's
# byte-at-a-time read can truncate this value. Read it in one cat buffer.
if [ -r "$counter" ] && count=$(cat "$counter" 2>/dev/null); then
case "$count" in ''|*[!0-9]*) ;; *) printf '%s\n' "$count"; return ;; esac
fi
if [ -r "$table" ] && count=$(wc -l < "$table" 2>/dev/null); then
count=$((count + 0))
printf '%s\n' "$count"
return
fi
printf 'null\n'
}
CONNS=$(conntrack_count)
# --------------------------------------------------------------------- VPN
VPN_ENABLED=0; VPN_ENGINE=""; VPN_UP=0
if [ -r /etc/mu300/vpn.conf ]; then
grep -q '^ENABLE=1' /etc/mu300/vpn.conf && VPN_ENABLED=1
VPN_ENGINE=$(sed -n 's/^ENGINE=//p' /etc/mu300/vpn.conf | tail -n1)
fi
if ip link show xtun >/dev/null 2>&1 || ip link show sbtun >/dev/null 2>&1; then VPN_UP=1; fi
CAP_VPN=0; [ -x /etc/init.d/mu300-vpn ] && CAP_VPN=1
CAP_DUALBOOT=0; [ -x /opt/mu300/bin/mu300-next-boot ] && CAP_DUALBOOT=1
# ------------------------------------------------------------------ output
printf '{"ts":%d,"uptime":%d,"host":%s,"model":%s,"fw":%s,"kernel":%s,' \
"$NOW" "$UPTIME" "$(qs "$HOST")" "$(qs "$MODEL")" "$(qs "$FW")" "$(qs "$(uname -r)")"
printf '"cpu":{"n":%d,"total":%d,"idle":%d,"freqs":[%s]},' "$CPUN" "$CPU_TOTAL" "$CPU_IDLE" "${FREQS:-}"
printf '"mem":{"total_kb":%s,"avail_kb":%s},' "$(n_or_null "$MEM_T")" "$(n_or_null "$MEM_A")"
printf '"storage":{"total_kb":%s,"used_kb":%s,"avail_kb":%s},' "$(n_or_null "$DISK_T")" "$(n_or_null "$DISK_U")" "$(n_or_null "$DISK_A")"
printf '"temps":{"soc":%s,"cpu":%s,"modem":%s,"board":%s,"hottest":%s},' \
"$(f_or_null "$T_SOC")" "$(f_or_null "$T_CPU")" "$(f_or_null "$T_NR")" "$(f_or_null "$T_BRD")" "$(f_or_null "$T_HOT")"
printf '"power":{"present":%d,"capacity":%s,"status":%s,"volt":%s,"ua":%s,"usb":%s},' \
"$P_PRESENT" "$(n_or_null "$P_CAP")" "$(qs "$P_STATUS")" "$P_V" "$P_I" "$(n_or_null "$P_USB")"
MOBILE_NET=$(net_obj "$DATA_DEVICE")
printf '"net":{"mobile":%s,"sipa_eth0":%s,"brlan":%s,"wlan0":%s,"usb0":%s},' \
"$MOBILE_NET" "$MOBILE_NET" "$(net_obj "$LAN_DEVICE")" "$(net_obj "$WIFI_DEVICE")" "$(net_obj "$USB_DEVICE")"
printf '"wan":{"up":%d,"uptime":%s,"proto":%s,"device":%s,"apn":%s,"ip4":%s,"ip6":%s,"dns":%s},' \
"$wan_up" "$(n_or_null "$wan_uptime")" "$(qs "$wan_proto")" "$(qs "$DATA_DEVICE")" "$(qs "$apn")" "$(qs "$wan_ip4")" "$(qs "$wan6_ip")" "$(qs "$wan_dns")"
printf '"wifi":{"available":%d,"enabled":%d,"pending":%d,"section":%s,"radio":%s,"error":%s,"up":%d,"ssid":%s,"channel":%s,"band":%s,"width":%s,"country":%s,"enc":%s,"hidden":%s,"hostapd":%d,"clients":[%s],"clients_n":%s},' \
"$W_AVAILABLE" "$W_ENABLED" "$W_PENDING" "$(qs "$W_SECTION")" "$(qs "$W_RADIO")" "$(qs "$W_ERROR")" "$W_UP" "$(qs "$W_SSID")" "$(qs "$W_CH")" "$(qs "$W_BAND")" "$(qs "$W_WIDTH")" "$(qs "$W_COUNTRY")" "$(qs "$W_ENC")" "$(n_or_null "$W_HIDDEN")" "$W_HOSTAPD" "${W_CLIST:-}" "$W_CN"
printf '"lan":{"leases":%s,"ip":%s,"list":[%s]},' "$(n_or_null "$LAN_LEASES")" "$(qs "$LAN_IP")" "${LEASES:-}"
printf '"modem":{"alive":%d,"atd":%d,"data_paused":%d},' "$MODEM_ALIVE" "$ATD_OK" "$DATA_PAUSED"
# Source a builtin-only boot snapshot; this never changes startup intent.
BOOT_STATUS_LIBRARY=1
. "${MU300_DASH_BIN:-/usr/libexec/unisoc-modem}/boot-status"
printf '"boot":'; boot_status; printf ','
printf '"capabilities":{"vpn":%d,"dualboot":%d},' "$CAP_VPN" "$CAP_DUALBOOT"
printf '"conns":%s,' "$(n_or_null "$CONNS")"
# The accounting worker publishes one atomic JSON line; no extra RPC or AT
# requests on the dashboard's fast refresh path.
TRAFFIC=null
if [ -r /run/unisoc-modem-traffic/view.json ]; then
IFS= read -r TRAFFIC < /run/unisoc-modem-traffic/view.json || TRAFFIC=null
fi
printf '"traffic":%s,' "${TRAFFIC:-null}"
printf '"vpn":{"enabled":%d,"engine":%s,"up":%d}}\n' "$VPN_ENABLED" "$(qs "$VPN_ENGINE")" "$VPN_UP"
#!/usr/bin/ucode
import { info } from 'mu300.dash';
print(sprintf('%J\n', info(getenv('MU300_SIM_SLOT'))));
@@ -1,38 +1,4 @@
#!/usr/bin/ucode
// No AT, interface dump, process list or traffic-ledger query on the 1 s lane.
import { readfile } from 'fs';
import { cursor } from 'uci';
import { connect } from 'ubus';
const cfg = cursor();
const iface = cfg.get('unisoc_modem', 'main', 'data_interface') || 'wan';
let status;
if (match(iface, /^[A-Za-z0-9_]{1,32}$/)) {
// Same live interface priority as the full snapshot. Bound an unavailable
// netifd without adding AT, retries, or another refresh timer.
try {
const bus = connect(null, 1);
status = bus?.call('network.interface.' + iface, 'status', {});
} catch (e) {}
}
const device = status?.l3_device || status?.device ||
cfg.get('unisoc_modem', 'main', 'data_device') || 'sipa_eth0';
if (!match(device, /^[A-Za-z0-9_.:-]{1,15}$/)) {
print('{"available":false}\n');
exit(0);
}
const path = '/sys/class/net/' + device + '/';
const rx = readfile(path + 'statistics/rx_bytes');
const tx = readfile(path + 'statistics/tx_bytes');
const index = readfile(path + 'ifindex');
const uptime = readfile('/proc/uptime');
const valid = rx != null && tx != null && index != null && uptime != null;
printf('%J\n', {
available: valid,
device: device,
ifindex: valid ? int(index) : null,
boot_id: trim(readfile('/proc/sys/kernel/random/boot_id') || ''),
ts: valid ? +split(uptime, ' ')[0] : null,
rx: valid ? +trim(rx) : null,
tx: valid ? +trim(tx) : null
});
// Compatibility entry point; native rpcd uses the same sampler.
import { sample } from 'mu300.rates';
printf('%J\n', sample());
@@ -20,13 +20,10 @@ validate_apply() {
[ "$(uci -q get unisoc_modem.main.sim_slots)" = 2 ] || { echo dual_sim_unavailable >&2; return 1; };;
esac
return 0;;
u30-hot-[01]|u30-default-[01])
[ "$(mu300-device 2>/dev/null)" = u30air ] || { echo dual_sim_unavailable >&2; return 1; } ;;
*) echo invalid_sim >&2; return 1 ;;
esac
[ "$(uci -q get unisoc_modem.main.sim_slots)" = 2 ] && [ -x "$adapter" ] || { echo dual_sim_unavailable >&2; return 1; }
}
[ "$(mu300-device 2>/dev/null)" != u30air ] || MU300_JOB_TIMEOUT=360
. "$LIB/lock-jobs.sh"
case ${1:-} in
get) [ -x "$adapter" ] && "$adapter" get || printf '{"ok":0,"error":"dual_sim_unavailable"}\n' ;;
@@ -0,0 +1,49 @@
#!/bin/sh
# Panel adapter for the shared explicit nftables engine; replies are JSON.
# ttl get {"ok":1,"enabled":0|1,"value":N|null,"backend":"nft"|"none","offload":0|1|null,"iface":[...]}
# ttl set N|off {"ok":1}, or {"ok":0,"error":...}; N from 1 to 255, checked here again
set -u
export PATH="$PATH:/opt/mu300/bin:/usr/sbin:/sbin"
json_str() { ucode -e 'import * as fs from "fs"; print(sprintf("%J", fs.readfile("/dev/stdin")));'; }
TTL_CMD=${MU300_TTL_CMD:-/usr/libexec/unisoc-modem/ttl-engine}
error() { printf '{"ok":0,"error":%s}\n' "$(printf '%s' "$1" | json_str)"; exit 0; }
num() { case $1 in ''|*[!0-9]*) return 1 ;; esac; }
do_get() {
st=$("$TTL_CMD" state 2>/dev/null) || error '无法读取 TTL 设置'
v=$(printf '%s\n' "$st" | sed -n 's/^TTL=//p' | head -n1)
b=$(printf '%s\n' "$st" | sed -n 's/^BACKEND=//p' | head -n1)
o=$(printf '%s\n' "$st" | sed -n 's/^OFFLOAD=//p' | head -n1)
ifs=$(printf '%s\n' "$st" | sed -n 's/^IFACES=//p' | head -n1)
case $b in nft) ;; *) b=none ;; esac
if num "$v" && [ "$v" -ge 1 ] && [ "$v" -le 255 ]; then en=1; else en=0; v=null; fi
case $o in 0|1) ;; *) o=null ;; esac
list= sep=
for i in $ifs; do
case $i in sipa_eth[0-9]|sipa_eth[0-9][0-9]) list="$list$sep\"$i\""; sep=, ;; esac
done
printf '{"ok":1,"enabled":%s,"value":%s,"backend":"%s","offload":%s,"iface":[%s]}\n' "$en" "$v" "$b" "$o" "$list"
}
do_set() {
case ${1:-} in
off) set -- off ;;
0*) error 'TTL 无效' ;;
*) { num "${1:-}" && [ "${#1}" -le 3 ] && [ "$1" -ge 1 ] && [ "$1" -le 255 ]; } || error 'TTL 无效'
set -- set "$1" ;;
esac
if out=$("$TTL_CMD" "$@" 2>&1 >/dev/null); then
echo '{"ok":1}'
else
code=$?
[ "$code" != 75 ] || error '另一项 TTL 操作正在执行,请稍后重试'
printf '{"ok":0,"error":"无法应用 TTL 设置","detail":%s}\n' "$(printf '%s\n' "$out" | tail -n1 | json_str)"
fi
}
case ${1:-} in
get) do_get ;;
set) do_set "${2:-}" ;;
*) error 'Unknown TTL operation' ;;
esac
@@ -0,0 +1,78 @@
#!/bin/sh
# Explicit nftables backend. One transaction replaces only our cellular table.
# fw4 offloading bypasses postrouting, so it must be off while TTL rewriting is on.
set -eu
CONF=${MU300_TTL_CONF:-/etc/mu300/ttl.conf}
LOCK=${MU300_TTL_LOCK:-/var/lock/unisoc-ttl.lock}
MARK=${CONF%/*}/ttl.offload-off
TABLE='inet mu300_ttl'
saved() { sed -n 's/^TTL=\([0-9]*\)$/\1/p' "$CONF" 2>/dev/null | tail -n1; }
valid() { case ${1:-} in ''|0*|*[!0-9]*) return 1;; esac; [ ${#1} -le 3 ] && [ "$1" -le 255 ]; }
offload_restore() {
[ -f "$MARK" ] || return 0
while IFS= read -r key; do
case "$key" in flow_offloading|flow_offloading_hw) ;; *) return 1;; esac
uci set "firewall.@defaults[0].$key=1" || return 1
done < "$MARK"
uci commit firewall || return 1
fw4 -q reload || return 1
rm -f "$MARK"
}
offload_disable() {
changed=0
for key in flow_offloading flow_offloading_hw; do
v=$(uci -q get "firewall.@defaults[0].$key" || true)
case "$v" in 1)
# Record ownership before changing a persistent firewall setting.
grep -qx "$key" "$MARK" 2>/dev/null || { printf '%s\n' "$key" >> "$MARK" || return 1; }
uci set "firewall.@defaults[0].$key=0" || return 1
changed=1;;
''|0) ;; *) echo 'Invalid firewall offloading setting' >&2; return 1;; esac
done
if [ "$changed" = 1 ] || [ -f "$MARK" ]; then uci commit firewall && fw4 -q reload; fi
}
clear_rule() {
if nft list table $TABLE >/dev/null 2>&1; then nft delete table $TABLE || return 1; fi
}
apply_value() {
value=$1
if [ -z "$value" ]; then clear_rule || return 1; offload_restore; return; fi
valid "$value" || { echo 'Invalid saved TTL' >&2; return 2; }
offload_disable || { echo 'Cannot disable firewall offloading; TTL was not applied' >&2; return 1; }
# add + delete + create in one batch also handles the first application.
nft -f - <<EOF
add table $TABLE
delete table $TABLE
table $TABLE {
chain postrouting {
type filter hook postrouting priority mangle; policy accept;
oifname "sipa_eth*" ip ttl set $value counter
oifname "sipa_eth*" ip6 hoplimit set $value counter
}
}
EOF
}
state() {
v=$(saved)
if nft list table $TABLE >/dev/null 2>&1; then backend=nft; else backend=none; fi
offload=$(uci -q get 'firewall.@defaults[0].flow_offloading' || true)
printf 'TTL=%s\nBACKEND=%s\nIFACES=\nOFFLOAD=%s\n' "$v" "$backend" "$offload"
}
case ${1:-state} in
state|status) state; exit;;
set) valid "${2:-}" || { echo 'TTL must be an integer from 1 to 255' >&2; exit 2; };;
off|apply) ;;
*) echo 'Usage: ttl-engine [state|status|set N|off|apply]' >&2; exit 2;;
esac
mkdir -p "${CONF%/*}" "${LOCK%/*}"
exec 9>"$LOCK"
flock -n -x 9 || { echo 'TTL operation is busy; retry shortly' >&2; exit 75; }
old=$(saved)
case $1 in
set)
apply_value "$2" || exit $?
printf 'TTL=%s\n' "$2" > "$CONF.tmp"
mv "$CONF.tmp" "$CONF";;
off) apply_value ''; rm -f "$CONF";;
apply) apply_value "$old";;
esac
@@ -0,0 +1,23 @@
MIT License
Copyright (c) 2026 dikeckaan
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
Note: kernel/patches/*.patch modify GPL-2.0 kernel code and are licensed GPL-2.0.
@@ -1,109 +1,170 @@
{
"admin/home": {
"title": "状态看板",
"order": 5,
"action": {
"type": "view",
"path": "mu300/home"
},
"depends": {
"acl": [ "luci-app-mu300" ]
}
},
"admin/modem": {
"title": "蜂窝",
"order": 25,
"action": {
"type": "firstchild"
},
"depends": {
"acl": [ "luci-app-mu300" ]
}
},
"admin/modem/apn": {
"title": "接入点 APN",
"order": 10,
"action": { "type": "view", "path": "mu300/apn" },
"depends": { "acl": [ "luci-app-mu300" ] }
},
"admin/modem/locks": {
"title": "网络锁定",
"order": 1,
"action": {
"type": "view",
"path": "mu300/locks"
},
"depends": {
"acl": [ "luci-app-mu300" ]
}
},
"admin/modem/sms": {
"title": "短信",
"order": 2,
"action": {
"type": "view",
"path": "mu300/sms"
},
"depends": {
"acl": [ "luci-app-mu300" ]
}
},
"admin/modem/forward": {
"title": "短信转发",
"order": 3,
"action": { "type": "view", "path": "mu300/forward" },
"depends": { "acl": [ "luci-app-mu300" ] }
},
"admin/modem/at": {
"title": "AT 终端",
"order": 4,
"action": {
"type": "view",
"path": "mu300/at"
},
"depends": {
"acl": [ "luci-app-mu300" ]
}
},
"admin/modem/settings": {
"title": "适配设置",
"order": 7,
"action": {
"type": "view",
"path": "mu300/settings"
},
"depends": {
"acl": [ "luci-app-mu300" ]
}
},
"admin/modem/device": {
"title": "设备管理",
"order": 6,
"action": { "type": "view", "path": "mu300/device" },
"depends": { "acl": [ "luci-app-mu300" ] }
},
"admin/modem/sim": {
"title": "SIM 卡管理",
"order": 9,
"action": { "type": "view", "path": "mu300/sim" },
"depends": { "acl": [ "luci-app-mu300" ] }
},
"admin/modem/cpu": {
"title": "CPU 设置",
"order": 8,
"action": { "type": "view", "path": "mu300/cpu" },
"depends": { "acl": [ "luci-app-mu300" ] }
},
"admin/modem/traffic": {
"title": "流量池",
"order": 5,
"action": { "type": "view", "path": "mu300/traffic" },
"depends": { "acl": [ "luci-app-mu300" ] }
}
"admin/home": {
"title": "状态看板",
"order": 5,
"action": {
"type": "view",
"path": "mu300/home"
},
"depends": {
"acl": [
"luci-app-mu300"
]
}
},
"admin/modem": {
"title": "蜂窝",
"order": 25,
"action": {
"type": "firstchild"
},
"depends": {
"acl": [
"luci-app-mu300"
]
}
},
"admin/modem/apn": {
"title": "接入点 APN",
"order": 10,
"action": {
"type": "view",
"path": "mu300/apn"
},
"depends": {
"acl": [
"luci-app-mu300"
]
}
},
"admin/modem/locks": {
"title": "网络锁定",
"order": 1,
"action": {
"type": "view",
"path": "mu300/locks"
},
"depends": {
"acl": [
"luci-app-mu300"
]
}
},
"admin/modem/sms": {
"title": "短信",
"order": 2,
"action": {
"type": "view",
"path": "mu300/sms"
},
"depends": {
"acl": [
"luci-app-mu300"
]
}
},
"admin/modem/forward": {
"title": "短信转发",
"order": 3,
"action": {
"type": "view",
"path": "mu300/forward"
},
"depends": {
"acl": [
"luci-app-mu300"
]
}
},
"admin/modem/at": {
"title": "AT 终端",
"order": 4,
"action": {
"type": "view",
"path": "mu300/at"
},
"depends": {
"acl": [
"luci-app-mu300"
]
}
},
"admin/modem/settings": {
"title": "适配设置",
"order": 7,
"action": {
"type": "view",
"path": "mu300/settings"
},
"depends": {
"acl": [
"luci-app-mu300"
]
}
},
"admin/modem/device": {
"title": "设备管理",
"order": 6,
"action": {
"type": "view",
"path": "mu300/device"
},
"depends": {
"acl": [
"luci-app-mu300"
]
}
},
"admin/modem/sim": {
"title": "SIM 卡管理",
"order": 9,
"action": {
"type": "view",
"path": "mu300/sim"
},
"depends": {
"acl": [
"luci-app-mu300"
]
}
},
"admin/modem/cpu": {
"title": "CPU 设置",
"order": 8,
"action": {
"type": "view",
"path": "mu300/cpu"
},
"depends": {
"acl": [
"luci-app-mu300"
]
}
},
"admin/modem/traffic": {
"title": "流量池",
"order": 5,
"action": {
"type": "view",
"path": "mu300/traffic"
},
"depends": {
"acl": [
"luci-app-mu300"
]
}
},
"admin/modem/ttl": {
"title": "TTL",
"order": 8,
"action": {
"type": "view",
"path": "mu300/ttl"
},
"depends": {
"acl": [
"luci-app-mu300"
]
}
}
}
@@ -1,28 +1,77 @@
{
"luci-app-mu300": {
"description": "MU300 控制中心:状态看板、网络锁定、AT 终端与短信",
"read": {
"ubus": {
"mu300dash": [
"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", "sim_radio_get", "sim_radio_status", "v50_sim_get"
],
"mu300-charge": [ "get" ]
},
"uci": {
"unisoc_modem": [ "*" ]
}
},
"write": {
"ubus": {
"uci": [ "commit" ],
"mu300dash": [ "*" ],
"mu300-charge": [ "configure", "full_once", "pause", "resume" ]
},
"uci": {
"unisoc_modem": [ "*" ]
}
"luci-app-mu300": {
"description": "MU300 控制中心:状态看板、网络锁定、AT 终端与短信",
"read": {
"ubus": {
"mu300rates": [
"rates"
],
"mu300dash": [
"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",
"sim_radio_get",
"sim_radio_status",
"v50_sim_get",
"ttl_get"
],
"mu300-charge": [
"get"
],
"mu300status": [
"status",
"cells",
"sysinfo",
"sms_head"
],
"mu300.modem": [
"signal"
]
},
"uci": {
"unisoc_modem": [
"*"
]
}
},
"write": {
"ubus": {
"uci": [
"commit"
],
"mu300dash": [
"*"
],
"mu300-charge": [
"configure",
"full_once",
"pause",
"resume"
]
},
"uci": {
"unisoc_modem": [
"*"
]
}
}
}
}
}
@@ -0,0 +1,4 @@
// No subprocess, AT access, arbitrary path, or caller-selected interface.
'use strict';
import { sample } from 'mu300.rates';
return { mu300rates: { rates: { call: function() { return sample(); } } } };
@@ -0,0 +1,7 @@
import * as dash from 'mu300.dash';
return {mu300status:{
status:{args:{slot:''},call:(req)=>dash.status(req.args.slot,false)},
cells:{args:{slot:''},call:(req)=>dash.status(req.args.slot,true)},
sysinfo:{call:()=>dash.info(null)},
sms_head:{args:{slot:''},call:(req)=>dash.sms_head(req.args.slot)}
}};
@@ -0,0 +1,247 @@
// Native dashboard snapshot. Shared by rpcd and the compatibility CLI.
// No AT access, shell commands, configuration writes or private credentials.
import * as fs from 'fs';
import * as nl from 'nl80211';
import * as rt from 'rtnl';
import { statvfs } from 'luci.core';
import { cursor } from 'uci';
import { connect } from 'ubus';
import * as hotspot from '/usr/libexec/unisoc-modem/hotspot.uc';
import * as apn from '/usr/libexec/unisoc-modem/apn.uc';
const ROOT = getenv('MU300_DASH_SYSROOT') || '';
const CONFIG = getenv('MU300_DASH_CONFIG') || '/etc/config';
function rd(path) { return trim(fs.readfile(ROOT + path) || ''); }
function obj(path) { try { return json(rd(path)); } catch(e) { return null; } }
function num(v) { return v != null && match(''+v, /^-?[0-9]+(\.[0-9]+)?$/) ? +v : null; }
function text(v) { return v == null || v === '' ? null : replace(''+v,/[\r\n]/g,''); }
function device(v) { return type(v)=='string' && v!='.' && v!='..' && match(v,/^[A-Za-z0-9_.:-]{1,15}$/) ? v : null; }
function exists(p) { return fs.stat(ROOT+p)!=null; }
function executable(p) { return fs.access(ROOT+p,'x')==true; }
function call(bus,o,m) { return bus?.call(o,m,{}) || {}; }
function net(dev) {
dev=device(dev);
if(!dev || !exists('/sys/class/net/'+dev))return null;
let p='/sys/class/net/'+dev+'/';
return {rx:num(rd(p+'statistics/rx_bytes')),tx:num(rd(p+'statistics/tx_bytes')),up:rd(p+'operstate')=='up'?1:0};
};
function address(rows,dev,global6) {
for(let a in rows || []) if(a.dev==dev && a.address) {
let s=replace(a.address,/\/.*/,'');
if(!global6 || match(s,/^[23]/))return s;
}
return null;
};
function board() {
// Match mu300-device: live DT outranks a restored rootfs/runtime label.
if(exists('/proc/device-tree/charger_policy_service'))return 'u30air';
if(exists('/proc/device-tree/soc/soc:ap-ahb/i2c@2270000/aw9523b_led@5b') ||
exists('/proc/device-tree/soc/ap-ahb/i2c@2270000/aw9523b_led@5b'))return 'v50';
if(exists('/proc/device-tree'))return 'f50';
return rd('/run/mu300/device');
};
export function power() {
const base='/sys/class/power_supply';
let model=board(), battery=null, usb=null;
let names=['battery','sc27xx-fgu',...(fs.lsdir(ROOT+base) || [])], seen={};
for(let name in names) {
if(seen[name])continue; seen[name]=true;
let p=base+'/'+name, kind=rd(p+'/type');
if(model!='f50' && model!='v50' && !battery &&
(name=='battery' || name=='sc27xx-fgu' || kind=='Battery') &&
rd(p+'/present')!='0') {
let raw=rd(p+'/capacity'), cap=match(raw,/^[0-9]+$/)?+raw:null;
if(cap!=null && cap>=0 && cap<=100)battery=p;
}
if(name in ['usb','ac','bq256xx-charger'] || match(kind,/^(USB|Mains)/)) {
let on=num(rd(p+'/online'));
if(on==1)usb=1; else if(on==0 && usb==null)usb=0;
}
}
let volts=battery?num(rd(battery+'/voltage_now')):null;
return {present:battery?1:0,capacity:battery?num(rd(battery+'/capacity')):null,
status:battery?text(rd(battery+'/status')):null,
volt:volts!=null && volts>0?+sprintf('%.2f',volts/1000000.0):null,
ua:battery?num(rd(battery+'/current_now')):null,usb};
};
export function boot() {
let state=rd('/etc/mu300/default-boot') || 'android';
if(!(state in ['android','linux']))state='unknown';
let slot=rd('/run/mu300/linux-slot') || 'b', writable=false;
if(executable('/opt/mu300/bin/mu300-next-boot') && slot in ['a','b']) {
writable=fs.stat(ROOT+'/run/mu300/misc-bc-linux-trial.bin')?.size>0 &&
fs.stat(ROOT+'/run/mu300/misc-bc-android.bin')?.size>0;
if(slot=='b')writable = writable || fs.stat(ROOT+'/run/mu300/misc-bc-slot-b-trial.bin')?.size>0 &&
fs.stat(ROOT+'/run/mu300/misc-bc-slot-a.bin')?.size>0;
}
return {default:state,temporary:state=='unknown'?null:state!='linux',can_set_default:!!writable};
};
function clients(dev,bus,leases) {
if(!device(dev) || !exists('/sys/class/net/'+dev))return {rows:[],count:0};
let dump=nl.request(nl.const.NL80211_CMD_GET_STATION,nl.const.NLM_F_DUMP,{dev}), rows=[], seen={};
// Drivers without station metrics still expose association through hostapd.
// Both are sources in this single collector, never an alternate backend.
for(let s in dump || []) {
let mac=lc(s.mac || '');
if(!match(mac,/^([0-9a-f]{2}:){5}[0-9a-f]{2}$/) || seen[mac])continue;
seen[mac]=true;
let i=s.sta_info || {}, lease=leases[mac] || {};
let rate=(r)=>(r?.bitrate32 ?? r?.bitrate)!=null?sprintf('%g Mbit/s',(r.bitrate32 ?? r.bitrate)/10.0):null;
push(rows,{mac,host:lease.host,ip:lease.ip,signal:i.signal ?? null,
tx:rate(i.tx_bitrate),rx:rate(i.rx_bitrate),
conn:i.connected_time!=null?sprintf('%d min',int(i.connected_time/60)):null});
}
if(!length(rows)) {
let associated=call(bus,'hostapd.'+dev,'get_clients').clients;
if(associated!=null && dump==null)dump=[];
for(let mac in associated || {}) {
mac=lc(mac);
if(!match(mac,/^([0-9a-f]{2}:){5}[0-9a-f]{2}$/))continue;
let lease=leases[mac] || {};
push(rows,{mac,host:lease.host,ip:lease.ip,signal:null,tx:null,rx:null,conn:null});
}
}
return {rows,count:dump==null && !length(rows)?null:length(rows)};
};
export function conntrack() {
let raw=rd('/proc/sys/net/netfilter/nf_conntrack_count');
let scalar=match(raw,/^[0-9]+$/)?+raw:null;
if(scalar!=null)return scalar;
// Older kernels may expose only the table. Count it in bounded chunks,
// as wc -l did, rather than allocating a potentially huge connection table.
fs.error();
let table=fs.open(ROOT+'/proc/net/nf_conntrack','r');
if(!table)return null;
let count=0;
while(true) {
let chunk=table.read(4096);
if(chunk==null || chunk=='')break;
count+=length(split(chunk,'\n'))-1;
}
let error=fs.error(); table.close();
return error?null:count;
};
export function info(slot) {
const c=cursor(CONFIG), bus=connect(null,2), now=time();
function cfg(k,d) { return c.get('unisoc_modem','main',k) || d; }
let iface=cfg('data_interface','wan'), iface6=cfg('data_interface_v6','wan6');
let wan=match(iface,/^[A-Za-z0-9_]{1,32}$/)?call(bus,'network.interface.'+iface,'status'):{};
let wan6=match(iface6,/^[A-Za-z0-9_]{1,32}$/)?call(bus,'network.interface.'+iface6,'status'):{};
let mobile=device(wan.l3_device || wan.device || cfg('data_device','sipa_eth0'));
let lan=device(cfg('lan_device','br-lan')), usb=device(cfg('usb_device','usb0'));
let wifi=hotspot.status(c,call(bus,'network.wireless','status'),cfg('wifi_iface',null),cfg('wifi_device','wlan0'));
let wd=device(wifi.device || cfg('wifi_device','wlan0'));
let rows4=rt.request(rt.const.RTM_GETADDR,rt.const.NLM_F_DUMP,{family:rt.const.AF_INET});
let rows6=rt.request(rt.const.RTM_GETADDR,rt.const.NLM_F_DUMP,{family:rt.const.AF_INET6});
let leases=[], bymac={};
for(let line in split(rd('/tmp/dhcp.leases'),'\n')) {
let f=split(trim(line),/[ \t]+/);
if(length(f)<4)continue;
let row={host:f[3]=='*'?null:text(f[3]),ip:text(f[2]),mac:text(f[1]),left:max(0,(num(f[0]) || 0)-now)};
push(leases,row); bymac[lc(f[1])]=row;
}
let stations=clients(wd,bus,bymac), hapd=wd?call(bus,'hostapd.'+wd,'get_status'):{};
let cpu=split(split(rd('/proc/stat'),'\n')[0],/[ \t]+/), total=0;
for(let i=1;i<=8;i++)total+=num(cpu[i]) || 0;
let freqs=[];
for(let p in fs.glob(ROOT+'/sys/devices/system/cpu/cpufreq/policy*') || []) {
if(fs.readfile(p+'/scaling_cur_freq')==null)continue;
push(freqs,{cur:num(trim(fs.readfile(p+'/scaling_cur_freq') || '')),max:num(trim(fs.readfile(p+'/cpuinfo_max_freq') || ''))});
}
let mem={};
for(let line in split(rd('/proc/meminfo'),'\n')) {
let m=match(line,/^(MemTotal|MemAvailable):[ \t]+([0-9]+)/);
if(m)mem[m[1]]=+m[2];
}
let temps={soc:null,cpu:null,modem:null,board:null,hottest:null};
let labels={'soc-thmzone':'soc','apcpu0-thmzone':'cpu','nr0-thmzone':'modem','board-thmzone':'board'};
for(let z in fs.glob(ROOT+'/sys/class/thermal/thermal_zone*') || []) {
let t=num(trim(fs.readfile(z+'/temp') || '')), kind=trim(fs.readfile(z+'/type') || '');
if(t==null)continue;
t=+sprintf('%.1f',t/1000.0);
if(temps.hottest==null || t>temps.hottest)temps.hottest=t;
if(labels[kind] && temps[labels[kind]]==null)temps[labels[kind]]=t;
}
let vfs=statvfs(ROOT || '/'), storage={total_kb:null,used_kb:null,avail_kb:null};
if(vfs?.frsize)storage={total_kb:vfs.blocks*vfs.frsize/1024,used_kb:(vfs.blocks-vfs.bfree)*vfs.frsize/1024,avail_kb:vfs.bavail*vfs.frsize/1024};
let release=match(rd('/etc/openwrt_release'),/DISTRIB_DESCRIPTION='([^']*)'/);
let kernel=rd('/proc/sys/kernel/osrelease'), fw=release?release[1]:'Linux '+kernel;
let private_fw=obj('/etc/unisoc-ota/current.json')?.version || rd('/etc/mu300/image-version');
if(private_fw)fw=private_fw+' ('+fw+')';
let data_slot=cfg('data_sim','0')=='1'?'1':'0';
let selection=apn.status(c,obj('/run/unisoc-apn-sim'+data_slot+'.json') || {}), selected_apn=null;
if(selection.ok && (slot==null || ''+selection.data_sim==slot) && selection.source in ['sim','auto','network','default'] &&
type(selection.apn)=='string' && length(selection.apn)<=100 && !match(selection.apn,/[^A-Za-z0-9.-]/))
selected_apn=selection.apn || '(SIM default)';
let dns=[];
for(let w in [wan,wan6])for(let ip in w['dns-server'] || [])if(index(dns,ip)<0)push(dns,ip);
let atd=false;
for(let p in ['/run/mu300-at','/run/mu300-at4']) {
let pid=rd(p+'/owner/pid');
if(match(pid,/^[1-9][0-9]*$/) && exists('/proc/'+pid) && fs.stat(ROOT+p+'/cmd')?.type=='fifo')atd=true;
}
let urc=fs.stat(ROOT+'/run/mu300-at/urc/stty_nr0.log');
let vpn=rd('/etc/mu300/vpn.conf'), engine=null, enabled=false;
for(let line in split(vpn,'\n')) {
if(line=='ENABLE=1')enabled=true;
if(substr(line,0,7)=='ENGINE=')engine=text(substr(line,7));
}
let ht=replace(wifi.htmode || '',/[^0-9]/g,'');
return {ts:now,uptime:int(rd('/proc/uptime')),host:text(c.get('system','@system[0]','hostname') || rd('/proc/sys/kernel/hostname')),
model:text(rd('/tmp/sysinfo/model') || replace(rd('/proc/device-tree/model'),/\x00/g,'')),fw,kernel,
cpu:{n:length(filter(split(rd('/proc/cpuinfo'),'\n'),line=>!!match(line,/^processor[ \t]*:/))),total,idle:(num(cpu[4]) || 0)+(num(cpu[5]) || 0),freqs},
mem:{total_kb:mem.MemTotal ?? null,avail_kb:mem.MemAvailable ?? null},storage,temps,power:power(),
net:{mobile:net(mobile),sipa_eth0:net(mobile),brlan:net(lan),wlan0:net(wd),usb0:net(usb)},
wan:{up:wan.up?1:0,uptime:wan.uptime ?? null,proto:text(wan.proto),device:mobile,apn:selected_apn,
ip4:wan['ipv4-address']?.[0]?.address ?? null,ip6:address(rows6,mobile,true),dns:text(join(', ',dns))},
wifi:{available:wifi.available?1:0,enabled:wifi.enabled?1:0,pending:wifi.pending?1:0,section:text(wifi.section),radio:text(wifi.radio),
error:text(wifi.error),up:wifi.up && hapd.status=='ENABLED' && exists('/sys/class/net/'+wd)?1:0,
ssid:text(wifi.ssid),channel:text(wifi.channel),band:text(wifi.band),width:ht?substr(ht,0,2)+' MHz':null,
country:text(wifi.country),enc:wifi.enc || 'none',hidden:wifi.hidden ?? null,hostapd:hapd.status=='ENABLED'?1:0,
clients:stations.rows,clients_n:stations.count},
lan:{leases:length(leases),ip:address(rows4,lan,false),list:leases},
modem:{alive:atd || (urc && now-urc.mtime<240)?1:0,atd:atd?1:0,data_paused:exists('/run/mu300-mobile-data-down')?1:0},
boot:boot(),capabilities:{vpn:executable('/etc/init.d/mu300-vpn')?1:0,dualboot:executable('/opt/mu300/bin/mu300-next-boot')?1:0},
conns:conntrack(),traffic:obj('/run/unisoc-modem-traffic/view.json'),
vpn:{enabled:enabled?1:0,engine,up:exists('/sys/class/net/xtun') || exists('/sys/class/net/sbtun')?1:0}};
};
function age(path) { let s=fs.stat(ROOT+path); return s?.size>0?time()-s.mtime:-1; }
function owner(dir) {
let pid=rd(dir+'/pid');
return match(pid,/^[1-9][0-9]*$/) && exists('/proc/'+pid) &&
!!match(join(' ',split(rd('/proc/'+pid+'/cmdline'),'\x00')),/unisoc-modem\/cell|mu300-modemd/);
};
export function status(slot,cells) {
let c=cursor(CONFIG);
if(!(slot in ['0','1']) || (slot=='1' && c.get('unisoc_modem','main','sim_slots')!='2'))return {error:'SIM 卡槽不可用'};
let dir='/tmp/unisoc-modem'+(slot=='1'?'/sim1':''), cage=age(dir+'/cell.json'), sage=age(dir+'/sig.json');
let busy=exists('/run/unisoc-modem-lock-apply') || exists('/run/unisoc-data-sim-switch') || owner(dir+'/collect.lck');
let fast=busy || owner(dir+'/fast.lck'), failed=false;
let mode=cage<0 || cage>=5?'full':sage<0 || sage>=1?'fast':null;
if(mode && !(mode=='full'?busy:fast)) {
let r=connect(null,2)?.call('mu300.modem','collect',{slot,mode});
failed=!r?.started && !r?.busy;
if(mode=='full' && (r?.started || r?.busy))busy=true;
}
return {info:cells?null:info(slot),cell:failed?{error:'Unable to read cellular status'}:obj(dir+'/cell.json'),
sig:failed?{error:'Unable to read cellular status'}:obj(dir+'/sig.json'),cell_age:cage,sig_age:sage,refreshing:busy?1:0};
};
export function sms_head(slot) {
let c=cursor(CONFIG);
if(!(slot in ['0','1']) || (slot=='1' && c.get('unisoc_modem','main','sim_slots')!='2'))return {error:'SIM 卡槽不可用'};
let cmd=c.get('unisoc_modem','main','sms_command') || '';
// Adapter selection is explicit configuration. An external adapter owns
// its format; never assume its records use the native pool layout.
if(cmd && !match(cmd,/(^|\/)mu300-sms$/))return {adapter:true};
let pool=rtrim(c.get('unisoc_modem','main','sms_pool') || '/etc/mu300/sms','/');
if(pool=='/etc/unisoc-modem/sms')pool='/etc/mu300/sms';
if(substr(pool,0,1)!='/' || match(pool,/[[:cntrl:]]/) || index(pool,'//')>=0 ||
length(filter(split(pool,'/'),part=>part=='.' || part=='..')))
return {error:'Invalid SMS pool'};
if(slot=='1')pool+='/sim1';
let s=fs.stat(ROOT+pool+'/msg');
return {source:pool,next_id:num(rd(pool+'/next_id')),count:length(filter(fs.lsdir(ROOT+pool+'/msg') || [],f=>!!match(f,/^[0-9]+$/))),mtime:s?.mtime ?? null};
};
@@ -0,0 +1,38 @@
// Resident rate sampler, adapted from liuwang97/cpu-load with the local WAN schema.
import { readfile } from 'fs';
import { cursor } from 'uci';
import { connect } from 'ubus';
export function sample() {
const cfg = cursor();
const iface = cfg.get('unisoc_modem', 'main', 'data_interface') || 'wan';
let status;
if (match(iface, /^[A-Za-z0-9_]{1,32}$/)) {
// Same live interface priority as the full snapshot. Bound an unavailable
// netifd without adding AT, retries, or another refresh timer.
try {
const bus = connect(null, 1);
status = bus?.call('network.interface.' + iface, 'status', {});
} catch (e) {}
}
const device = status?.l3_device || status?.device ||
cfg.get('unisoc_modem', 'main', 'data_device') || 'sipa_eth0';
if (!match(device, /^[A-Za-z0-9_.:-]{1,15}$/)) {
return {available:false};
}
const path = '/sys/class/net/' + device + '/';
const rx = readfile(path + 'statistics/rx_bytes');
const tx = readfile(path + 'statistics/tx_bytes');
const index = readfile(path + 'ifindex');
const uptime = readfile('/proc/uptime');
const valid = rx != null && tx != null && index != null && uptime != null;
return {
available: valid,
device: device,
ifindex: valid ? int(index) : null,
boot_id: trim(readfile('/proc/sys/kernel/random/boot_id') || ''),
ts: valid ? +split(uptime, ' ')[0] : null,
rx: valid ? +trim(rx) : null,
tx: valid ? +trim(tx) : null
};
};
+15 -183
View File
@@ -20,196 +20,28 @@ START=19
USE_PROCD=1
export PATH="$PATH:/opt/mu300/busybox-bin"
. "${MU300_SMS_POOL_LIB:-/opt/mu300/lib/sms-pool.sh}" || exit 1
. "${MU300_MODEMD_SERVICE_LIB:-/opt/mu300/lib/modemd-service.sh}" || exit 1
# wait for a SIPC tty inside the procd command: the nodes appear when the CP is alive, and an init
# script that returns without opening an instance never gets a second chance. Bounded (240 s) so a
# kernel without the modem stack says so instead of spinning silently - procd respawns and retries.
wait_and_exec() {
# $1 = tty node, $2.. = the daemon and its env is set by the caller
local dev=$1; shift
local ready="[ -c $dev ]"
if [ "$(/opt/mu300/bin/mu300-device 2>/dev/null)" = u30air ]; then
ready="$ready && [ -c /dev/sipc_sbuf ] && grep -q '^sbuf_5_006, state: 1,' /dev/sipc_sbuf"
fi
echo "n=0; until $ready; do n=\$((n+1)); if [ \"\$n\" -gt 240 ]; then echo 'mu300-atd: $dev never appeared' >&2; exit 1; fi; sleep 1; done; exec $*"
}
start_legacy() {
local sms_pool=$(mu300_sms_pool)
start_service() {
# Resolve board capabilities before creating any physical owner.
/opt/mu300/bin/mu300-platform-config || return 1
if [ "$(/opt/mu300/bin/mu300-device 2>/dev/null)" = u30air ]; then
mkdir -p /run/mu300
: > /run/mu300/u30-native
# The missing-policy-library path must also pin SIM1, regardless of
# an old saved SIM2 preference. No fallback may dial an unprepared RF.
[ -s /run/mu300/sim-slot ] || printf '0\n' > /run/mu300/sim-slot
if [ -e /run/mu300-radio-freeze ] || [ -e /run/mu300/sim-slot ]; then
echo 'mu300-atd: SIM controller changed; reboot before starting owners' >&2
return 1
fi
fi
# Do not migrate NR3 ownership after daemons have opened the SIPC ttys.
[ ! -x /opt/mu300/bin/mu300-platform-config ] || /opt/mu300/bin/mu300-platform-config
# Optional plugin handshake: reserve nr1's first-command window for the
# platform radio-on path. The generic worker waits for this marker to clear.
[ ! -x /usr/libexec/unisoc-modem/lock ] || : > /run/unisoc-modem-early-hook-pending
[ -x /opt/mu300/bin/bootmark ] && /opt/mu300/bin/bootmark S19-atd-init
procd_open_instance atd
procd_set_param env MU300_AT_DISABLE_REOPEN="$([ "$(/opt/mu300/bin/mu300-device 2>/dev/null)" = u30air ] && echo 1 || echo 0)" MU300_SMS_POOL="$sms_pool"
procd_set_param command /bin/sh -c "$(wait_and_exec /dev/stty_nr1 /opt/mu300/bin/mu300-atd)"
[ "$(/opt/mu300/bin/mu300-device 2>/dev/null)" = u30air ] || procd_set_param respawn 3600 10 0
procd_set_param stdout 1
procd_set_param stderr 1
procd_close_instance
# second instance on nr2 (mobile-data's dedicated channel)
procd_open_instance atd2
procd_set_param command /bin/sh -c "$(wait_and_exec /dev/stty_nr2 /opt/mu300/bin/mu300-atd)"
procd_set_param env MU300_AT_DISABLE_REOPEN="$([ "$(/opt/mu300/bin/mu300-device 2>/dev/null)" = u30air ] && echo 1 || echo 0)" MU300_SMS_POOL="$sms_pool" MU300_AT_DEV=/dev/stty_nr2 MU300_AT_DIR=/run/mu300-at2 MU300_AT_URC_CHANNELS= MU300_AT_ALIVE_LOG=/run/mu300-at/urc/stty_nr0.log
[ "$(/opt/mu300/bin/mu300-device 2>/dev/null)" = u30air ] || procd_set_param respawn 3600 10 0
procd_set_param stdout 1
procd_set_param stderr 1
procd_close_instance
# Keep slot 1's nr3/nr4/nr5 open like the vendor RIL does. The optional
# nr6/nr7 channels are the bounded slot-0 dashboard pool; all descriptors
# remain open for the life of the boot so failover never requires a reopen.
local n urc pool alive_log
for n in 3 4 5 6 7; do
# NR3 is the slot-1 URC stream, not an extra command reader. Ownership
# changes only at boot: never restart atd to enable this on a live CP.
[ "$n" != 3 ] || [ "$(uci -q get unisoc_modem.main.sim_slots)" != 2 ] || continue
procd_open_instance atd$n
procd_set_param command /bin/sh -c "$(wait_and_exec /dev/stty_nr$n /opt/mu300/bin/mu300-atd)"
urc= pool=$sms_pool alive_log=/run/mu300-at/urc/stty_nr0.log
case "$n" in 3|4|5)
pool=$sms_pool/sim1
if [ "$n" = 4 ] && [ "$(uci -q get unisoc_modem.main.sim_slots)" = 2 ]; then
urc=3 alive_log=/run/mu300-at4/urc/stty_nr3.log
fi ;;
esac
# Set the env table ONCE. Adding another table with the same JSON key
# can leave procd with only MU300_AT_DEV and the wrong owner directory.
procd_set_param env MU300_AT_DISABLE_REOPEN="$([ "$(/opt/mu300/bin/mu300-device 2>/dev/null)" = u30air ] && echo 1 || echo 0)" MU300_AT_DEV=/dev/stty_nr$n MU300_AT_DIR=/run/mu300-at$n MU300_AT_URC_CHANNELS=$urc "MU300_SMS_POOL=$pool" MU300_AT_ALIVE_LOG=$alive_log
[ "$(/opt/mu300/bin/mu300-device 2>/dev/null)" = u30air ] || procd_set_param respawn 3600 10 0
procd_set_param stdout 1
procd_set_param stderr 1
procd_close_instance
done
# Turn the radio on as soon as nr1's persistent daemon is ready, in a
# separate procd process. This overlaps the remaining rc scripts and leaves
# PDP activation to netifd. The FIFO is the readiness event; mobile-data's
# radio lock excludes a simultaneous dial-up state machine.
procd_open_instance radio-warmup
procd_set_param command /bin/sh -c 'n=0; until [ -p /run/mu300-at/cmd ]; do n=$((n+1)); [ "$n" -gt 90 ] && exit 1; sleep 1; done; exec /opt/mu300/bin/mobile-data radio-on'
procd_set_param stdout 1
procd_set_param stderr 1
procd_close_instance
}
# broker NAME CHANNEL DIR URC-CHANNELS LIVE-URC-LOG [WAIT]: one persistent owner of a SIPC tty. WAIT is a shell
# condition the instance waits for (bounded) before it opens the channel: the second group's channels have a node
# before the CP is up, and spipe_open returns ENODEV until the sbuf is READY, which the driver's seqfile shows.
# The wait is inside the instance, never in start_service: an init script that waits returns without instances
# when the wait fails, and a boot without AT brokers is a boot without WAN.
broker() {
local name=$1 channel=$2 directory=$3 urc=$4 live=$5 wait=${6:-} condition= pool=$(mu300_sms_pool)
[ "$channel" -lt 3 ] || pool=$pool/sim1
# A literal brace inside ${...:+...} closes the expansion early in ash. Build it separately.
[ -z "$wait" ] || condition=" && { $wait; }"
procd_open_instance "$name"
procd_set_param command /bin/sh -c "n=0; until [ -c /dev/stty_nr$channel ]$condition; do n=\$((n+1)); [ \"\$n\" -gt 240 ] && { echo 'mu300-atd: /dev/stty_nr$channel never became ready' >&2; exit 1; }; sleep 1; done; exec /opt/mu300/bin/mu300-atd"
procd_set_param env "MU300_AT_DEV=/dev/stty_nr$channel" "MU300_AT_DIR=$directory" \
"MU300_AT_URC_CHANNELS=$urc" "MU300_AT_ALIVE_LOG=$live" "MU300_SMS_POOL=$pool" \
MU300_AT_DISABLE_REOPEN=1
# A failed owner stays failed during this boot (no respawn): restarting it would reopen a SIPC channel, and
# the cold start / the switch refuse to run without all four owners rather than talk to a reopened one.
procd_set_param stdout 1
procd_set_param stderr 1
procd_close_instance
}
SBUF_READY="[ -c /dev/sipc_sbuf ] && grep -q '^sbuf_5_006, state: 1,' /dev/sipc_sbuf"
start_sim2() {
mkdir -p /run/mu300
[ ! -x /usr/libexec/unisoc-modem/lock ] || : > /run/unisoc-modem-early-hook-pending
# Before S20network or any radio-warmup process: inhibit automatic SIM1 bring-up for this entire boot.
: > /run/mu300-radio-freeze
: > /run/mu300/sim-active-unknown
[ "$hot" != 1 ] || : > /run/mu300/sim-managed
broker atd 1 /run/mu300-at 0 /run/mu300-at/urc/stty_nr0.log "$SBUF_READY"
broker atd2 2 /run/mu300-at2 '' /run/mu300-at/urc/stty_nr0.log "$SBUF_READY"
broker atd4 4 /run/mu300-at4 3 /run/mu300-at4/urc/stty_nr3.log "$SBUF_READY"
broker atd5 5 /run/mu300-at5 '' /run/mu300-at4/urc/stty_nr3.log "$SBUF_READY"
# The cold start (and its fallback to SIM1 when it cannot be done): mu300-sim2-warmup confirms the boot.
procd_open_instance sim2-cold-start
procd_set_param command /bin/bash /opt/mu300/bin/mu300-sim2-warmup
[ ! -x /opt/mu300/bin/bootmark ] || /opt/mu300/bin/bootmark S19-atd-init
modemd_require || return 1
# Both SIM groups keep one URC reader and persistent command owners.
# U30 retains sbuf readiness, no SIPC reopen and no bridge respawn.
modemd_single_layout
procd_open_instance radio-warmup
procd_set_param command /bin/sh -c 'n=0; until [ -p /run/mu300-at/cmd ] && { [ "$(uci -q get unisoc_modem.main.sim_slots)" != 2 ] || [ -p /run/mu300-at4/cmd ]; }; do n=$((n+1)); [ "$n" -gt 90 ] && exit 1; sleep 1; done; exec /opt/mu300/bin/mobile-data radio-on'
procd_set_param stdout 1
procd_set_param stderr 1
procd_close_instance
}
# sim_fallback REASON: back to SIM1 without live switching, the reason kept for the Dual SIM page (mu300-sim status).
# It never fails its caller: settings that cannot be written (a full or read-only filesystem) leave the pending
# marker, and the caller makes this boot a SIM1 boot either way.
sim_fallback() {
echo "mu300-atd: dual SIM: $1; SIM1 without live switching from now on" >&2
printf '%s\n' "$1" > /etc/mu300-sim-fallback 2>/dev/null
sim_cfg_save_default 0 && sim_cfg_save_hot 0 && rm -f /etc/mu300-sim-pending
return 0
}
# sim1_only: this boot is a plain SIM1 boot, whatever was chosen. The pin says so to every reader (mu300-sim active):
# without it start_legacy would take a saved second card for the F50's kind and open nr4/nr5 under SIM1's names.
sim1_only() {
mkdir -p /run/mu300
printf '0\n' > /run/mu300/sim-slot
start_legacy
}
# Every path through here ends with AT owners started: a return without instances is a boot without modem control,
# and nothing starts this service a second time. Whatever cannot be read, written or understood is a SIM1 boot.
start_service() {
[ ! -x /opt/mu300/bin/mu300-platform-config ] || /opt/mu300/bin/mu300-platform-config
local slot hot temporary lib=${MU300_SIM_CONFIG_LIB:-/opt/mu300/lib/sim-config.sh}
# Only the U30 Air has the second group and the validated sequences; everywhere else the files are ignored.
[ "$(/opt/mu300/bin/mu300-device 2>/dev/null)" = u30air ] || { start_legacy; return; }
[ -r "$lib" ] || { start_legacy; return; }
mkdir -p /run/mu300
: > /run/mu300/u30-native
SIM_CONFIG_U30=1
. "$lib"
mkdir -p /run/mu300
# mu300-sim2-warmup gave the dual-SIM start up in this boot and started the service over: SIM1, nothing else
[ ! -e /run/mu300/sim-fallback-boot ] || { sim1_only; return; }
sim_cfg_migrate || sim_fallback invalid-settings
slot=$(cat /run/mu300/sim-slot 2>/dev/null || sim_cfg_default) || slot=invalid
hot=$(sim_cfg_hot) || hot=invalid
case "$hot" in 0|1) ;; *) sim_fallback invalid-hot; slot=0; hot=0;; esac
case "$slot" in 0|1) ;; *) sim_fallback invalid-slot; slot=0; hot=0 ;; esac
# One boot at a time: the dual-SIM path leaves a pending marker that mu300-sim2-warmup removes once the radio
# is up (or it falls back itself). A marker still there at the next boot means that boot never confirmed
# (a broker that never came up, a warm-up that died): this boot is a plain SIM1 boot, and the page says why.
if [ ! -e /run/mu300/sim-boot-policy ] && [ -e /etc/mu300-sim-pending ]; then
sim_fallback unconfirmed
: > /run/mu300/sim-boot-policy
sim1_only; return
fi
: > /run/mu300/sim-boot-policy
# Pin the active slot for this boot; changing network.wan.sim_slot only affects the next boot.
if [ ! -e /run/mu300/sim-slot ]; then
temporary=$(mktemp /run/mu300/sim-slot.XXXXXX) || { sim1_only; return; }
printf '%s\n' "$slot" > "$temporary"
ln "$temporary" /run/mu300/sim-slot 2>/dev/null
rm -f "$temporary"
fi
slot=$(cat /run/mu300/sim-slot 2>/dev/null) || slot=invalid
case "$slot:$hot" in
0:0) start_legacy ;;
0:1|1:[01])
# The dual-SIM path's helpers are bash, and its one-boot guarantee needs the marker on the disk: without
# either this is a SIM1 boot, and the settings go back so that the next one does not try again.
if command -v bash >/dev/null 2>&1 && touch /etc/mu300-sim-pending 2>/dev/null; then
start_sim2
else
sim_fallback not-startable
sim1_only
fi ;;
*) echo "mu300-atd: invalid SIM slot $slot; SIM1" >&2; sim1_only ;;
esac
}
-14
View File
@@ -1,14 +0,0 @@
#!/bin/sh /etc/rc.common
# the buttons: power wakes the LEDs (held: shut down), the U30 Air's Wi-Fi key switches the hotspot band
# (see /opt/mu300/bin/mu300-buttons)
START=95
USE_PROCD=1
export PATH="$PATH:/opt/mu300/busybox-bin"
start_service() {
[ -x /opt/mu300/bin/mu300-keys ] || return 0
procd_open_instance buttons
procd_set_param command /opt/mu300/bin/mu300-buttons
procd_set_param respawn 3600 10 0
procd_close_instance
}
+26 -5
View File
@@ -14,24 +14,45 @@ boot() {
}
hw_bringup() {
[ ! -x /opt/mu300/bin/bootmark ] || /opt/mu300/bin/bootmark wifi-hw-enter
# switch_root terminates initramfs background jobs. Resume the same tracked
# chase immediately and keep it until mu300-post (or an earlier WAN success)
# selects the steady state.
/opt/mu300/bin/led-status boot 2>/dev/null
/opt/mu300/bin/extra-modules >/tmp/mu300-extra-modules.log 2>&1
/opt/mu300/bin/zram-start >/dev/null 2>&1
/opt/mu300/bin/wifi-start >/tmp/mu300-wifi-start.log 2>&1
/opt/mu300/bin/openwrt-board-check >>/tmp/mu300-wifi-start.log 2>&1 || return 1
# cfg80211 looked for regulatory.db before the rootfs was mounted; load it now so hostapd sees the country rules
[ ! -x /opt/mu300/bin/bootmark ] || /opt/mu300/bin/bootmark wifi-board-ready
# Set regulatory rules before the PHY appears and netifd starts APs.
/opt/mu300/bin/regdb-load >>/tmp/mu300-wifi-start.log 2>&1
[ ! -x /opt/mu300/bin/bootmark ] || /opt/mu300/bin/bootmark wifi-regdb-ready
country=$(uci -q get wireless.radio0.country)
[ -z "$country" ] || iw reg set "$country"
/opt/mu300/bin/wifi-start >>/tmp/mu300-wifi-start.log 2>&1
[ ! -x /opt/mu300/bin/bootmark ] || /opt/mu300/bin/bootmark wifi-driver-ready
/opt/mu300/bin/extra-modules >/tmp/mu300-extra-modules.log 2>&1
[ ! -x /opt/mu300/bin/bootmark ] || /opt/mu300/bin/bootmark wifi-extra-modules-done
/opt/mu300/bin/zram-start >/dev/null 2>&1
cfg=$(sha256sum /etc/config/wireless 2>/dev/null)
/opt/mu300/bin/openwrt-wifi-config >>/tmp/mu300-wifi-start.log 2>&1
[ ! -x /opt/mu300/bin/bootmark ] || /opt/mu300/bin/bootmark wifi-config-ready
# Supported NFC tags (U30 Air / V50): retain custom text/URLs, synchronize Wi-Fi.
/opt/mu300/bin/mu300-nfc supported 2>/dev/null && /opt/mu300/bin/mu300-nfc sync >/tmp/mu300-nfc.log 2>&1
[ ! -x /opt/mu300/bin/bootmark ] || /opt/mu300/bin/bootmark wifi-nfc-done
reg_ready=1
# apply the country before netifd starts hostapd, otherwise 5 GHz channels are still NO-IR under world rules
country=$(uci -q get wireless.radio0.country)
if [ -n "$country" ]; then
iw reg set "$country"
for n in $(seq 1 10); do iw reg get | grep -q "country $country:" && break; sleep 1; done
reg_ready=0
for n in $(seq 1 10); do
if iw reg get | grep -q "country $country:"; then reg_ready=1; break; fi
sleep 1
done
fi
# Keep working APs when netifd already applied unchanged settings.
if [ "$reg_ready" = 1 ] && [ -n "$cfg" ] && [ "$cfg" = "$(sha256sum /etc/config/wireless 2>/dev/null)" ] &&
/opt/mu300/bin/wifi-ready; then
echo 'configured wireless interfaces already ready; retaining them' >>/tmp/mu300-wifi-start.log
return 0
fi
# netifd may have scanned before the late, external SC2355 driver created
# phy0. Reconcile once immediately when firmware and regulatory data are
-4
View File
@@ -54,10 +54,6 @@ start_service() {
procd_set_param env MU300_NETIFD=1 PATH="$PATH"
procd_set_param respawn 3600 30 0
procd_close_instance
procd_open_instance thermalguard
procd_set_param command /opt/mu300/bin/thermal-guard
procd_set_param env PATH="$PATH"
procd_close_instance
procd_open_instance bootok
procd_set_param command /bin/sh -c "sleep 30; exec /opt/mu300/bin/mu300-next-boot --rearm"
procd_set_param env PATH="$PATH"
@@ -0,0 +1,9 @@
#!/bin/sh /etc/rc.common
# One-shot placement after procd creates the services hierarchy.
START=95
start() {
/opt/mu300/bin/mu300-service-cpus apply || {
logger -t mu300-service-cpus 'Failed to apply saved service CPU placement'
return 1
}
}
+2 -2
View File
@@ -11,7 +11,7 @@ start_service() {
procd_open_instance smsd
procd_set_param command /opt/mu300/bin/mu300-smsd
# /var is tmpfs on OpenWrt; the pool is small and worth keeping across reboots
procd_set_param env MU300_SMS_POOL="$sms_pool" MU300_SIM_SLOT=0
procd_set_param env MU300_SMS_TRANSPORT=ubus MU300_SMS_POOL="$sms_pool" MU300_SIM_SLOT=0
procd_set_param respawn 3600 10 0
procd_set_param stdout 1
procd_set_param stderr 1
@@ -19,7 +19,7 @@ start_service() {
if [ "$(uci -q get unisoc_modem.main.sim_slots)" = 2 ]; then
procd_open_instance smsd-sim1
procd_set_param command /opt/mu300/bin/mu300-smsd
procd_set_param env MU300_SMS_POOL="$sms_pool/sim1" MU300_AT_DIR=/run/mu300-at4 MU300_SIM_SLOT=1 MU300_SMS_LOCK=/run/mu300-smsd-sim1.lock MU300_SMS_OP_LOCK=/tmp/mu300-sms-op-sim1.lock MU300_SMS_DIRECT_FLAG=/run/mu300-sms-direct-sim1
procd_set_param env MU300_SMS_TRANSPORT=ubus MU300_SMS_POOL="$sms_pool/sim1" MU300_AT_DIR=/run/mu300-at4 MU300_SIM_SLOT=1 MU300_SMS_LOCK=/run/mu300-smsd-sim1.lock MU300_SMS_OP_LOCK=/tmp/mu300-sms-op-sim1.lock MU300_SMS_DIRECT_FLAG=/run/mu300-sms-direct-sim1
procd_set_param respawn 3600 10 0
procd_set_param stdout 1
procd_set_param stderr 1
+14
View File
@@ -0,0 +1,14 @@
#!/bin/sh /etc/rc.common
# Common keys, LED deadline checks and thermal guard; original helpers retain policy.
START=95
USE_PROCD=1
export PATH="$PATH:/opt/mu300/bin:/opt/mu300/busybox-bin"
start_service() {
/usr/bin/ucode /opt/mu300/bin/mu300-sysd --check || return 1
procd_open_instance sysd
procd_set_param command /usr/bin/ucode /opt/mu300/bin/mu300-sysd
procd_set_param respawn 3600 5 0
procd_set_param stdout 1
procd_set_param stderr 1
procd_close_instance
}
@@ -18,9 +18,7 @@ function read_json(path) {
try { return json(fs.readfile(path)); } catch (e) { return null; }
}
function selected_slot() {
// Native U30 boot selection takes precedence over a next-boot UI choice.
let native = trim(fs.readfile(runtime + '/sim-slot') || '');
let value = native || cfg.get('unisoc_modem', 'main', 'data_sim') || '0';
let value = cfg.get('unisoc_modem', 'main', 'data_sim') || '0';
return value == '0' ? 0 : value == '1' ? 1 : null;
}
function radio_busy() {
+53 -13
View File
@@ -21,8 +21,12 @@
# Track every /64: during renumbering old and new SLAAC addresses can coexist.
IF_INET6=${MU300_IF_INET6:-/proc/net/if_inet6}
IFACE=sipa_eth0
. "${MU300_NDP_INTERFACE_LIB:-/opt/mu300/lib/ndp-interface.sh}" || exit 1
ndp_iface_refresh || exit $?
bearer_prefixes() {
awk '$6=="sipa_eth0" && $4=="00" && length($1)==32 &&
awk -v iface="$IFACE" '$6==iface && $4=="00" && length($1)==32 &&
$1 ~ /^[23][0-9a-f]+$/ {
p=""
for (i=1; i<=4; i++) {
@@ -77,7 +81,7 @@ has_prefix() {
}
router_lifetime() {
ip -6 route show default dev sipa_eth0 2>/dev/null | awk '{
ip -6 route show default dev "$IFACE" 2>/dev/null | awk '{
for (i=1; i<NF; i++) if ($i=="expires") { v=$(i+1); sub(/sec$/, "", v) }
} END {
if (v !~ /^[0-9]+$/ || v+0<1) v=1800; else if (v+0>9000) v=9000
@@ -117,6 +121,11 @@ withdraw_old() {
logger -t ndp-learn "withdrawing from the LAN:$withdraw"
fi
[ -n "$withdraw" ] && [ "$withdraw_rounds" -gt 0 ] || return 0
if [ "${ndp_events:-0}" = 1 ]; then
ndp_clock || return 0
[ "$NDP_NOW" -ge "$NDP_WITHDRAW_AT" ] || return 0
NDP_WITHDRAW_AT=$((NDP_NOW + NDP_INTERVAL))
fi
withdraw_rounds=$((withdraw_rounds - 1))
# Fixed /64s from /proc, intentionally passed as separate arguments.
# shellcheck disable=SC2086
@@ -147,9 +156,9 @@ learn_once() {
# Remove only host routes inside the shared prefix; the LAN /64 resolves
# the client by NDP even before it appears in the neighbour table.
if [ -n "$prefixes" ]; then
for r in $(ip -6 route show dev sipa_eth0 2>/dev/null |
for r in $(ip -6 route show dev "$IFACE" 2>/dev/null |
prefix_hosts "$prefixes"); do
ip -6 route del "$r/128" dev sipa_eth0 2>/dev/null
ip -6 route del "$r/128" dev "$IFACE" 2>/dev/null
done
fi
# Do not recreate stale /128s just removed above from leftover neighbours.
@@ -165,15 +174,46 @@ case ${1:-} in
--once) learn_once; exit ;;
esac
# OpenWrt requires the packaged ip-full and event library.
. "${MU300_NDP_EVENTS_LIB:-/opt/mu300/lib/ndp-events.sh}" || exit 1
trap ndp_events_stop EXIT
trap 'exit 0' INT TERM
ndp_events_start || exit 1
ndp_seen= ndp_heal_at=0
while :; do
learn_once
# self-heal the bearer's own public address: the carrier's RA can be missed while the
# bearer settles after boot, and nothing else ever re-solicits - flip accept_ra to send
# a fresh router solicitation whenever the bearer has no global address
if ! ip -6 addr show sipa_eth0 2>/dev/null | grep -q 'scope global'; then
echo 0 > /proc/sys/net/ipv6/conf/sipa_eth0/accept_ra 2>/dev/null
sleep 1
echo 2 > /proc/sys/net/ipv6/conf/sipa_eth0/accept_ra 2>/dev/null
ndp_previous_iface=$IFACE
if ndp_iface_refresh; then :
else
status=$?
[ "$status" = 75 ] || exit "$status"
sleep 10
continue
fi
sleep 10
[ "$IFACE" = "$ndp_previous_iface" ] || { ndp_seen=; ndp_heal_at=0; NDP_FULL_AT=0; }
if ! ndp_snapshot 2>/dev/null; then
echo "ndp-learn: kernel IPv6 tables unavailable" >&2
exit 1
fi
ndp_clock
if [ "$NDP_SNAPSHOT" != "$ndp_seen" ] || [ "$NDP_DIRTY" = 1 ] ||
[ "$NDP_NOW" -ge "$NDP_FULL_AT" ] ||
{ [ "$withdraw_rounds" -gt 0 ] && [ "$NDP_NOW" -ge "$NDP_WITHDRAW_AT" ]; }; then
ndp_addresses=$NDP_ADDRESSES
learn_once
# The snapshot AFTER our writes absorbs our own route notifications.
ndp_snapshot || exit 1
# An RA arriving DURING the writes is external, not one of our
# notifications. Process it now instead of absorbing its address.
if [ "$NDP_ADDRESSES" != "$ndp_addresses" ]; then ndp_seen=; continue; fi
ndp_seen=$NDP_SNAPSHOT
NDP_FULL_AT=$((NDP_NOW + 10))
fi
# Preserve the original ten-second no-address solicitation cadence.
if [ "$NDP_GLOBAL" = 0 ] && [ "$NDP_NOW" -ge "$ndp_heal_at" ]; then
echo 0 > "/proc/sys/net/ipv6/conf/$IFACE/accept_ra" 2>/dev/null
sleep 1
echo 2 > "/proc/sys/net/ipv6/conf/$IFACE/accept_ra" 2>/dev/null
ndp_heal_at=$((NDP_NOW + 10))
fi
ndp_events_wait || exit 1
done
+63
View File
@@ -0,0 +1,63 @@
'use strict';
const fs = require('fs'), path = require('path'), assert = require('assert');
const repo = path.resolve(__dirname, '../..');
const app = fs.existsSync(path.join(repo, 'devices/e5')) ? 'luci-app-t551m' : 'luci-app-mu300';
const dir = path.join(repo, 'openwrt', app, 'htdocs/luci-static/resources');
String.prototype.format = function(...args) { let i=0; return this.replace(/%[ds]/g,()=>String(args[i++])); };
function el(tag,attrs={},children=[]) {
const node={tag,attrs,style:{},children:[],disabled:!!attrs.disabled,events:{},
appendChild(n){this.children.push(n);},
addEventListener(k,v){this.events[k]=v;},
querySelectorAll(){return all(this).filter(n=>n.tag==='button'||n.tag==='input');}};
for (const c of Array.isArray(children)?children:[children]) node.children.push(c);
return node;
}
function all(n) {return typeof n==='object'&&n ? [n,...n.children.flatMap(all)] : [];}
const lookup=(root,id)=>all(root).find(n=>n.attrs.id===id);
const text=n=>typeof n==='string'?n:n.children.map(text).join(' ');
const commonSource=fs.readFileSync(path.join(dir,'mu300/common.js'),'utf8');
const pageSource=fs.readFileSync(path.join(dir,'view/mu300/ttl.js'),'utf8');
(async()=>{
for(const lang of ['zh','en','tr']) {
const options=[];
const M=new Function('rpc','baseclass','L','document','navigator','sessionStorage',commonSource)(
{declare:o=>{options.push(o);return ()=>Promise.resolve({});}}, {extend:o=>o},
{env:{lang}}, {}, {}, {getItem(){return null;},setItem(){}});
assert(options.find(o=>o.method==='ttl_set').nobatch);
assert.equal(M.fmtBatteryCurrent(60000),'+60mA');
assert.equal(M.fmtBatteryCurrent(-123456),'-123mA');
assert.equal(M.fmtBatteryCurrent(null),'--');
assert.equal(M.fmtBatteryCurrent(NaN),'--');
const home=fs.readFileSync(path.join(dir,'view/mu300/home.js'),'utf8');
const nodes={}, values={};
const power=new Function('i','M',home.slice(home.indexOf('var p = i.power || {};'),home.indexOf("M.set('model'",home.indexOf('var p = i.power || {};'))));
const powerM={...M,v:id=>nodes[id]||(nodes[id]={style:{}}),set:(id,value)=>values[id]=value};
power({power:{present:1,capacity:44,status:'Charging',volt:3.7999999999999998,ua:12000,usb:1}},powerM);
assert.equal(values.batt,'44%');assert(values['batt-l'].includes('3.80 V'));
assert(values['batt-l'].includes('+12mA'));assert.equal(nodes['batt-bar'].style.width,'44%');
assert.equal(nodes['batt-meter'].hidden,false);
power({power:{present:0,usb:1}},powerM);
assert.equal(values.batt,'USB');assert.equal(nodes['batt-meter'].hidden,true);
let writes=[],finish,toast=[];
Object.assign(M,{injectCss(){},busy(){},toast:(msg,opts)=>toast.push([msg,opts]),
callTtlGet:()=>Promise.resolve({ok:1,enabled:1,value:64,backend:'nft',offload:0}),
callTtlSet:v=>{writes.push(v);return new Promise(resolve=>finish=resolve);}});
const page=new Function('view','dom','M','E',pageSource)({extend:o=>o},
{content:(n,c)=>{n.children=[c];}}, M, el);
const root=page.render({ok:1,enabled:0,backend:'none',offload:1});
assert(text(root).includes(lang==='zh'?'蜂窝网络 TTL':lang==='tr'?'Mobil veri TTL':'Cellular TTL'));
assert(text(root).includes(lang==='zh'?'降低转发性能':lang==='tr'?'performans':'performance'));
lookup(root,'mud-ttl-value').value='1; reboot';
lookup(root,'mud-ttl-custom').events.click();assert.equal(writes.length,0);
const a=page.set(lookup(root,'mud-ttl-64'),64);
assert(root.querySelectorAll().every(n=>n.disabled));
await page.set(lookup(root,'mud-ttl-128'),128);assert.deepEqual(writes,['64']);
finish({ok:0,error:'无法应用 TTL 设置'});await a;
assert(toast.at(-1)[1].type==='error');assert(!lookup(root,'mud-ttl-64').disabled);
const b=page.set(lookup(root,'mud-ttl-65'),65);finish({ok:1});await b;
assert.deepEqual(writes,['64','65']);assert.equal(lookup(root,'mud-ttl-off').disabled,false);
page.paint({ok:0,error:'无法读取 TTL 设置'});
assert(!lookup(root,'mud-ttl-custom'));
}
console.log('TTL page zh/en/tr: validation, serialization, errors, save/refresh and battery current passed');
})().catch(e=>{console.error(e);process.exitCode=1;});
+125
View File
@@ -0,0 +1,125 @@
#!/usr/bin/env python3
"""Run both repositories' TTL engine against isolated firewall/config commands."""
import json
import os
from pathlib import Path
import subprocess
import tempfile
import unittest
TOP = Path(__file__).resolve().parents[2]
APP = TOP / 'openwrt' / ('luci-app-t551m' if (TOP/'devices/e5').exists() else 'luci-app-mu300')
ENGINE = APP/'root/usr/libexec/unisoc-modem/ttl-engine'
class Ttl(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory(); self.addCleanup(self.tmp.cleanup)
self.root = Path(self.tmp.name)
self.bin = self.root/'bin'; self.bin.mkdir()
self.store = self.root/'firewall.json'
self.store.write_text(json.dumps({'flow_offloading':'1','flow_offloading_hw':'1'}))
self.conf = self.root/'etc/ttl.conf'
self.env = dict(os.environ, PATH=str(self.bin)+':'+os.environ['PATH'],
MU300_TTL_CONF=str(self.conf), MU300_TTL_LOCK=str(self.root/'lock'),
TEST_TTL_ROOT=str(self.root))
self.stub('uci', '''import sys,json,os
from pathlib import Path
r=Path(os.environ['TEST_TTL_ROOT']); p=r/'firewall.json'; d=json.loads(p.read_text())
a=sys.argv[1:]
if a[0]=='-q': a=a[1:]
if a[0]=='get': print(d.get(a[1].split('.')[-1],''))
elif a[0]=='set':
if (r/'uci.fail').exists(): sys.exit(1)
k,v=a[1].split('=');d[k.split('.')[-1]]=v;p.write_text(json.dumps(d))
''')
self.stub('fw4', '''import os,sys
from pathlib import Path
r=Path(os.environ['TEST_TTL_ROOT'])
with (r/'reloads').open('a') as f:f.write('reload\\n')
sys.exit(1 if (r/'reload.fail').exists() else 0)
''')
self.stub('nft', '''import os,sys,time
from pathlib import Path
r=Path(os.environ['TEST_TTL_ROOT']);a=sys.argv[1:];p=r/'rules'
if a[0]=='list': sys.exit(0 if p.exists() else 1)
if a[0]=='delete':p.unlink(missing_ok=True)
if a[0]=='-f':
data=sys.stdin.read()
if (r/'nft.fail').exists():sys.exit(1)
if (r/'delay').exists():time.sleep(.2)
p.write_text(data)
''')
def stub(self, name, code):
p=self.bin/name;p.write_text('#!/usr/bin/env python3\n'+code);p.chmod(0o755)
def call(self, *args, ok=True):
r=subprocess.run(['sh',str(ENGINE),*args],env=self.env,text=True,capture_output=True,timeout=10)
if ok:self.assertEqual(r.returncode,0,r.stderr)
else:self.assertNotEqual(r.returncode,0)
return r
def test_ipv4_ipv6_only_cellular_and_restore_both_offload_flags(self):
self.call('set','65')
rules=(self.root/'rules').read_text()
self.assertIn('ip ttl set 65',rules);self.assertIn('ip6 hoplimit set 65',rules)
self.assertEqual(rules.count('oifname "sipa_eth*"'),2)
self.assertNotIn('flush ruleset',rules)
self.assertEqual(json.loads(self.store.read_text()),{'flow_offloading':'0','flow_offloading_hw':'0'})
self.call('off')
self.assertEqual(json.loads(self.store.read_text()),{'flow_offloading':'1','flow_offloading_hw':'1'})
self.assertFalse(self.conf.exists());self.assertFalse((self.root/'rules').exists())
def test_invalid_values_do_not_change_settings(self):
for v in ('','0','01','256','-1','1; reboot','1\n2','1.5','999999999999'):
self.call('set',v,ok=False)
self.assertFalse(self.conf.exists());self.assertFalse((self.root/'reloads').exists())
def test_preserves_user_disabled_offload(self):
self.store.write_text(json.dumps({'flow_offloading':'0','flow_offloading_hw':'0'}))
self.call('set','64');self.call('apply');self.call('off')
self.assertEqual(json.loads(self.store.read_text()),{'flow_offloading':'0','flow_offloading_hw':'0'})
self.assertFalse((self.root/'reloads').exists())
def test_failed_atomic_rule_keeps_previous_value_and_can_retry(self):
self.call('set','64');before=(self.root/'rules').read_text()
(self.root/'nft.fail').touch();self.call('set','128',ok=False)
self.assertEqual(self.conf.read_text(),'TTL=64\n');self.assertEqual((self.root/'rules').read_text(),before)
(self.root/'nft.fail').unlink();self.call('set','128')
self.assertEqual(self.conf.read_text(),'TTL=128\n')
def test_reload_failure_is_reported_and_retried_even_after_uci_changed(self):
(self.root/'reload.fail').touch();self.call('set','64',ok=False)
self.assertFalse(self.conf.exists());self.assertFalse((self.root/'rules').exists())
(self.root/'reload.fail').unlink();self.call('set','64')
self.assertEqual((self.root/'reloads').read_text().count('reload'),2)
self.call('off')
self.assertEqual(json.loads(self.store.read_text())['flow_offloading'],'1')
def test_uci_failure_never_claims_success(self):
(self.root/'uci.fail').touch();self.call('set','64',ok=False)
self.assertFalse(self.conf.exists());self.assertFalse((self.root/'rules').exists())
def test_process_restart_reapplies_saved_rule(self):
self.call('set','128');(self.root/'rules').unlink()
self.call('apply');self.assertIn('ttl set 128',(self.root/'rules').read_text())
self.assertIn('TTL=128\nBACKEND=nft',self.call('state').stdout)
def test_default_off_does_not_touch_firewall(self):
self.call('apply');self.call('state')
self.assertFalse((self.root/'rules').exists());self.assertFalse((self.root/'reloads').exists())
def test_parallel_requests_are_serialized(self):
(self.root/'delay').touch()
procs=[subprocess.Popen(['sh',str(ENGINE),'set',v],env=self.env,stdout=subprocess.PIPE,stderr=subprocess.PIPE) for v in ('64','128')]
codes=[]
for p in procs:
out,err=p.communicate(timeout=10);codes.append(p.returncode)
self.assertEqual(sorted(codes),[0,75])
v=self.conf.read_text().strip().split('=')[1]
self.assertIn('ttl set '+v,(self.root/'rules').read_text())
self.call('off');self.assertEqual(json.loads(self.store.read_text())['flow_offloading'],'1')
if __name__=='__main__':unittest.main()
+2 -1
View File
@@ -23,7 +23,7 @@ if [ -n "$miss" ]; then
fi
# Optional inputs decide whether the image can use the modem, Wi-Fi and the GPU at all. Missing ones used to
# pass silently and produce an image that boots and does nothing useful, so say what went in.
for o in /firmware /android-subset /android-gpu-subset /bt-init /keys /cltest /sing-box /xray /hev-socks5-tunnel; do
for o in /firmware /android-subset /android-gpu-subset /bt-init /keys /atd-io /cltest /sing-box /xray /hev-socks5-tunnel; do
[ -e "$o" ] && echo "assemble.sh: + $o" || echo "assemble.sh: - $o (not mounted; the image will be built without it)"
done
@@ -61,6 +61,7 @@ if [ -e /cltest ]; then install -D -m755 /cltest $R/opt/mu300/android/system/bin
if [ -e /bt-init ]; then cp /bt-init $R/opt/mu300/bin/mu300-bt-init; fi
# tools/keys build (static arm64): the buttons (mu300-buttons)
if [ -e /keys ]; then install -m755 /keys $R/opt/mu300/bin/mu300-keys; fi
if [ -e /atd-io ]; then install -m755 /atd-io $R/opt/mu300/bin/mu300-atd-io; fi
# VLESS clients for mu300-vpn: the xray engine (tools/fetch-xray.sh) and sing-box (tools/fetch-sing-box.sh)
if [ -f /sing-box ]; then install -m755 /sing-box $R/opt/mu300/bin/sing-box; fi
if [ -f /xray ]; then install -m755 /xray $R/opt/mu300/bin/xray; fi
+18 -1
View File
@@ -10,6 +10,23 @@ bootpart=boot_$slot
BOOTDEV=$(readlink -f "/dev/block/by-name/$bootpart" 2>/dev/null)
[ -b "$BOOTDEV" ] || for u in /sys/class/block/mmcblk0p*/uevent; do grep -qx "PARTNAME=$bootpart" "$u" && BOOTDEV=/dev/$(basename "$(dirname "$u")"); done
[ -b "$BOOTDEV" ] || exit 0
# --- cpus begin
# The little cluster (FINDINGS 208): a round reads the kernel's whole log, which is work that woke an A76 every few
# seconds of the boot's first minutes. This runs from preinit, before mu300-cpu puts procd's services on the little
# CPUs, so it pins itself (and what it starts): the CPUs of the lowest cpu_capacity, where taskset is there.
little_cpus() {
_lc_min= _lc_list=
for _c in "${MU300_CPUDIR:-/sys/devices/system/cpu}"/cpu[0-9]*; do
_cap=; read -r _cap < "$_c/cpu_capacity" 2>/dev/null
case $_cap in ''|*[!0-9]*) continue ;; esac
if [ -z "$_lc_min" ] || [ "$_cap" -lt "$_lc_min" ]; then _lc_min=$_cap; _lc_list=${_c##*/cpu}
elif [ "$_cap" = "$_lc_min" ]; then _lc_list="$_lc_list,${_c##*/cpu}"; fi
done
echo "$_lc_list"
}
# --- cpus end
_lc=$(little_cpus)
[ -z "$_lc" ] || taskset -pc "$_lc" $$ >/dev/null 2>&1 || true
end=$(( $(cut -d. -f1 /proc/uptime) + ${1:-300} ))
while [ "$(cut -d. -f1 /proc/uptime)" -lt "$end" ]; do
{
@@ -20,7 +37,7 @@ while [ "$(cut -d. -f1 /proc/uptime)" -lt "$end" ]; do
systemctl list-units --no-legend --plain --state=activating,failed 2>/dev/null
[ -f /etc/openwrt_release ] && { echo "--- ps"; ps w 2>/dev/null; echo "--- logread"; logread 2>/dev/null | grep -v PR_CAPBSET | tail -300; echo "--- android logcat"; tail -150 /var/log/android-logcat.txt 2>/dev/null; echo "--- mu300 logs"; tail -40 /tmp/mu300-*.log 2>/dev/null; }
echo "--- dmesg"
dmesg | tail -c 1000000
dmesg -s 1000000 2>/dev/null || dmesg | tail -c 1000000
echo "MU300-PERSIST-END"
} > /run/mu300-early.txt 2>&1
head -c 65536 /dev/zero >> /run/mu300-early.txt
@@ -14,6 +14,16 @@ M=/lib/modules/$(uname -r)
if [ -f "$M/mu300_thermal.ko" ] && ! [ -d /sys/module/mu300_thermal ]; then
insmod "$M/mu300_thermal.ko" || echo 'virtual thermal load failed'
fi
# UMS9620 mainline: let enabled USB/IPA/PCIe interrupts wake a powered-down
# cluster. The module checks the actual SoC and clock gates; it does not disable
# idle states or change system-suspend wake sources. Vendor 5.4 has no module.
for f in "$M/ums9620_lpintc.ko" "$M/extra/ums9620_lpintc.ko"; do
[ -f "$f" ] || continue
if ! [ -d /sys/module/ums9620_lpintc ]; then
insmod "$f" && echo 'loaded ums9620_lpintc' || echo 'FAILED ums9620_lpintc'
fi
break
done
if [ -f "$M/sipc-core.ko" ] && ! [ -e /dev/modem ]; then
for m in sprd_systimer sprd_time_sync sprd_time_sync_cp trusty trusty-pm trusty-log trusty-irq trusty-ipc \
trusty-virtio sprd_shm unisoc-mailbox sprd-sipc-virt-bus sprd_power_manager sipc-core spipe spool \
+25 -38
View File
@@ -257,15 +257,6 @@ v6_off() {
# 实测那一步会把刚起来的 CP 又清一次,白等一整轮 CP 启动(12 s 起)。SFUN=4 之后要等
# 射频真正上来,而不是问一次就走。
radio_on_locked() {
if [ "$DEVICE" = u30air ]; then
"${MU300_RADIO_ALLOWED:-/opt/mu300/bin/mu300-radio-allowed}" "$MU300_SIM_SLOT" || return 7
fi
if [ "$DEVICE" = u30air ] && [ -e /run/mu300-radio-freeze ]; then
[ ! -e /run/mu300/sim-switching ] && [ ! -e /run/mu300/sim-active-unknown ] &&
[ -e /run/mu300/sim-radio-ready ] || return 1
at 'AT+CFUN?' 4 | tr -d '\r' | grep -Eq '^\+CFUN: *1$'
return $?
fi
local i=0 out silent=0 answered=0 urclog=/run/mu300-at/urc/stty_nr0.log
local ready_deadline=$((SECONDS + ${MU300_CFUN_WAIT:-30}))
mark radio-on-enter
@@ -304,7 +295,7 @@ radio_on_locked() {
if [ "$DEVICE" = v50 ] && [ -n "$(uci -q get unisoc_modem.main.v50_card 2>/dev/null || true)" ]; then
/opt/mu300/bin/mu300-v50-sim boot || return 1
fi
if [ "$DEVICE" != u30air ] && [ "$(uci -q get unisoc_modem.main.sim_slots 2>/dev/null || true)" = 2 ]; then
if [ "$(uci -q get unisoc_modem.main.sim_slots 2>/dev/null || true)" = 2 ]; then
/opt/mu300/bin/mu300-dual-radio
local dual_rc=$?
[ "$dual_rc" = 0 ] || return "$dual_rc"
@@ -675,16 +666,6 @@ configure_initial_apn() {
}
up_locked() {
if [ "$DEVICE" = u30air ] && [ -e /run/mu300-radio-freeze ]; then
# The cold-start process needs the RF mutex. Wait outside it, so a
# first dial does not fail and incur netifd's normal retry delay.
local native_end=$((SECONDS + ${MU300_NATIVE_RADIO_WAIT:-40})) boot_slot
until [ -e /run/mu300/sim-radio-ready ] || [ ! -e /run/mu300-radio-freeze ] || [ "$SECONDS" -ge "$native_end" ]; do sleep 1; done
boot_slot=$(cat /run/mu300/sim-slot 2>/dev/null || true)
# A fallback changed this protocol task's card. Let netifd re-evaluate
# its per-SIM APN and teardown owner instead of dialing the old choice.
[ "$boot_slot" = "$MU300_SIM_SLOT" ] || return 1
fi
modem_stack || { echo "no modem stack in this kernel ($(uname -r))" >&2; exit 3; }
rm -f /run/mu300-mobile-data-down /run/mu300-mobile-data-manual-down
tty_setup
@@ -692,16 +673,7 @@ up_locked() {
echo 'SIM absent; waiting for card state event' >&2; return 6
fi
radio_on || return $?
if [ "$DEVICE" = u30air ] && [ "$MU300_SIM_SLOT" = 0 ] && [ ! -e /run/mu300-radio-freeze ] && [ -e /etc/mu300/sim-data-route-2 ]; then
current=$(at 'AT+SPSWDATA?' 4 | tr -d '\r' | sed -n 's/^+SPSWDATA: *\([01]\) *$/\1/p' | head -n1) || current=
if [ "$current" = 1 ]; then
at 'AT+SPSWDATA' 8 | tr -d '\r' | grep -qx OK || return 1
current=$(at 'AT+SPSWDATA?' 4 | tr -d '\r' | sed -n 's/^+SPSWDATA: *\([01]\) *$/\1/p' | head -n1) || current=
[ "$current" != 1 ] || return 1
fi
[ "$current" != 0 ] || rm -f /etc/mu300/sim-data-route-2
fi
if [ "$DEVICE" != u30air ] && [ "$(uci -q get unisoc_modem.main.sim_slots 2>/dev/null || true)" = 2 ]; then
if [ "$(uci -q get unisoc_modem.main.sim_slots 2>/dev/null || true)" = 2 ]; then
# Select the data card once, before activation; never use SMMSWAP to
# implement viewing or data selection. Confirm even an omitted OK.
current=$(at 'AT+SPSWDATA?' 3 | sed -n 's/^+SPSWDATA: *\([01]\).*/\1/p' | head -n1)
@@ -875,7 +847,6 @@ down() {
sim_reset() {
"${MU300_RADIO_ALLOWED:-/opt/mu300/bin/mu300-radio-allowed}" "$MU300_SIM_SLOT" || { echo 'This SIM radio is disabled by the user' >&2; return 1; }
[ ! -e /run/mu300/sim-managed ] || { echo "Native dual-SIM RF is managed; use SIM control or reboot" >&2; return 1; }
tty_setup
at 'AT+SFUN=5' 20; at 'AT+SFUN=3' 10; sleep 2; at 'AT+SFUN=2' 10; at 'AT+SFUN=4' 30
for _ in $(seq 1 30); do at 'AT+CPIN?' | grep -q READY && break; sleep 2; done
@@ -908,6 +879,12 @@ watch_radio_if_off() {
watch() {
local fails=0 context_state want have
# OpenWrt uses ubus events; Ubuntu retains its existing watchdog wait.
watch_events_stop() { :; }
watch_next() { sleep "${MU300_WATCH_INTERVAL:-30}"; }
if [ "${MU300_NETIFD:-0}" = 1 ]; then
. "${MU300_DATA_EVENTS_LIB:-/opt/mu300/lib/data-events.sh}" || return 1
fi
# one watchdog is enough: procd and systemd have both been seen starting a second one
local wlock=/run/mu300-mobile-data-watch.lock wp=
while ! mkdir "$wlock" 2>/dev/null; do
@@ -921,12 +898,26 @@ watch() {
rm -rf "$wlock"
done
echo $$ > "$wlock/pid"
trap 'rm -f "$wlock/pid"; rmdir "$wlock" 2>/dev/null || true' EXIT
# Bash may unwind function locals before EXIT on errexit. Keep cleanup
# state at process scope, and never remove a lock another owner replaced.
watch_state_lock=$wlock
watch_cleanup() {
local owner=
watch_events_stop
[ -n "${watch_state_lock:-}" ] || return 0
[ -r "$watch_state_lock/pid" ] || return 0
IFS= read -r owner < "$watch_state_lock/pid" 2>/dev/null || return 0
[ "$owner" = "$$" ] || return 0
rm -f "$watch_state_lock/pid"
rmdir "$watch_state_lock" 2>/dev/null || true
}
trap watch_cleanup EXIT
trap 'exit 143' TERM
trap 'exit 130' INT
modem_stack || { echo "no modem stack in this kernel ($(uname -r)), not watching" >&2; exit 0; }
if [ "${MU300_NETIFD:-0}" = 1 ]; then watch_events_start || return 1; fi
while :; do
sleep "${MU300_WATCH_INTERVAL:-30}"
watch_next
[ ! -e /run/mu300/sim-switching ] && [ ! -e /run/mu300/sim-active-unknown ] || continue
[ ! -d /run/unisoc-data-sim-switch ] || continue
[ -e /run/mu300-mobile-data-down ] && continue
@@ -1058,11 +1049,7 @@ case "${1:-status}" in
esac
exit $?
fi
[ "$DEVICE" = u30air ] || exit 2
case "$*" in
'/bin/bash /opt/mu300/bin/mu300-sim2-start --cold-start'|'/opt/mu300/bin/mu300-sim-u30 --sequence 0'|'/opt/mu300/bin/mu300-sim-u30 --sequence 1') radio_locked "$@" ;;
*) exit 2 ;;
esac ;;
exit 2 ;;
up) up "${2:-}" ;;
data-priority) data_priority ;;
radio-on)
+3 -4
View File
@@ -1,10 +1,6 @@
#!/bin/sh
# MU300 netifd adapter. No tty opens, RIL handshake changes or USB operations.
export PATH="$PATH:/opt/mu300/bin:/opt/mu300/busybox-bin:/usr/sbin:/sbin"
# The U30 has one active RF stack; a V50-style SPSWDATA-only switch is unsafe.
if [ "$(mu300-device 2>/dev/null)" = u30air ]; then
exec /opt/mu300/bin/mu300-data-sim-u30 "$@"
fi
. "${MU300_SIM_ENV_LIB:-/opt/mu300/bin/mu300-sim-env}"
cfg() { uci -q get "unisoc_modem.main.$1" 2>/dev/null || true; }
wan=$(cfg data_interface); wan=${wan:-wan}
@@ -92,6 +88,9 @@ apply)
case "$permission:$target" in
0:*) ;;
1:1)
[ "$(mu300-device 2>/dev/null)" != u30air ] || {
echo 'Enable the target SIM radio before switching' >&2; exit 1;
}
at_slot "$target" 'AT+CPIN?' | grep -q '^+CPIN: READY' || { echo sim_not_ready >&2; exit 1; }
"${MU300_RADIO_CONTROL:-/opt/mu300/bin/mu300-sim-radio}" --switch-enable 1 1 || exit 1 ;;
*) echo 'Enable the target SIM radio before switching' >&2; exit 1 ;;
@@ -1,39 +1,3 @@
#!/bin/sh
# Native U30 controller adapted to the shared dashboard's zero-based SIM API.
export PATH="$PATH:/opt/mu300/bin:/usr/sbin:/sbin"
[ "$(mu300-device 2>/dev/null)" = u30air ] || exit 1
NATIVE=${MU300_NATIVE_SIM_CMD:-/opt/mu300/bin/mu300-sim-u30}
field() { printf '%s' "$view" | jsonfilter -e "@.$1" 2>/dev/null; }
case ${1:-} in
get)
view=$("$NATIVE" status) || { printf '{"ok":0,"error":"dual_sim_unavailable"}\n'; exit 1; }
actual=$(field active); saved=$(field default); hot=$(field hot)
case "$actual" in 1|2) actual=$((actual-1));; *) actual=null;; esac
case "$saved" in 1|2) saved=$((saved-1));; *) saved=0;; esac
case "$hot" in 0|1) ;; *) hot=0;; esac
ready=false; [ "$(field available)" != 1 ] || ready=true
connected=false; [ "$(field wan_up)" != true ] || connected=true
printf '{"ok":1,"native":true,"ready":%s,"saved_sim":%s,"actual_sim":%s,"hot":%s,"data_connected":%s,"devices":["sipa_eth0","sipa_eth8"],"native_status":%s}\n' "$ready" "$saved" "$actual" "$hot" "$connected" "$view"
;;
apply)
case ${2:-} in
0|1) operation=switch; value=$(( $2+1 ));;
u30-hot-[01]) operation=hot; value=${2##*-};;
u30-default-[01]) operation=default; value=$(( ${2##*-}+1 ));;
*) echo invalid_sim >&2; exit 1;;
esac
mutex=${MU300_SIM_MUTEX:-/run/unisoc-data-sim-switch}
mkdir "$mutex" 2>/dev/null || { echo modem_busy >&2; exit 1; }
echo $$ > "$mutex/pid"
trap 'rm -f "$mutex/pid"; rmdir "$mutex" 2>/dev/null || true' EXIT
trap 'exit 143' INT TERM
[ ! -d /run/unisoc-modem-lock-apply ] || { echo modem_busy >&2; exit 1; }
rc=0; view=$("$NATIVE" "$operation" "$value") || rc=$?
if [ "$rc" != 0 ]; then
reason=$(field error)
printf '%s\n' "${reason:-sim_rollback_failed}" >&2
fi
exit "$rc"
;;
*) exit 2;;
esac
# Compatibility name; use the shared manual data-card transaction.
exec /opt/mu300/bin/mu300-data-sim "$@"
+62 -17
View File
@@ -50,7 +50,14 @@ esac
# mixed): its battery LED, the F50's only one, where green is green and stays out
case $DEVICE in u30air) SIREN="sc27xx:red sc27xx:green sc27xx:blue" ;; *) SIREN="sc27xx:red sc27xx:blue" ;; esac
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)
BOOT_STATE=$STATE/.boot-chase
rd() { local value=; [ -r "$1" ] || return 1; IFS= read -r value < "$1" || :; printf '%s\n' "$value"; }
TIMEOUT=
if [ -r "${MU300_LED_CONF:-/etc/mu300/led.conf}" ]; then
while IFS= read -r line || [ -n "$line" ]; do
case $line in LED_TIMEOUT=*) value=${line#LED_TIMEOUT=}; case $value in ''|*[!0-9]*) ;; *) TIMEOUT=$value ;; esac ;; esac
done < "${MU300_LED_CONF:-/etc/mu300/led.conf}"
fi
TIMEOUT=${TIMEOUT:-$DEFAULT_TIMEOUT}
if [ "$DEVICE" = u30air ]; then
value=$(uci -q get system.mu300_leds.timeout 2>/dev/null)
@@ -62,7 +69,7 @@ cfg() { uci -q get "system.mu300_leds.$1" 2>/dev/null; }
# 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
if [ "$DEVICE" = u30air ] && [ "${1:-}" != siren ] && [ "${1:-}" != boot-worker ]; then
mkdir -p "$STATE" || exit 0
exec 9>"$STATE/.lock"
flock -w 2 9 || exit 0
@@ -83,11 +90,11 @@ external_power() {
KEEP_LIT=0
external_power && KEEP_LIT=1
uptime_s() { cut -d. -f1 "$R/proc/uptime" 2>/dev/null || echo 0; }
uptime_s() { local value=; IFS=" " read -r value _ < "$R/proc/uptime" 2>/dev/null || :; value=${value%%.*}; printf "%s\n" "${value:-0}"; }
awake() {
[ "$KEEP_LIT" != 1 ] || return 0
[ "$TIMEOUT" = 0 ] && return 0
until=$(cat "$STATE/.awake-until" 2>/dev/null) || return 1
until=$(rd "$STATE/.awake-until") || return 1
[ "$(uptime_s)" -lt "${until:-0}" ]
}
vendor_ldo() { # vendor_ldo zte-ldoN: the 5.4 kernel's switch for that LDO, if there
@@ -98,6 +105,13 @@ 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
local requested=$2 group= value maximum level pattern
# Boot owns only the battery RGB. Power events still update the desired
# battery state, but cannot overwrite a frame before the boot handoff.
case $1 in sc27xx:*)
if [ -f "$BOOT_STATE" ]; then
[ "${BOOT_FRAME:-0}" = 1 ] || return 0
fi ;;
esac
if [ "$DEVICE" = u30air ]; then
case $1 in
net_blue|zte-ldo0|keyboard-backlight) group=signal ;;
@@ -108,7 +122,7 @@ write() { # write NAME 0|1: the LED itself
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)
maximum=$(rd "$LEDS/$1/max_brightness")
case $maximum in ''|*[!0-9]*) maximum=255 ;; esac
value=0
if [ "$requested" = 1 ]; then
@@ -120,7 +134,7 @@ write() { # write NAME 0|1: the LED itself
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" ] &&
if [ "${BOOT_FRAME:-0}" != 1 ] && [ "$value" -gt 0 ] && [ "$(rd "$STATE/.battery-breathe")" = "$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.
@@ -133,14 +147,14 @@ write() { # write NAME 0|1: the LED itself
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"
[ "$(rd "$LEDS/$1/repeat")" = -1 ] || echo -1 > "$LEDS/$1/repeat"
[ "$(rd "$LEDS/$1/hw_pattern")" = "$pattern" ] || echo "$pattern" > "$LEDS/$1/hw_pattern"
return 0
fi
fi
echo none > "$LEDS/$1/trigger" 2>/dev/null
echo "$value" > "$LEDS/$1/brightness" 2>/dev/null
if [ "$value" -gt 0 ] && [ "$(cat "$STATE/.battery-blink" 2>/dev/null)" = "$1" ] &&
if [ "$value" -gt 0 ] && [ "$(rd "$STATE/.battery-blink")" = "$1" ] &&
grep -qw timer "$LEDS/$1/trigger"; then
echo timer > "$LEDS/$1/trigger"
echo 750 > "$LEDS/$1/delay_on"
@@ -162,27 +176,29 @@ wifi_band() { # 5 or 2.4: the channel the hotspot runs on, else (it has none ye
show_all() { # every LED as it should be
for f in "$STATE"/*; do
[ -f "$f" ] || continue
write "${f##*/}" "$(cat "$f")"
write "${f##*/}" "$(rd "$f")"
done
}
siren_running() { p=$(cat "$SIREN_PID" 2>/dev/null) && [ -n "$p" ] && kill -0 "$p" 2>/dev/null; }
siren_running() { p=$(rd "$SIREN_PID") && [ -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)
cap=$(rd "$root/sc27xx-fgu/capacity")
case $cap in ''|*[!0-9]*) return 0 ;; esac
[ "$cap" -le 100 ] || return 0
status=$(cat "$root/sc27xx-fgu/status" 2>/dev/null)
status=$(rd "$root/sc27xx-fgu/status")
# 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
# Stock U30 Air: blue below 50%, white from 50%; Full is steady white.
# U30 Air: charging below 10% breathes red, 10..49% blue, then white.
# Discharging keeps its existing colour policy; Full is steady white.
color=sc27xx:green
[ "$cap" -ge 50 ] || color=sc27xx:blue
if [ "$status" = Charging ] && [ "$cap" -lt 10 ]; then color=sc27xx:red; fi
mkdir -p "$STATE"
previous_power=$(cat "$STATE/.external-power" 2>/dev/null)
previous_power=$(rd "$STATE/.external-power")
echo "$KEEP_LIT" > "$STATE/.external-power"
if [ "$previous_power" = 1 ] && [ "$KEEP_LIT" = 0 ] && [ "$TIMEOUT" != 0 ]; then
echo $(( $(uptime_s) + TIMEOUT )) > "$STATE/.awake-until"
@@ -200,6 +216,34 @@ battery() {
}
case "$1 ${2:-}" in
"boot on")
[ "$DEVICE" = u30air ] || exit 0
[ ! -f "$BOOT_STATE" ] || exit 0
siren_running && exit 0
echo $$ > "$BOOT_STATE"
"$0" boot-worker "$$" 9>&- </dev/null >/dev/null 2>&1 & ;;
"boot off")
[ -f "$BOOT_STATE" ] || exit 0
rm -f "$BOOT_STATE"
battery
if awake && ! siren_running; then show_all; fi ;;
"boot-frame "*)
[ "$DEVICE" = u30air ] && [ "$(rd "$BOOT_STATE")" = "${2:-}" ] || exit 1
siren_running && exit 1
case ${3:-} in sc27xx:red|sc27xx:green|sc27xx:blue) ;; *) exit 1 ;; esac
BOOT_FRAME=1
for l in $SIREN; do [ "$l" = "$3" ] || write "$l" 0; done
if awake; then write "$3" 1; else write "$3" 0; fi ;;
"boot-worker "*)
# Each frame takes the same lock as battery/thermal writes. The token
# prevents an old worker from drawing after stop/restart. Never hold
# the lock while sleeping or leave a worker once boot has completed.
while :; do
for l in $SIREN; do
"$0" boot-frame "$2" "$l" || exit 0
"${MU300_BUSYBOX:-/opt/mu300/bin/busybox}" usleep 250000 || exit 1
done
done ;;
"battery "*) battery ;;
"refresh "*) if awake; then show_all; fi ;;
"power on") set_led "$POWER" 1; [ "$TIMEOUT" = 0 ] || { exec 9>&-; exec "$0" wake; } ;;
@@ -225,6 +269,7 @@ case "$1 ${2:-}" in
rm -f "$STATE/.awake-until"
for f in "$STATE"/*; do [ -f "$f" ] && write "${f##*/}" 0; done ;;
"alarm on")
rm -f "$BOOT_STATE"
siren_running && exit 0
mkdir -p "${SIREN_PID%/*}" 2>/dev/null
"$0" siren 9>&- </dev/null >/dev/null 2>&1 &
@@ -242,7 +287,7 @@ case "$1 ${2:-}" in
# The file is written just after the start, so a missing one counts only after the first round.
n=0
while :; do
own=$(cat "$SIREN_PID" 2>/dev/null)
own=$(rd "$SIREN_PID")
if [ -n "$own" ]; then [ "$own" = $$ ] || exit 0
elif [ $n -gt 0 ]; then exit 0; fi
n=$((n + 1))
@@ -255,7 +300,7 @@ case "$1 ${2:-}" in
for l in "$LEDS"/*; do
n=${l##*/}
case $n in mmc*|*backlight*) continue ;; esac
old=$(cat "$l/brightness" 2>/dev/null)
old=$(rd "$l/brightness")
echo "$n"; write "$n" 1; sleep 2; echo "${old:-0}" > "$l/brightness" 2>/dev/null
done ;;
*) sed -n '2,10s/^# \{0,1\}//p' "$0" >&2; exit 2 ;;
File diff suppressed because it is too large. Load diff
@@ -22,7 +22,7 @@ if [ "$previous" = "$device" ]; then
# the selected data SIM, APNs and custom adapter mappings stay untouched.
case $device in
f50) version=f50_dual_version ;;
u30air) version=u30_native_version ;;
u30air) version=u30_dual_version ;;
*) exit 0 ;;
esac
[ "$(uci -q get "unisoc_modem.main.$version")" != 1 ] || exit 0
@@ -42,7 +42,7 @@ fi
elif [ "$slots" = 2 ]; then
printf "set unisoc_modem.main.sim_slots='2'\n"
fi
if [ "$device" = u30air ]; then printf "set unisoc_modem.main.u30_native_version='1'\n"; fi
if [ "$device" = u30air ]; then printf "set unisoc_modem.main.u30_dual_version='1'\n"; fi
if [ "$device" = f50 ]; then printf "set unisoc_modem.main.f50_dual_version='1'\n"; fi
printf "set unisoc_modem.main.platform_defaults='%s'\n" "$device"
printf 'commit unisoc_modem\n'
@@ -1,12 +1,13 @@
#!/bin/sh
# Persistent per-slot RF permission. SIM2 is opt-in; an existing saved SIM2
# data-card choice is also explicit intent and must survive an upgrade.
# Persistent per-slot RF permission. U30 defaults both on; other boards keep
# their SIM2 opt-in default. Explicit saved choices always survive an upgrade.
case ${1:-} in 0|1|--flags) ;; *) exit 2;; esac
policy=${UNISOC_RADIO_POLICY:-/etc/mu300/sim-radio}
if [ -e "$policy" ]; then
flags=$(cat "$policy") || exit 2
else
flags='1 0'
[ "$(mu300-device 2>/dev/null)" != u30air ] || flags='1 1'
[ "$(uci -q get unisoc_modem.main.data_sim 2>/dev/null)" != 1 ] || flags='1 1'
fi
case "$flags" in '0 0'|'0 1'|'1 0'|'1 1') ;; *) exit 2;; esac
@@ -0,0 +1,16 @@
#!/usr/bin/ucode
import { cursor } from 'uci';
import { apply } from 'mu300.service-cpus';
let c=cursor(), action=ARGV[0] || 'get';
let selected=c.get('unisoc_modem','main','services_cpus') || 'little';
if(action=='get') { print(selected+'\n'); exit(0); }
if(!(action in ['apply','little','all']))die('Usage: mu300-service-cpus [get|apply|little|all]\n');
let mode=action=='apply'?selected:action;
let result=apply('',mode);
if(result.ok && action!='apply') {
if(!c.get('unisoc_modem','main'))c.set('unisoc_modem','main','core');
if(!c.set('unisoc_modem','main','services_cpus',mode) || !c.commit('unisoc_modem'))
result={ok:false,error:'Service placement applied but could not be saved'};
}
print(sprintf('%J\n',result));
exit(result.ok?0:1);
@@ -2,9 +2,6 @@
# Source this platform mapping. The standalone plugin never assumes SIPA names.
mu300_sim_env() {
local selected=${1:-} device
if [ -z "$selected" ] && [ "$("${MU300_DEVICE_CMD:-/opt/mu300/bin/mu300-device}" 2>/dev/null)" = u30air ]; then
selected=$(cat /run/mu300/sim-slot 2>/dev/null || true)
fi
[ -n "$selected" ] || selected=$(uci -q get unisoc_modem.main.data_sim 2>/dev/null || true)
selected=${selected:-0}
case "$selected" in 0|1) ;; *) return 1 ;; esac
+3 -11
View File
@@ -50,13 +50,9 @@ if [ "$1" != --locked ]; then
# Release the RF mutex before invoking its existing initialization
# path. Retain the switch gate so no other UI operation can interleave.
# Never invent a second SFUN/SPSWDATA sequence for cold re-enablement.
if [ "$(mu300-device)" = u30air ] && [ -e /run/mu300-radio-freeze ]; then
/bin/bash /opt/mu300/bin/mu300-sim2-warmup --radio-only || exit 1
else
init_rc=0
MU300_SIM_CONTROL=1 /opt/mu300/bin/mobile-data radio-on || init_rc=$?
case "$init_rc" in 0|7) ;; *) exit "$init_rc";; esac
fi
init_rc=0
MU300_SIM_CONTROL=1 /opt/mu300/bin/mobile-data radio-on || init_rc=$?
case "$init_rc" in 0|7) ;; *) exit "$init_rc";; esac
/opt/mu300/bin/mobile-data radio-policy "$slot" "$enabled" || {
echo 'Radio setting saved; target SIM is not ready' >&2; exit 1;
}
@@ -78,10 +74,6 @@ wan=$(uci -q get unisoc_modem.main.data_interface) || wan=wan
case "$wan" in ''|*[!a-zA-Z0-9_]*) exit 2;; esac
availability() { ubus -t 3 call "network.interface.$wan" notify_proto "{\"action\":5,\"available\":$1}" >/dev/null; }
if [ "$slot" = "$own" ] && [ "$enabled" = 0 ]; then availability false; fi
# U30 has one active RF stack. The inactive slot is already RF-off. Changing
# its permission must not turn its CFUN=0 cold baseline into flight mode,
# since the native switch requires that baseline before its SFUN sequence.
if [ "$(mu300-device)" = u30air ] && [ "$slot" != "$own" ]; then exit 0; fi
# Cold boot is RF-off. Do not let this UI preempt nr1's first SMMSWAP
# command with SFUN. Enabling delegates to the original initializer below;
# disabling just retains the cold RF-off state and its saved policy.
+7 -454
View File
@@ -1,457 +1,10 @@
#!/bin/bash
# OpenWrt SIM policy and a bounded, broker-only live switch. Public slots are 1/2.
# U30 Air on OpenWrt only: the cold start and the live switch were validated on that firmware alone; everywhere
# else every command (status included) answers ok:0, and nothing is written.
#
# Nothing a caller passes ever reaches an AT command: the arguments are checked against a fixed list below, and the
# commands are built from the two slot numbers alone. Replies are never logged (CCID, cell, numbers).
set -euo pipefail
export PATH="$PATH:/opt/mu300/busybox-bin"
umask 077
R=/run/mu300
FALLBACK=/etc/mu300-sim-fallback
AT=/opt/mu300/bin/mu300-at
MD=/opt/mu300/bin/mobile-data
DEVICE=/opt/mu300/bin/mu300-device
REBOOT=${MU300_REBOOT_CMD:-reboot}
supported() { [ -e /etc/openwrt_release ] && [ "$("$DEVICE" 2>/dev/null)" = u30air ]; }
supported || { printf '{"ok":0,"supported":0,"error":"Dual SIM control is only for the U30 Air on OpenWrt"}\n'; exit 1; }
SIM_CONFIG_U30=1
. "${MU300_SIM_CONFIG_LIB:-/opt/mu300/lib/sim-config.sh}"
LOCKED=${MU300_SIM_LOCKED:-0}
mkdir -p "$R"
uptime_s() { cut -d' ' -f1 /proc/uptime 2>/dev/null || date +%s; }
active() { cat "$R/sim-slot" 2>/dev/null || echo unknown; }
policy() { sim_cfg_hot; }
main() { [ "$1" = 0 ] && echo /run/mu300-at || echo /run/mu300-at4; }
data() { [ "$1" = 0 ] && echo /run/mu300-at2 || echo /run/mu300-at5; }
bearer() { [ "$1" = 0 ] && echo sipa_eth0 || echo sipa_eth8; }
owner() {
local pid
[ -p "$1/cmd" ] && [ -s "$1/owner/pid" ] || return 1
pid=$(cat "$1/owner/pid")
[[ "$pid" =~ ^[0-9]+$ ]] && kill -0 "$pid" 2>/dev/null
}
available() {
[ -e /run/mu300-radio-freeze ] || return 1
local d
for d in /run/mu300-at /run/mu300-at2 /run/mu300-at4 /run/mu300-at5; do owner "$d" || return 1; done
}
atomic() { local t; t=$(mktemp "$1.XXXXXX"); printf '%s\n' "$2" > "$t"; mv -f "$t" "$1"; }
fail() {
if [ "${LOCKED:-0}" = 1 ]; then
case "$(cat "$R/sim-result" 2>/dev/null || true)" in rolled_back|reboot_required|restarting|no_data|no_data_kept) ;; *) atomic "$R/sim-result" failed;; esac
fi
printf '{"ok":0,"error":"%s"}\n' "$1"; return 1; }
status() {
local slot boot hot can=0 busy=0 result=idle fallback=null phase=idle radio=null wan=null error=null
local check=null left=null word end
slot=$(active); boot=$(sim_cfg_default); hot=$(policy)
case "$slot" in 0|1) slot=$((slot+1));; *) slot=null;; esac
[ ! -e "$R/sim-active-unknown" ] || slot=null
case "$boot" in 0|1) boot=$((boot+1));; *) boot=null;; esac
[ "$hot" = 1 ] || hot=0
if [ "$hot" = 1 ] && available && [ ! -e "$R/sim-switching" ] && [ ! -e "$R/sim-active-unknown" ]; then can=1; fi
# Kernel flock is released on exit, including SIGKILL; a leftover file is harmless. The holder of the lock
# (this process, reporting after its own change) is not "busy" to itself.
if [ "${LOCKED:-0}" != 1 ] && command -v flock >/dev/null; then
(exec 9>"$R/sim-control.lock"; flock -n 9) || busy=1
fi
result=$(cat "$R/sim-result" 2>/dev/null || echo idle)
case "$result" in idle|switching|switched|rolled_back|reboot_required|restarting|failed|no_data|no_data_kept) ;; *) result=idle;; esac
# A switch marker nobody holds the lock for is a switch that was killed: the radio is where it was left.
if [ -e "$R/sim-switching" ] && [ "$busy" = 0 ]; then
slot=null
[ "$result" = restarting ] || result=reboot_required
fi
# The last boot's cold start failed and the settings went back to SIM1 (mu300-sim2-warmup): say why until the
# user chooses again. Reasons are identifiers, never modem output.
if [ -s "$FALLBACK" ]; then
fallback=$(head -c 40 "$FALLBACK" | tr -cd 'a-z0-9_-')
[ -n "$fallback" ] && fallback="\"$fallback\"" || fallback=null
fi
phase=$(cat "$R/sim-phase" 2>/dev/null || echo idle)
case "$phase" in idle|switching|waiting_for_data|rolling_back) ;; *) phase=idle;; esac
[ ! -e "$R/sim-radio-ready" ] || radio=true
if [ "$slot" != null ]; then
observed_wan=$(ubus call network.interface.$sim_wan status 2>/dev/null | tr -d ' \n\t') || observed_wan=
if [ -n "$observed_wan" ]; then
if wan_up; then wan=true; else wan=false; fi
fi
fi
# The boot check of a second card that never had data (mu300-sim2-warmup): "waiting" with the seconds left,
# then confirmed, kept (the connection was off), off (no check) or failed (the device restarts into SIM1).
if [ -s "$R/sim-boot-check" ]; then
read -r word end < "$R/sim-boot-check" || true
case "$word" in
waiting)
check='"waiting"'
case "${end:-}" in ''|*[!0-9]*) ;; *) left=$(( end - $(cut -d. -f1 /proc/uptime 2>/dev/null || echo "$end") )); [ "$left" -gt 0 ] || left=0 ;; esac ;;
confirmed|kept|off|failed) check="\"$word\"" ;;
esac
fi
case "$result" in failed|no_data|no_data_kept|reboot_required|restarting|rolled_back) error="\"$result\"";; esac
[ "$busy" = 0 ] || can=0
printf '{"version":1,"ok":1,"supported":1,"slot1_supported":1,"active":%s,"default":%s,"hot":%s,"available":%s,"busy":%s,"phase":"%s","result":"%s","error":%s,"fallback":%s,"boot_check":%s,"boot_check_left":%s,"capabilities":{"boot_selection":true,"live_switch":true},"radio_ready":%s,"registered":null,"wan_up":%s}\n' \
"$slot" "$boot" "$hot" "$can" "$busy" "$phase" "$result" "$error" "$fallback" "$check" "$left" "$radio" "$wan"
}
# raw DIRECTORY COMMAND: one command through a persistent owner; prints the answer whatever its result code.
# 75: not sent at all (the channel's client lock was busy the whole wait); 1: no owner, or no completed answer.
# MU300_SIM_CONTROL=1 lets these through mu300-at's gate, which keeps every other client off the modem while the
# sequence runs (see run_sequence).
raw() {
local directory=$1 command=$2 seconds=${3:-8} output rc=0
owner "$directory" || return 1
# Do not log replies: CCID, subscriber or cell identifiers never belong in switch logs.
printf '%s %s %s\n' "$(uptime_s)" "$directory" "$command" >> "$R/sim-switch.log"
output=$(MU300_SIM_CONTROL=1 MU300_AT_DAEMON_ONLY=1 MU300_AT_DIR="$directory" MU300_AT_LOCK_WAIT="${MU300_SIM_AT_LOCK_WAIT:-20}" \
MU300_AT_BUDGET=$((seconds + 4)) "$AT" -t "$seconds" "$command" 2>&1) || rc=$?
if [ "$rc" != 0 ]; then
case "$output" in *'mu300-at: busy'*) return 75 ;; esac
return 1
fi
printf '%s\n' "$output" | tr -d '\r'
}
# cmd DIRECTORY COMMAND: raw, and the modem must have said OK
cmd() {
local output rc=0
output=$(raw "$@") || rc=$?
[ "$rc" = 0 ] || return "$rc"
[ "$(printf '%s\n' "$output" | tail -1)" = OK ] || return 1
printf '%s\n' "$output"
}
# (The answer is taken whole before it is looked at. Piped into a reader that stops at its first match - grep -q,
# head - the writer can be left with a closed pipe, and under pipefail that reads as "the modem said no": seen in
# the tests as a switch that rolled back after a radio that had come on.)
check() {
local output
output=$(cmd "$(main "$1")" 'AT+CFUN?') || return 1
grep -Eq "^\+CFUN: *$2$" <<< "$output"
}
ready() {
local output
output=$(cmd "$(main "$1")" 'AT+CPIN?') || return 1
grep -Eq '^\+CPIN: *READY$' <<< "$output"
}
# card SLOT: what the card says of itself: ready, sim-pin, no-sim or unknown. "no-sim" (+CME ERROR: 10) is also
# what a position answers whose SIM power is off: see preflight.
card() {
local output
output=$(raw "$(main "$1")" 'AT+CPIN?') || { echo unknown; return 0; }
if [[ "$output" == *'+CPIN: READY'* ]]; then echo ready
elif [[ "$output" == *'+CPIN: SIM PIN'* || "$output" == *'+CPIN: SIM PUK'* ]]; then echo sim-pin
elif [[ "$output" =~ \+CME\ ERROR:\ (10($|[^0-9])|SIM\ not\ inserted) ]]; then echo no-sim
else echo unknown; fi
}
# preflight TARGET: is there a card to switch to? Asked before the connection in use is touched. The target's SIM
# power is switched on for the question (AT+SPACTCARD=<target>;+SFUN=2, the sequence's own first command): with it
# off the position answers "no card" whatever is in it (measured on our U30 Air, whose second position does that at
# every boot), and SIM power moves no radio - the card in use does not notice (measured, with its data up). A
# card that still does not answer, or is locked, gets its power switched off again and the switch is refused: one
# second, and the WAN never went down. Prints the reason when it refuses.
preflight() {
local target=$1 state attempt
cmd "$(main "$target")" "AT+SPACTCARD=$target;+SFUN=2" 10 >/dev/null || { echo 'The target SIM could not be powered; nothing was changed'; return 1; }
for ((attempt=0; attempt<8; attempt++)); do
state=$(card "$target")
case "$state" in ready) return 0 ;; sim-pin) break ;; esac
sleep 1
done
cmd "$(main "$target")" "AT+SPACTCARD=$target;+SFUN=3" 10 >/dev/null || true
case "$state" in
sim-pin) echo 'The target SIM is locked by its PIN; nothing was changed' ;;
*) echo 'No card answers in the target SIM position; nothing was changed' ;;
esac
return 1
}
# route SLOT: the card the modem says has the packet-data route (0 or 1), asked on SLOT's command channel; nothing
# when this firmware does not answer the question.
route() {
local output
output=$(cmd "$(main "$1")" 'AT+SPSWDATA?') || return 1
sed -n 's/^+SPSWDATA: *\([01]\) *$/\1/p' <<< "$output" | sed -n 1p
}
# sequence TARGET: the radio from the other card to TARGET, the card in use first off, then the other one on.
#
# The order is the measured one (our U30 Air, 7.2.10, 2026-10-13; docs/FINDINGS.md 74). The factory selector
# (VendorTelephonyManager.setProtocolStack) and this script's first version switch the target's radio on while the
# other card is still on, and on the unit the sequence came from that worked in both directions. On ours the
# target's AT+SFUN=4 then never answered (30 s), the card in use lost its radio meanwhile, and the way back could
# not be verified. With the card in use switched off first, every step answered within a second, in both
# directions: it is the cold start's situation, one card on while the other is off, which both units have shown.
#
# Every command names its card (AT+SPACTCARD=<card>;+...): the selection holds for that command line only. A
# line with AT+SPACTCARD=0 alone, which the first version sent "to reset the channel", changes nothing (measured:
# AT+SPACTCARD? keeps answering the channel's own card, and the channel keeps reading it).
# The first command alone may say "not sent" (75): after it the radio has been told something.
sequence() {
local target=$1 old=$((1-$1)) got attempt
"${MU300_RADIO_ALLOWED:-/opt/mu300/bin/mu300-radio-allowed}" "$target" || return 1
cmd "$(main "$old")" "AT+SPACTCARD=$old;+SFUN=5" 20 >/dev/null || return $?
cmd "$(main "$old")" "AT+SPACTCARD=$old;+SFUN=3" 10 >/dev/null || return 1
check "$old" 0 || return 1
# the target: SIM power, the card, the data route, the radio - the cold start's order (mu300-sim2-start)
cmd "$(main "$target")" "AT+SPACTCARD=$target;+SFUN=2" 10 >/dev/null || return 1
for ((attempt=0; attempt<8; attempt++)); do
if ready "$target"; then break; fi
sleep 1
done
ready "$target" || return 1
# the mark that makes a later plain SIM1 dial take the data route back (lib/sim-config.sh)
[ "$target" != 1 ] || sim_route_mark_set || return 1
cmd "$(data "$target")" 'AT+SPSWDATA' >/dev/null || return 1
# Read back which card has the route (after kanoqwq's mu300-data-sim): the other card is a failure; a firmware
# that does not answer the question is not.
got=$(route "$target") || got=
case "$got" in "$target"|'') ;; *) return 1 ;; esac
[ "$target:$got" != 0:0 ] || rm -f "$sim_route_mark"
if [ -x /usr/libexec/unisoc-modem/lock ]; then
(
. /usr/libexec/unisoc-modem/sim-scope.sh
sim_scope "$target" || exit 1
[ ! -e "${UNISOC_REPLAY_MARKER:-/run/unisoc-modem-lock-replay-done}" ] || exit 0
MU300_SIM_CONTROL=1 /usr/libexec/unisoc-modem/lock replay early
) || logger -t mu300-sim 'Early lock replay unconfirmed; late worker remains armed'
fi
cmd "$(data "$target")" 'AT+SFUN=4' 30 >/dev/null || return 1
for ((attempt=0; attempt<15; attempt++)); do
if check "$target" 1; then break; fi
sleep 1
done
check "$target" 1 && check "$old" 0
}
publish() {
atomic "$R/sim-slot" "$1"
: > "$R/sim-managed"
: > "$R/sim-radio-ready"
if [ "$1" = 1 ]; then : > "$R/sim2-radio-ready"; else rm -f "$R/sim2-radio-ready"; fi
rm -f "$R/sim-active-unknown"
# The dashboard caches are shared across cards; identity caches remain per card.
rm -f /run/unisoc-modem/cell.json /run/unisoc-modem/sig.json
}
# wan_up: netifd applies the selected SIM profile and has an address on that exact bearer. A radio-only
# transition does not change the next-boot preference; the boot default
# is saved only once this says yes (MU300_SIM_WAN_WAIT seconds at most, 60 by default), else the switch is undone.
wan_up() { sim_wan_up "$(bearer "$(active)")"; }
wan_wait() {
local deadline=$(( $(date +%s) + ${MU300_SIM_WAN_WAIT:-60} ))
while :; do
wan_up && return 0
[ "$(date +%s)" -lt "$deadline" ] || return 1
sleep 1
done
}
# unknown_radio: nobody can say which card the radio is on (a sequence that stopped half way and could not be
# undone, a controller that was killed). Nothing dials or resets a radio in that state, so it would stay without
# data until somebody restarts the device by hand: the device restarts itself, into the saved boot default, which
# a failed switch never changes. network.wan.sim_restart '0' leaves it at "reboot required" instead.
unknown_radio() {
: > "$R/sim-active-unknown"
if [ "$(sim_cfg_auto_restart)" = 1 ]; then
atomic "$R/sim-result" restarting
logger -t mu300-sim "the radio state is unknown after a SIM switch: restarting" 2>/dev/null || true
( sleep "${MU300_SIM_RESTART_DELAY:-20}"; sync 2>/dev/null; exec $REBOOT ) 9>&- </dev/null >/dev/null 2>&1 &
else
atomic "$R/sim-result" reboot_required
fi
}
SEQPID=
interrupt_switch() {
[ -z "$SEQPID" ] || kill -TERM -- "-$SEQPID" 2>/dev/null || true
exit 143
}
# run_sequence TARGET: the sequence in a process of its own, under mobile-data's radio lock (the dial's radio-on,
# the watchdog and the lock helper's SFUN restart take the same one; 75 when it stays busy) and behind mu300-at's
# gate ($R/sim-sequence: every other AT client is told "busy" meanwhile - SMS, USSD, the panel's terminal).
run_sequence() {
local rc=0
: > "$R/sim-sequence"
MU300_RADIO_LOCK_WAIT="${MU300_SIM_RADIO_LOCK_WAIT:-20}" setsid "$MD" radio-locked "$0" --sequence "$1" &
SEQPID=$!
# A shell waiting on a builtin wait runs TERM traps immediately; a foreground child delays them.
wait "$SEQPID" || rc=$?
SEQPID=
rm -f "$R/sim-sequence"
return "$rc"
}
# roll_back OLD: the one guarded return to the previous card. Only if BOTH brokers still answer: a silent CP must
# not receive blind restart loops. True when the old card is back; false leaves the radio state unknown.
roll_back() {
local old=$1
atomic "$R/sim-phase" rolling_back
if cmd "$(main 0)" 'AT+CFUN?' >/dev/null && cmd "$(main 1)" 'AT+CFUN?' >/dev/null && run_sequence "$old"; then
publish "$old"
atomic "$R/sim-phase" idle
return 0
fi
unknown_radio
return 1
}
wait_wan_down() {
local n st
for ((n=0; n<15; n++)); do
st=$(ubus call network.interface.$sim_wan status 2>/dev/null) || { sleep 1; continue; }
if [[ $(jsonfilter -s "$st" -e '@.up') == false && $(jsonfilter -s "$st" -e '@.pending') != true ]]; then return 0; fi
sleep 1
done
return 1
}
live_switch() {
local target=$1 old had_data=0 rc=0 held_down=0
old=$(active); case "$old" in 0|1) ;; *) fail 'Unknown active SIM; reboot first'; return 1;; esac
[ ! -e "$R/sim-switching" ] || { fail 'Interrupted switch; reboot first'; return 1; }
[ ! -e "$R/sim-active-unknown" ] || { fail 'Unknown radio state; reboot first'; return 1; }
[ "$(policy)" = 1 ] || { fail 'Enable hot switching first'; return 1; }
available || { fail 'Persistent dual-SIM brokers unavailable; reboot first'; return 1; }
[ ! -e /run/mu300-mobile-data.suspend ] || { fail 'Resume the modem before switching'; return 1; }
[ ! -d /run/unisoc-modem-lock-apply ] || { fail 'Network locks are being applied'; return 1; }
if [ "$old" = 1 ] && [ ! -e "${UNISOC_RADIO_POLICY:-/etc/mu300/sim-radio}" ]; then
"${MU300_RADIO_CONTROL:-/opt/mu300/bin/mu300-sim-radio}" --switch-enable 1 1 || return 1
fi
local permission=0
"${MU300_RADIO_ALLOWED:-/opt/mu300/bin/mu300-radio-allowed}" "$target" || permission=$?
case "$permission:$target" in
0:*) ;;
1:1) "${MU300_RADIO_CONTROL:-/opt/mu300/bin/mu300-sim-radio}" --switch-enable 1 1 || return 1 ;;
*) fail 'Enable the target SIM radio before switching'; return 1 ;;
esac
# Decide before the same-slot path too: data deliberately off needs no IP.
if sim_wan_held_down; then held_down=1; fi
if [ "$old" = "$target" ]; then
[ "$held_down" = 1 ] || wan_wait || { atomic "$R/sim-result" no_data; fail 'Active SIM has no data; use default for next-boot selection'; return 1; }
sim_cfg_save_default "$target" || return 1
[ "$held_down" = 1 ] || sim_seen_add "$target" || true
atomic "$R/sim-result" switched
rm -f "$FALLBACK"; status; return 0
fi
# A card whose SIM power is off answers CME ERROR 10 whatever is in its position: the starting RF state is
# validated here, the card itself only once its power is on (preflight).
if ! check "$old" 1; then
# Explicit RF off is a known state, not a failed native switch.
# Keep the original off/old-SIM-power-off/new-SIM-power-on sequence.
! "${MU300_RADIO_ALLOWED:-/opt/mu300/bin/mu300-radio-allowed}" "$old" &&
{ check "$old" 0 || check "$old" 2 || check "$old" 4; } || { fail 'Unexpected radio state; reboot first'; return 1; }
fi
check "$target" 0 || { fail 'Unexpected radio state; reboot first'; return 1; }
local refusal
refusal=$(preflight "$target") || { fail "$refusal"; return 1; }
# Did the card in use have data? It decides what a target without data means, below.
if wan_up; then had_data=1; fi
# Prevent new dial/watch rounds before netifd cancels the old protocol task.
: > "$R/sim-switching"
atomic "$R/sim-result" switching
atomic "$R/sim-phase" switching
# However this ends, the markers go; a result still "switching" then is a switch that was cut short (the
# deadline, a TERM): which card the radio is on is not known.
trap 'atomic "$R/sim-phase" idle; rm -f "$R/sim-sequence" "$R/sim-switching"; if [ "$(cat "$R/sim-result")" = switching ]; then unknown_radio; fi' EXIT
trap interrupt_switch INT TERM
ifdown "$sim_wan" || { atomic "$R/sim-result" failed; fail 'Cannot stop WAN'; return 1; }
if ! wait_wan_down; then
atomic "$R/sim-result" failed
rm -f "$R/sim-switching"
[ "$held_down" = 1 ] || ifup "$sim_wan" || true
fail 'data_disconnect_failed'; return 1
fi
# Serialize the whole protocol-stack transaction against radio-on and manual resets.
run_sequence "$target" || rc=$?
if [ "$rc" = 75 ]; then
# nothing was sent: the radio lock or the AT channel stayed busy. The previous card is as it was.
atomic "$R/sim-result" failed
rm -f "$R/sim-switching"
[ "$held_down" = 1 ] || ifup "$sim_wan" || true
fail 'The modem is busy; nothing was changed, try again'; return 1
fi
if [ "$rc" != 0 ]; then
if roll_back "$old"; then
atomic "$R/sim-result" rolled_back
rm -f "$R/sim-switching"
if [ "$held_down" != 1 ]; then
ifup "$sim_wan" || { fail 'Previous SIM restored but WAN could not be started'; return 1; }
fi
fail 'Switch failed; previous SIM restored'; return 1
fi
fail 'Switch failed; radio state unknown, reboot required'; return 1
fi
# The target card is up: let netifd dial it, and keep the boot default where it was until the bearer is
# there. The published slot is this boot's; the saved one is tomorrow's.
publish "$target"
rm -f "$R/sim-switching"
atomic "$R/sim-phase" waiting_for_data
if [ "$held_down" = 1 ]; then
sim_cfg_save_default "$target" || { atomic "$R/sim-result" failed; fail storage_failed; return 1; }
atomic "$R/sim-result" switched
atomic "$R/sim-phase" idle
status; return 0
fi
if ifup "$sim_wan" && wan_wait; then
if ! sim_cfg_save_default "$target"; then
atomic "$R/sim-result" failed
fail 'SIM switched but the boot default could not be saved'; return 1
fi
sim_seen_add "$target" || true
rm -f "$FALLBACK"
atomic "$R/sim-result" switched
atomic "$R/sim-phase" idle
# Existing watcher reloads its slot itself; never restart AT owners or the whole mu300-post service.
status; return 0
fi
# No bearer on the target within the time. When the previous card had data, back to it, the boot default
# untouched. When it had none either (a first card without a data plan, a boot onto a card with no service),
# going back restores nothing and undoes what the user asked for: the target stays, netifd keeps dialling it,
# and the boot default is still not saved - "use at next boot" is the user's to press.
if [ "$had_data" = 0 ]; then
atomic "$R/sim-result" no_data_kept
atomic "$R/sim-phase" idle
fail 'Target SIM has no data yet and the previous SIM had none either; staying on the target, boot default unchanged'; return 1
fi
: > "$R/sim-switching"
ifdown "$sim_wan" || true
if roll_back "$old"; then
atomic "$R/sim-result" no_data
rm -f "$R/sim-switching" /run/mu300-mobile-data-down
ifup "$sim_wan" || { fail 'Target SIM got no data; previous SIM restored but WAN could not be started'; return 1; }
fail 'Target SIM got no data within the time; previous SIM restored'; return 1
fi
fail 'Target SIM got no data and the previous one could not be restored; reboot required'; return 1
}
#!/bin/sh
# Legacy CLI spelling; all operations use the shared manual SIM controller.
case ${1:-status} in
status) status; exit 0;;
--sequence)
# Only the parent holding BOTH locks may enter this internal operation.
[[ ${2:-} =~ ^[01]$ ]] && [ -e "$R/sim-switching" ] &&
[ "$(readlink /run/mu300-radio-on.owner 2>/dev/null)" = "$PPID" ] || exit 2
sequence "$2"; exit $?;;
default|hot|switch) ;;
*) fail 'Usage: mu300-sim status | default 1|2 | hot 0|1 | switch 1|2'; exit 2;;
esac
[ "$#" = 2 ] || { fail 'Exactly one value is required'; exit 2; }
case $1:$2 in default:1|default:2|switch:1|switch:2|hot:0|hot:1) ;; *) fail 'Invalid SIM setting'; exit 2;; esac
command -v flock >/dev/null || { fail 'flock is required for SIM control'; exit 1; }
exec 9>"$R/sim-control.lock"
flock -n 9 || { fail 'SIM control is busy'; exit 1; }
LOCKED=1
case $1 in
# A choice of the user's ends the last fallback's notice: the next boot tries what was chosen.
default) sim_cfg_save_default "$(( $2-1 ))"; rm -f "$FALLBACK"; status;;
hot) sim_cfg_save_hot "$2"; rm -f "$FALLBACK"; status;;
status) exec /opt/mu300/bin/mu300-data-sim get ;;
active) cat /run/mu300-data-sim-actual ;;
switch)
# The whole operation is bounded: switch (about 15 s of AT), the wait for a bearer (60 s), one rollback
# (15 s) and two dials fit in 300 s; past it the switch is ended and the radio state declared unknown.
# The same guard watches this process: killed outright (SIGKILL, out of memory) it can clean nothing up -
# the markers stay, or the radio is left on a card nobody confirmed and nobody will switch back from. A
# result still "switching" with this process gone is that case: the guard clears the markers and declares
# the radio unknown, as this process's own exit would have.
( trap 'kill "$sleeper" 2>/dev/null || true; exit 0' TERM INT
end=$(( $(date +%s) + ${MU300_SIM_DEADLINE:-300} ))
while kill -0 "$$" 2>/dev/null && [ "$(date +%s)" -lt "$end" ]; do sleep 2 & sleeper=$!; wait "$sleeper"; done
if kill -0 "$$" 2>/dev/null; then kill -TERM "$$" 2>/dev/null
elif [ "$(cat "$R/sim-result" 2>/dev/null || true)" = switching ]; then
rm -f "$R/sim-sequence" "$R/sim-switching"; atomic "$R/sim-phase" idle; unknown_radio
fi
) 9>&- </dev/null >/dev/null 2>&1 &
deadline=$!
rc=0; live_switch "$(( $2-1 ))" || rc=$?
kill "$deadline" 2>/dev/null || true
wait "$deadline" 2>/dev/null || true
exit "$rc";;
case ${2:-} in 1) target=0;; 2) target=1;; *) exit 2;; esac
exec /opt/mu300/bin/mu300-data-sim apply "$target" ;;
*) echo 'Legacy automatic SIM policy removed; use SIM management and radio controls' >&2; exit 2;;
esac
@@ -1,172 +0,0 @@
#!/bin/bash
# Native selected-SIM cold-start sequence verified on this U30 Air firmware; once per boot.
# Run once during Linux boot, through: mobile-data radio-locked /path/to/this/script --cold-start
# Existing nr0/nr1/nr2 and nr3/nr4/nr5 owners must already be running; this opens no modem device.
#
# What it leaves for its caller (mu300-sim2-warmup), all under /run/mu300:
# sim2-cold-start.log every command sent and why it stopped; never a reply (no CCID, no cell, no number)
# sim2-cold-start.reason one word when it stops before the radio is up: no-sim, sim-pin, sim-not-ready,
# wrong-card, not-cold, modem-silent, modem-refused, data-route, no-radio
# sim2-cold-start.sent the radio has been told something: a failure after it is not undone within this boot
set -euo pipefail
export PATH="$PATH:/opt/mu300/busybox-bin"
umask 077 # the logs and markers under /run/mu300 are root's alone
DEVICE=${MU300_DEVICE_CMD:-/opt/mu300/bin/mu300-device}
[ -e /etc/openwrt_release ] && [ "$("$DEVICE" 2>/dev/null)" = u30air ] || {
echo 'Native SIM startup requires U30 Air on OpenWrt' >&2
exit 1
}
[[ ${1:-} == --cold-start ]] || { echo 'Requires an explicitly prepared cold-start boot.' >&2; exit 2; }
[[ -e /run/mu300-radio-freeze ]] || { echo 'Automatic radio bring-up must be inhibited before cold-start.' >&2; exit 2; }
[[ ! -e /run/mu300/charging-boot ]] || exit 0
SLOT=${MU300_SIM_SLOT:-$(cat /run/mu300/sim-slot 2>/dev/null || echo 1)}
case "$SLOT" in 0|1) ;; *) exit 2;; esac
# Called under the RF mutex: recheck after the warm-up's broker wait, before
# the first handshake or any power command. 7 is user-disabled, not failure.
"${MU300_RADIO_ALLOWED:-/opt/mu300/bin/mu300-radio-allowed}" "$SLOT" || exit 7
SIM_CONFIG_U30=1
. "${MU300_SIM_CONFIG_LIB:-/opt/mu300/lib/sim-config.sh}"
LOG=/run/mu300/sim2-cold-start.log
REASON=/run/mu300/sim2-cold-start.reason
mkdir -p /run/mu300
say() { printf '%s %s\n' "$(cut -d' ' -f1 /proc/uptime 2>/dev/null || date +%s)" "$*" >> "$LOG"; }
# stop REASON TEXT [RC]: the word for the page, the line for the log
stop() { printf '%s\n' "$1" > "$REASON"; say "$2"; exit "${3:-1}"; }
trap 'result=$?; say "EXIT rc=$result; no further radio commands will be sent"' EXIT
at() {
local slot=$1 command=$2 seconds=${3:-6} directory
case "$slot" in main0) directory=/run/mu300-at ;; main1) directory=/run/mu300-at4 ;; data0) directory=/run/mu300-at2 ;; data1) directory=/run/mu300-at5 ;; *) return 2 ;; esac
# mu300-at has a direct-device fallback: never allow this probe to take it.
[[ -p "$directory/cmd" && -s "$directory/owner/pid" ]] || return 2
local owner
owner=$(cat "$directory/owner/pid")
[[ "$owner" =~ ^[0-9]+$ ]] && kill -0 "$owner" 2>/dev/null || return 2
say "TX $slot $command"
MU300_SIM_CONTROL=1 MU300_AT_DAEMON_ONLY=1 MU300_AT_DIR="$directory" /opt/mu300/bin/mu300-at -t "$seconds" "$command"
}
expect_ok() {
local output
output=$(at "$@") || { say "FAILED $1 $2 (no completed response)"; return 1; }
[[ $(printf '%s\n' "$output" | tr -d '\r' | tail -n 1) == OK ]] || { say "FAILED $1 $2 (modem rejected command)"; return 1; }
}
[[ ! -e /run/mu300/sim2-cold-start.attempted ]] || { say 'Refusing a second attempt in this boot'; exit 2; }
: > /run/mu300/sim2-cold-start.attempted
rm -f "$REASON"
for directory in /run/mu300-at /run/mu300-at2 /run/mu300-at4 /run/mu300-at5; do
[[ -p "$directory/cmd" ]] || stop modem-silent "Missing broker $directory" 2
done
# Wait for actual CP output, not merely a FIFO created before open_tty completes.
for ((attempt=0; attempt<60; attempt++)); do
[[ -s /run/mu300-at/urc/stty_nr0.log ]] && break
sleep 1
done
[[ -s /run/mu300-at/urc/stty_nr0.log ]] || stop modem-silent 'No CP unsolicited output; refusing to send bring-up commands'
# Verified Android SIM2-primary handshake: nr1, SMMSWAP=0. SMMSWAP=1 is not a slot selector.
expect_ok main0 'AT+SMMSWAP=0' || stop modem-refused 'The RIL handshake was not taken'
: > /run/mu300-ril-handshake
for slot in main0 main1; do
response=$(at "$slot" 'AT+CFUN?') || stop modem-silent "$slot does not answer"
[[ "$response" == *'+CFUN: 0'* ]] || stop not-cold "$slot was already active; this is not the required cold baseline" 2
done
# The card. What it is not is told apart, for the page and the log (the answer itself is never logged):
# +CPIN: SIM PIN / SIM PUK locked; nothing here ever enters a PIN
# +CME ERROR: 10 no card - or a position whose SIM power is off. Measured on our U30 Air (7.2.10,
# 2026-10-13): its second position answers exactly this at every cold boot, and
# READY, with a card identity of its own, one second after its SIM power is switched
# on. (On the unit the sequence came from it answered READY at once; the modem
# seems to power at boot the cards Android had in use.) So that answer is not
# believed before the power has been on: AT+SPACTCARD=<card>;+SFUN=2, the live
# switch's own first command. It moves no radio, and the other card does not
# notice it (measured, with SIM1's data up). When the card still does not answer,
# the power goes off again (SFUN=3): the position is left as it was found.
# ask_card TRIES: sets card to ready, sim-pin, no-sim or sim-not-ready; a just-powered card may need a moment
card=sim-not-ready
ask_card() {
local attempt
for ((attempt=0; attempt<$1; attempt++)); do
response=$(at main$SLOT 'AT+CPIN?' | tr -d '\r') || stop modem-silent "SIM$((SLOT+1)): no answer to the card query"
if [[ "$response" == *'+CPIN: READY'* ]]; then card=ready; return 0
elif [[ "$response" == *'+CPIN: SIM PIN'* || "$response" == *'+CPIN: SIM PUK'* ]]; then card=sim-pin; return 0
elif [[ "$response" =~ \+CME\ ERROR:\ (10($|[^0-9])|SIM\ not\ inserted) ]]; then card=no-sim
else card=sim-not-ready; fi
sleep 1
done
}
powered=0
# give_up REASON TEXT: stop, with the SIM power this script switched on switched off again
give_up() {
if [[ $powered == 1 ]]; then at main$SLOT "AT+SPACTCARD=$SLOT;+SFUN=3" 10 >/dev/null 2>&1 || true; fi
stop "$@"
}
ask_card 2
if [[ $card == no-sim || $card == sim-not-ready ]]; then
expect_ok main$SLOT "AT+SPACTCARD=$SLOT;+SFUN=2" 10 || stop modem-refused "SIM$((SLOT+1)): its SIM power could not be switched on"
powered=1
say "SIM$((SLOT+1)): SIM power switched on"
ask_card 10
fi
case $card in
ready) ;;
sim-pin) give_up sim-pin "SIM$((SLOT+1)) is locked by its PIN or PUK" ;;
no-sim) give_up no-sim "SIM$((SLOT+1)): no card answers in this position, with its SIM power on" ;;
*) give_up sim-not-ready "SIM$((SLOT+1)) is not ready" ;;
esac
response=$(at main$SLOT 'AT+CCID') || give_up modem-silent "SIM$((SLOT+1)): no answer to the identity query"
identity=$(printf '%s\n' "$response" | sed -n 's/^+CCID: *//p' | tr -d '\r" ')
[[ -n "$identity" && ( -z ${MU300_EXPECT_CCID:-} || "$identity" == "$MU300_EXPECT_CCID" ) ]] ||
give_up wrong-card "SIM$((SLOT+1)) identity did not match the recorded card"
# The work modes (network mode per card) are the modem's own, kept: read, and written back as they are, so a mode
# the user locked on the Locks page is not replaced by this start (as kanoqwq's mu300-dual-radio does). Only when
# the modem does not say is it the pair this firmware's RIL sends, 134,134 (s_modemConfig=7: buildWorkModeCmd
# does NOT append the primary SIM argument used by mode 6).
modes=134,134
response=$(at main0 'AT+SPTESTMODE?' | tr -d '\r') || response=
pair=$(sed -n 's/^+SPTESTMODE: *\([0-9][0-9]*\), *\([0-9][0-9]*\).*/\1,\2/p' <<< "$response" | sed -n 1p)
if [[ "$pair" =~ ^[0-9]{1,3},[0-9]{1,3}$ ]]; then modes=$pair; say "work modes kept ($modes)"
else say "work modes not readable; using $modes"; fi
# Native-RIL-derived sequence validated by cold-start registration and data traffic on this device.
# From here on the radio has been told something: a failure past this marker is not undone within this boot
# (mu300-sim2-warmup falls back to SIM1 in this boot only when nothing was sent).
: > /run/mu300/sim2-cold-start.sent
# the data route goes to the second card: the mark that makes a later SIM1 dial put it back (sim-config.sh)
[[ "$SLOT" != 1 ]] || sim_route_mark_set || stop modem-refused 'Cannot record the data route; not giving it to SIM2'
expect_ok data$SLOT "AT+SPTESTMODEM=$modes" || stop modem-refused 'The work modes were refused'
expect_ok data$SLOT 'AT+SPSWDATA' || stop modem-refused 'The data route was refused'
# Read back which card has the data route (after kanoqwq's mu300-dual-radio). Another card than the one asked for
# is a failure; a firmware that does not answer the question is not.
response=$(at main$SLOT 'AT+SPSWDATA?' | tr -d '\r') || response=
route=$(sed -n 's/^+SPSWDATA: *\([01]\) *$/\1/p' <<< "$response" | sed -n 1p)
case "$route" in
"$SLOT") say "data route read back: SIM$((SLOT+1))" ;;
0|1) stop data-route "the data route is on SIM$((route+1)), not on SIM$((SLOT+1))" ;;
*) say 'data route read-back not available on this firmware' ;;
esac
[[ "$SLOT:$route" != 0:0 ]] || rm -f "$sim_route_mark"
if [ -x /usr/libexec/unisoc-modem/lock ]; then
(
. /usr/libexec/unisoc-modem/sim-scope.sh
sim_scope "$SLOT" || exit 1
[ ! -e "${UNISOC_REPLAY_MARKER:-/run/unisoc-modem-lock-replay-done}" ] || exit 0
MU300_SIM_CONTROL=1 /usr/libexec/unisoc-modem/lock replay early
) || logger -t mu300-sim 'Early lock replay unconfirmed; late worker remains armed'
fi
expect_ok data$SLOT 'AT+SFUN=4' 20 || stop no-radio "SIM$((SLOT+1)): the radio-on command was refused"
for ((attempt=0; attempt<15; attempt++)); do
response=$(at main$SLOT 'AT+CFUN?') || stop no-radio "SIM$((SLOT+1)) stopped answering"
if [[ "$response" == *'+CFUN: 1'* ]]; then break; fi
sleep 1
done
[[ "$response" == *'+CFUN: 1'* ]] || stop no-radio "SIM$((SLOT+1)) did not reach CFUN=1"
# CFUN=1 is the radio ready, for either card, exactly as the SIM1 path marks it: no service on a card does not
# invalidate its RF bring-up, and registration is netifd's to wait for and retry (a slow registration used to
# fail this gate and leave the whole boot without WAN).
: > /run/mu300/sim-radio-ready
if [[ "$SLOT" == 0 ]]; then
say 'SIM1 native RF ready; data registration belongs to netifd'
exit 0
fi
: > /run/mu300/sim2-radio-ready
say 'SIM2 native RF ready (CFUN=1); registration and data attachment belong to netifd on sipa_eth8'
exit 0
@@ -1,160 +0,0 @@
#!/bin/bash
# One native bring-up of the selected card per Linux boot; all modem I/O stays in persistent brokers.
# procd instance of init.d/mu300-atd's dual-SIM path. Three things, in this order:
#
# 1. The cold start (mu300-sim2-start). When the radio is up the boot is confirmed: /etc/mu300-sim-pending goes.
# 2. When the cold start cannot be done, the settings go back to SIM1 without live switching and the reason is
# kept in /etc/mu300-sim-fallback for the Dual SIM page. Then this boot is made a SIM1 boot:
# - nothing was sent to the radio yet (no card, a PIN, the channels never came up): the pin, the freeze and the
# markers go and the ordinary SIM1 warm-up runs, through the owner of nr1 that is already there; without one,
# the AT service starts over as the ordinary SIM1 service (nothing holds a channel then).
# - the radio had been told to start the other card: that is not undone in a running modem, so the device
# restarts once, into a plain SIM1 boot (the settings are SIM1's by then; it cannot repeat).
# 3. The second card's first data. A SIM2 that has never had mobile data under Linux gets a time to get it
# (network.wan.sim_data_wait, 300 s; 0: no check). With data it is remembered (/etc/mu300/sim-data-seen) and
# never checked again: an outage is not the card's failure. Without, the choice is given up as in 2 (reason
# no-data) and the device restarts into SIM1 - a card chosen from far away that turns out to have no service
# must not keep the device off the network until somebody walks up to it. Whether SIM1 has data is not asked:
# a user whose SIM1 has none is at the device and reads the reason on the page.
set -euo pipefail
export PATH="$PATH:/opt/mu300/busybox-bin"
umask 077 # the logs and markers under /run/mu300 are root's alone
DEVICE=${MU300_DEVICE_CMD:-/opt/mu300/bin/mu300-device}
[ -e /etc/openwrt_release ] && [ "$("$DEVICE" 2>/dev/null)" = u30air ] || {
echo 'Native SIM startup requires U30 Air on OpenWrt' >&2
exit 1
}
PENDING=/etc/mu300-sim-pending
FALLBACK=/etc/mu300-sim-fallback
CHECK=/run/mu300/sim-boot-check
MD=/opt/mu300/bin/mobile-data
ATD_INIT=${MU300_ATD_INIT:-/etc/init.d/mu300-atd}
REBOOT=${MU300_REBOOT_CMD:-reboot}
SIM_CONFIG_U30=1
. "${MU300_SIM_CONFIG_LIB:-/opt/mu300/lib/sim-config.sh}"
# Preserve the charging-only boot's promise to leave both radios off (the pending marker stays for the real boot).
[[ ! -e /run/mu300/charging-boot ]] || exit 0
SLOT=$(cat /run/mu300/sim-slot 2>/dev/null || echo 1)
case "$SLOT" in 0|1) ;; *) SLOT=1 ;; esac
"${MU300_RADIO_ALLOWED:-/opt/mu300/bin/mu300-radio-allowed}" "$SLOT" || exit 0
say() { logger -t mu300-sim "$*" 2>/dev/null || true; }
# A second run in one boot is the AT service restarted by hand: the owners were closed and opened again, and the
# cold start cannot be repeated. Nothing is concluded from it and no setting is changed.
if [[ -e /run/mu300/sim2-cold-start.attempted ]]; then
: > /run/mu300/sim-active-unknown
say "the AT service was restarted in a dual-SIM boot: the radio state is unknown, reboot"
exit 1
fi
MU300_EXPECT_CCID=$(cat /etc/mu300/sim$((SLOT+1))-iccid 2>/dev/null || true)
export MU300_EXPECT_CCID
atomic() { local t; t=$(mktemp "$1.XXXXXX") && printf '%s\n' "$2" > "$t" && mv -f "$t" "$1"; }
uptime_s() { cut -d. -f1 /proc/uptime 2>/dev/null || date +%s; }
broker_ready() {
local directory=$1 owner
[[ -p "$directory/cmd" && -s "$directory/owner/pid" ]] || return 1
owner=$(cat "$directory/owner/pid")
[[ "$owner" =~ ^[0-9]+$ ]] && kill -0 "$owner" 2>/dev/null
}
# settings_to_sim1 REASON: SIM1 without live switching from the next boot on, the reason for the page. The pending
# marker goes only when both settings were written: left there, it makes the next boot a SIM1 boot all the same.
settings_to_sim1() {
local saved=1
atomic "$FALLBACK" "$1" || true
sim_cfg_save_default 0 || saved=0
sim_cfg_save_hot 0 || saved=0
[[ $saved == 0 ]] || rm -f "$PENDING"
}
# restart_for_sim1 WHY: the one restart into a plain SIM1 boot. Not before the boot has been marked good (S99 and
# 30 s: mu300-next-boot --rearm), so that it is never counted as a failed boot; nothing dials meanwhile.
restart_for_sim1() {
: > /run/mu300/sim-active-unknown
if [[ "$(sim_cfg_auto_restart)" != 1 ]]; then
say "$1: reboot for SIM1 (network.wan.sim_restart is 0: not restarting by itself)"
exit 1
fi
say "$1: restarting into SIM1"
while [[ -r /proc/uptime && $(uptime_s) -lt ${MU300_SIM_REBOOT_AFTER:-120} ]]; do sleep 5; done
sync 2>/dev/null || true
exec $REBOOT
}
fallback() { # fallback REASON: see 2. above
local reason=$1
settings_to_sim1 "$reason"
say "SIM$((SLOT+1)) cold start failed ($reason): SIM1 without live switching from now on"
if [[ -e /run/mu300/sim2-cold-start.sent ]]; then
restart_for_sim1 "the radio was already told to start SIM$((SLOT+1))"
fi
# Nothing reached the radio: this boot can still be an ordinary SIM1 boot. The pinned slot becomes 0, the
# freeze and the managed marker go; sim-fallback-boot keeps init.d/mu300-atd on the SIM1 path for this boot
# whatever the settings say.
: > /run/mu300/sim-fallback-boot
atomic /run/mu300/sim-slot 0 || printf '0\n' > /run/mu300/sim-slot
rm -f /run/mu300/sim-managed /run/mu300-radio-freeze /run/mu300/sim2-radio-ready /run/mu300/sim-active-unknown
if broker_ready /run/mu300-at; then
# a data owner that died left its fifo behind: without it the dial goes through nr1
broker_ready /run/mu300-at2 || rm -f /run/mu300-at2/cmd
say "nothing was sent to the radio: starting SIM1 in this boot"
exec "$MD" radio-on
fi
say "nothing was sent to the radio and nr1 has no owner: the AT service starts over for SIM1"
setsid "$ATD_INIT" restart </dev/null >/dev/null 2>&1 &
exit 1
}
for ((attempt=0; attempt<90; attempt++)); do
ready=1
for directory in /run/mu300-at /run/mu300-at2 /run/mu300-at4 /run/mu300-at5; do
broker_ready "$directory" || ready=0
done
[[ $ready == 1 ]] && break
sleep 1
done
[[ $ready == 1 ]] || fallback brokers-missing
# (the radio lock is waited for: netifd's first dial takes it for a moment at about the same time, only to find
# the radio not ready, and "busy" here would be a cold start that never ran)
start_rc=0
MU300_RADIO_LOCK_WAIT=30 "$MD" radio-locked /bin/bash /opt/mu300/bin/mu300-sim2-start --cold-start || start_rc=$?
if [[ $start_rc == 7 ]]; then exit 0; fi
if [[ $start_rc != 0 ]]; then
reason=$(head -c 40 /run/mu300/sim2-cold-start.reason 2>/dev/null | tr -cd 'a-z0-9-')
fallback "${reason:-cold-start-failed}"
fi
rm -f "$PENDING" /run/mu300/sim-active-unknown /run/unisoc-modem-early-hook-pending
[ "${1:-}" != --radio-only ] || exit 0
# 3. the second card's first data
[[ "$SLOT" == 1 ]] || exit 0
if sim_seen 1; then atomic "$CHECK" confirmed; exit 0; fi
wait=$(sim_cfg_data_wait)
if [[ "$wait" == 0 ]]; then atomic "$CHECK" off; exit 0; fi
end=$(( $(uptime_s) + wait ))
atomic "$CHECK" "waiting $end"
while :; do
if ! "${MU300_RADIO_ALLOWED:-/opt/mu300/bin/mu300-radio-allowed}" "$SLOT"; then
atomic "$CHECK" kept
say "SIM$((SLOT+1)) RF disabled by user: no first-data failure verdict"
exit 0
fi
if sim_wan_up sipa_eth8; then
sim_seen_add 1 || true
atomic "$CHECK" confirmed
say "SIM2 has mobile data: remembered, and not checked again"
exit 0
fi
# the user moved on: another card now (a live switch), or SIM1 chosen for the next boot
[[ "$(cat /run/mu300/sim-slot 2>/dev/null)" == 1 && "$(sim_cfg_default 2>/dev/null)" == 1 ]] || {
atomic "$CHECK" off; exit 0; }
[[ $(uptime_s) -lt $end ]] || break
sleep 2
done
# No verdict on a card whose data nobody was trying to bring up: taken down by hand, switched off in the settings,
# suspended by mu300-power, or in the middle of a live switch.
if ! "${MU300_RADIO_ALLOWED:-/opt/mu300/bin/mu300-radio-allowed}" "$SLOT" ||
sim_wan_held_down || [[ -s /run/mu300-mobile-data.suspend || -e /run/mu300/sim-switching ]] ||
[[ "$(uci -q get network.$sim_wan.auto 2>/dev/null || true)" == 0 || "$(uci -q get network.$sim_wan.disabled 2>/dev/null || true)" == 1 ]]; then
atomic "$CHECK" kept
say "SIM2 has no mobile data, but the connection was off: the choice is kept"
exit 0
fi
atomic "$CHECK" failed
settings_to_sim1 no-data
restart_for_sim1 "SIM2 got no mobile data within $wait s of being chosen"
+37 -9
View File
@@ -26,6 +26,9 @@ ATDIR=${MU300_AT_DIR:-/run/mu300-at}
URCDIR=$ATDIR/urc
POLL=${MU300_SMS_POLL:-5}
SYNC_INTERVAL=${MU300_SMS_SYNC_INTERVAL:-300}
# Zero/negative historically requested a sync on every POLL; do not turn that
# into a busy loop when events replace the periodic sleep.
[ "$SYNC_INTERVAL" -gt 0 ] 2>/dev/null || SYNC_INTERVAL=$POLL
SMS=${MU300_SMS_BIN:-$(command -v mu300-sms 2>/dev/null || echo /opt/mu300/bin/mu300-sms)}
DIRECT_FLAG=${MU300_SMS_DIRECT_FLAG:-/run/mu300-sms-direct}
SPOOL=$POOL/incoming
@@ -58,7 +61,17 @@ while ! mkdir "$LOCK" 2>/dev/null; do
rm -rf "$LOCK"
done
echo $$ > "$LOCK/pid"
trap '[ "$(cat "$LOCK/pid" 2>/dev/null)" = $$ ] && rm -rf "$LOCK"; exit 0' INT TERM
. "${MU300_SMS_EVENTS_LIB:-${0%/*}/../lib/sms-events.sh}" || exit 1
# The service chooses its platform transport explicitly, never by availability.
SMS_TRANSPORT=${MU300_SMS_TRANSPORT:-urc-log}
case "$SMS_TRANSPORT" in ubus|urc-log) ;; *) echo 'mu300-smsd: invalid platform transport' >&2; exit 1 ;; esac
release_sms() {
sms_events_stop
[ "$(cat "$LOCK/pid" 2>/dev/null)" != $$ ] || rm -rf "$LOCK"
}
trap release_sms EXIT
trap 'exit 0' INT TERM
# mu300-atd owns the AT channel; until its command fifo exists nothing can be asked at all
n=0
@@ -130,10 +143,24 @@ signature() {
}
last=$(signature)
elapsed=0
sms_clock; sync_due=$((SMS_NOW + SYNC_INTERVAL))
sms_event= spool_failures=0 sms_first=1
[ "$SMS_TRANSPORT" != ubus ] || sms_events_start || exit 1
echo "mu300-smsd: pooling into $POOL (poll ${POLL}s, full sync every ${SYNC_INTERVAL}s)" >&2
while :; do
sleep "$POLL"
sms_event=
if [ "$sms_first" = 1 ]; then
sms_first=0 # import an already-spooled frame before the first event wait
elif [ "$SMS_TRANSPORT" = urc-log ]; then
sleep "$POLL"
else
sms_clock
wait_due=$sync_due
if [ "$spool_failures" -gt 0 ] || [ "$sim_configured" = 0 ]; then
[ "$wait_due" -le "$((SMS_NOW + POLL))" ] || wait_due=$((SMS_NOW + POLL))
fi
sms_events_wait "$wait_due" || exit 1
fi
if sim_absent; then
sim_configured=0
rm -f "$DIRECT_FLAG"
@@ -161,17 +188,18 @@ while :; do
spool_failures=0
fi
fi
s=$(signature)
if [ "$s" != "$last" ]; then
s=$last
[ "$SMS_TRANSPORT" != urc-log ] || s=$(signature)
if [ "$sms_event" = sync ] || [ "$s" != "$last" ]; then
last=$s
sleep 2 # let the message land in the SIM storage before listing it
sync_fallback || echo "mu300-smsd: sync failed, will retry on the next trigger" >&2
elapsed=0
sms_clock; sync_due=$((SMS_NOW + SYNC_INTERVAL))
continue
fi
elapsed=$((elapsed + POLL))
if [ "$elapsed" -ge "$SYNC_INTERVAL" ]; then
elapsed=0
sms_clock
if [ "$SMS_NOW" -ge "$sync_due" ]; then
sync_due=$((SMS_NOW + SYNC_INTERVAL))
sync_fallback || true
fi
done
+648
View File
@@ -0,0 +1,648 @@
#!/usr/bin/ucode
// Event-driven service core from liuwang97/cpu-load ccf89bb6, adapted locally.
// Preserve this branch's U30 double-click, LED helper, per-policy owned caps,
// vendor-kernel policy and five-second protection/LED deadlines. No mu300-power
// protocol, adaptive thermal delay or upstream frequency backstop is assumed.
// --round runs one thermal round for offline tests; MU300_SYSROOT is a fake root.
'use strict';
import * as uloop from 'uloop';
import * as socket from 'socket';
import { readfile, writefile, open, stat, lstat, mkdir, unlink, lsdir, dup2, access, popen, fdopen, basename,
dirname, rmdir } from 'fs';
let logmod = null;
try { logmod = require('log'); } catch (e) { }
// ------------------------------------------------------------------ small things
function env(name, dflt) { let v = getenv(name); return (v != null && v != '') ? v : dflt; }
function digits(s) { return type(s) == 'string' && s != '' && ltrim(s, '0123456789') == ''; }
function integer(s) { return type(s) == 'string' && digits((substr(s, 0, 1) == '-') ? substr(s, 1) : s); }
function num(name, dflt) { let v = env(name, ''); return digits(v) ? +v : dflt; }
function shq(s) { return "'" + replace('' + s, "'", "'\\''") + "'"; }
function exists(path) { return lstat(path) != null; }
// rd PATH: its first line as the shell's `read -r` leaves it (the blanks around it gone); null when it cannot be read
function rd(path) {
let s = readfile(path);
if (s == null)
return null;
let i = index(s, '\n');
return trim((i >= 0) ? substr(s, 0, i) : s, ' \t');
}
function mkdir_p(dir) {
if (dir == '' || dir == '/' || exists(dir))
return;
mkdir_p(dirname(dir));
mkdir(dir);
}
function retimer(old, ms, cb) {
if (old)
old.cancel();
return uloop.timer(ms, cb);
}
// names DIR PREFIX: the entries of DIR that start with PREFIX, in the shell's glob order
function names(dir, prefix) {
let out = [];
for (let n in lsdir(dir) ?? [])
if (substr(n, 0, length(prefix)) == prefix)
push(out, n);
return sort(out);
}
const R = env('MU300_SYSROOT', '');
const RUN = env('MU300_RUN', '/run');
const BIN = env('MU300_BIN', '/opt/mu300/bin');
const KEYS = env('MU300_KEYS_BIN', 'mu300-keys');
const MODE = ARGV[0] ?? '';
const ONCE = env('MU300_SYSD_ONCE', '') == '1';
let parts = {};
for (let p in split(env('MU300_SYSD_PARTS', 'keys led thermal'), /[ ,]+/))
parts[p] = true;
// the uptime in seconds (a fraction): the clock of the LED files and of mu300-buttons' hotspot marker
function now() {
let u = readfile(R + '/proc/uptime');
return u ? +split(u, ' ')[0] : 0;
}
// log TAG MSG: as the script it comes from logged it (logger -t TAG), into syslog; MU300_SYSD_LOG: into that file
const LOGFILE = env('MU300_SYSD_LOG', null);
function log(tag, msg) {
if (LOGFILE) {
let f = open(LOGFILE, 'a');
if (f) {
f.write(tag + ': ' + msg + '\n');
f.close();
}
}
else if (logmod) {
logmod.openlog(tag);
logmod.syslog(logmod.LOG_NOTICE, '%s', msg);
}
else
warn(tag + ': ' + msg + '\n');
}
// ------------------------------------------------------------------ processes
// What runs is found on mu300-buttons' PATH (the stubs of the tests come first).
let ENV = getenv();
ENV.PATH = (ENV.PATH ?? '/usr/sbin:/usr/bin:/sbin:/bin') + ':/opt/mu300/bin:/usr/sbin:/sbin';
function which(cmd) {
if (index(cmd, '/') >= 0)
return access(cmd, 'x') ? cmd : null;
for (let d in split(ENV.PATH, ':')) {
let p = ((d == '') ? '.' : d) + '/' + cmd;
if (access(p, 'x') && stat(p)?.type == 'file')
return p;
}
return null;
}
// Retain the normal scheduler deadlines; no added timer slack.
function fork_exec(exe, args, envs, cb) { return uloop.process(exe,args,envs,cb); }
let running = 0; // started and not ended yet (the helper is not counted)
let idle_check; // set below
// spawn ARGV [DONE] [MORE] [QUIET]: ARGV in the background, DONE(exit code) once it ended; MORE: environment on top.
// QUIET: stdin, stdout and stderr on /dev/null, as mu300-buttons ran its background work.
function spawn(argv, done, more, quiet) {
let exe = which(argv[0]) ?? argv[0], args = slice(argv, 1);
if (quiet) {
args = [ '-c', 'exec "$0" "$@" </dev/null >/dev/null 2>&1', exe, ...args ];
exe = '/bin/sh';
}
let p = fork_exec(exe, args, more ? { ...ENV, ...more } : ENV, (code) => {
running--;
if (done) {
try { done(code); }
catch (e) { log('mu300-sysd', argv[0] + ': ' + e); }
}
idle_check();
});
if (!p) {
log('mu300-sysd', 'could not start ' + argv[0]);
if (done)
uloop.timer(0, () => done(-1));
return null;
}
running++;
return p;
}
// --- deadlines (mu300-buttons' and mu300-power's rule): a process tree killed
function proc_table() { // { PID: PPID } of every process
let t = {};
for (let d in lsdir('/proc') ?? []) {
let c = ord(d);
if (c < 48 || c > 57)
continue;
let s = readfile('/proc/' + d + '/stat');
if (s == null)
continue;
t[d] = split(substr(s, rindex(s, ')') + 2), ' ')[1];
}
return t;
}
// tree_kill PID: the process and everything it started. The tree is stopped until a look finds nothing new (a child
// forked during one look is caught by the next), then every process any look saw is killed
function tree_kill(pid) {
let prev = null, seen = {};
for (let n = 1; ; n++) {
let pp = proc_table(), s = {}, more = true;
s['' + pid] = true;
while (more) {
more = false;
for (let p in pp)
if (!s[p] && s[pp[p]]) {
s[p] = true;
more = true;
}
}
let all = sort(keys(s), (a, b) => +a - +b);
system('kill -STOP ' + join(' ', all) + ' 2>/dev/null');
for (let p in all)
seen[p] = true;
let key = join(' ', all);
if (key == prev || n >= 10)
break;
prev = key;
}
system('kill -KILL ' + join(' ', keys(seen)) + ' 2>/dev/null');
}
// deadline SECONDS P: past SECONDS the process P and all it started are killed; the timer to cancel when it ends
function deadline(secs, p) {
return p ? uloop.timer(secs * 1000, () => tree_kill(p.pid())) : null;
}
// chain ARGV: one after another, each within a minute (a round's power-off before its alarm, as the guard ran them)
let chain_q = [], chaining = false;
function chain_next() {
let a = shift(chain_q);
if (!a) {
chaining = false;
idle_check();
return;
}
chaining = true;
let t = null;
t = deadline(60, spawn(a, () => { if (t) t.cancel(); chain_next(); }));
}
function chain(argv) {
push(chain_q, argv);
if (!chaining)
chain_next();
}
// ------------------------------------------------------------------ the keys (mu300-buttons)
const KEY_POWER = 116;
const KEY_WIFI = 138; // "Wifi Switch Key" in the U30 Air's device tree (KEY_HELP's code, as its Android maps it)
const DEADLINE = num('MU300_BUTTONS_DEADLINE', 150); // a toggle in the background (the LED sync after wifi up: 120 s)
const PROBE_DEADLINE = num('MU300_BUTTONS_PROBE_DEADLINE', 5);
function is_openwrt() { return exists(R + '/etc/openwrt_release'); }
// probe ARGV CB: ARGV within PROBE_DEADLINE, CB(true) when it said yes (the direction of a hold is decided before the
// wake: it must not wait long)
function probe(argv, cb) {
let t = null;
t = deadline(PROBE_DEADLINE, spawn(argv, (code) => {
if (t)
t.cancel();
cb(code == 0);
}, null, true));
}
function hotspot_is_up(cb) {
if (is_openwrt())
probe([ 'ubus', '-t', '5', 'call', 'hostapd.wlan0', 'get_status' ], cb);
else
probe([ 'systemctl', 'is-active', '--quiet', 'mu300-hotspot' ], cb);
}
let led_arm;
let presses = [], pressing = false, wifi_last = null, key_model = null;
let press_next;
function button_done(argv, cb) {
let timer = null;
let p = spawn(argv, () => { if (timer) timer.cancel(); cb(); });
timer = deadline(DEADLINE, p);
}
function button_model() {
if (key_model != null) return key_model;
let exe = which('mu300-device');
let p = exe ? popen(shq(exe) + ' 2>/dev/null', 'r') : null;
key_model = p ? trim(p.read('all') ?? '') : '';
p?.close();
return key_model;
}
function band_toggle() {
button_done(['/bin/sh','-c','mu300-wifi-band toggle | logger -t mu300-buttons 2>/dev/null'], () => press_next());
}
function press_rest(code, kind) {
if (code == KEY_POWER) {
wifi_last = null;
if (kind == 'long') {
log('mu300-buttons', 'power button held: shutting down');
button_done(is_openwrt() ? ['poweroff'] : ['systemctl','poweroff'], () => press_next());
} else press_next();
return;
}
if (kind == 'long') {
wifi_last = null;
hotspot_is_up((up) => {
let cmd = is_openwrt() ? (up ? 'wifi down; mu300-led wifi off' : 'wifi up') :
(up ? 'systemctl stop mu300-hotspot' : 'systemctl start mu300-hotspot');
button_done(['/bin/sh','-c',cmd], () => press_next());
});
return;
}
if (button_model() != 'u30air') { band_toggle(); return; }
let stamp = rd(R + '/proc/uptime'), fields = stamp ? split(split(stamp, ' ')[0], '.') : [];
if (length(fields) != 2 || !digits(fields[0]) || !digits(fields[1])) {
wifi_last = null; press_next(); return;
}
let tick = +fields[0] * 100 + +fields[1];
if (wifi_last != null && tick >= wifi_last && tick - wifi_last <= 50) {
wifi_last = null; band_toggle();
} else { wifi_last = tick; press_next(); }
}
press_next = function() {
let p = shift(presses);
if (!p) { pressing = false; idle_check(); return; }
pressing = true;
spawn(['mu300-led','wake'], () => {
if (parts.led) led_arm();
try { press_rest(p[0],p[1]); }
catch(e) { log('mu300-sysd','a press failed: '+e); press_next(); }
});
};
function press(code, kind) {
push(presses,[code,kind]);
if (!pressing) press_next();
}
// The existing LED helper owns policy, custom styles, battery and charger state.
// Keep its safety tick unchanged; power-supply events can request a sooner check.
const UEVENTS = 'power_supply,extcon';
let led_timer = null, led_soon_timer = null, led_ticking = false, led_again = false;
function led_look() {
if (led_ticking) { led_again = true; return; }
led_ticking = true;
spawn(['mu300-led','sleep','--if-due'], () => {
led_ticking = false;
if (led_again) { led_again = false; led_look(); }
else led_arm();
});
}
led_arm = function() {
led_timer = retimer(led_timer,5000, () => { led_timer = null; led_look(); });
};
function led_soon() {
led_soon_timer ??= uloop.timer(500, () => { led_soon_timer = null; led_look(); });
}
// ------------------------------------------------------------------ the helper (mu300-keys -u power_supply)
let helper = null, helper_sock = null, helper_h = null, helper_buf = '';
let helper_gone = false, helper_said = false;
function on_line(line) {
let f = split(line, ' ');
if (f[0] == 'uevent') { // the charger or the fuel gauge; "uevent overflow": some were lost
if (parts.led)
led_soon();
}
else if (f[1] == 'tick') { // (from -t: a look, as mu300-buttons' tick)
if (parts.led)
led_look();
}
else if ((f[1] == 'short' || f[1] == 'long') && (f[0] == '116' || f[0] == '138') && parts.keys)
press(+f[0], f[1]);
}
function helper_close() {
if (helper_h)
helper_h.delete();
if (helper_sock)
helper_sock.close();
helper_h = null;
helper_sock = null;
helper_buf = '';
}
function helper_readable() {
let eof = false;
while (helper_sock) {
let d = helper_sock.recv(4096, socket.MSG_DONTWAIT);
if (d == null)
break;
if (d === '') {
eof = true;
break;
}
helper_buf += d;
}
let i;
while ((i = index(helper_buf, '\n')) >= 0) {
let line = substr(helper_buf, 0, i);
helper_buf = substr(helper_buf, i + 1);
try { on_line(line); }
catch (e) { log('mu300-sysd', 'a line failed: ' + e); }
}
if (eof) {
helper_close();
if (ONCE) {
helper_gone = true;
idle_check();
}
}
}
let helper_start; // set below
function helper_ended(code) {
helper = null;
helper_readable(); // what it said before it went
helper_close();
if (ONCE) {
helper_gone = true;
idle_check();
return;
}
// Retain the original button service's ten-second retry bound.
log('mu300-sysd', KEYS + ' ended (' + code + '); again in 10 s');
uloop.timer(10000, () => helper_start());
}
helper_start = function() {
let exe = which(KEYS);
let pr = exe ? socket.pair(socket.SOCK_STREAM | socket.SOCK_CLOEXEC) : null;
if (!pr) {
if (!helper_said)
log('mu300-sysd', exe ? 'no socket pair for ' + KEYS + ': ' + socket.error() : 'no ' + KEYS);
helper_said = true;
uloop.timer(10000, () => helper_start());
return;
}
helper_said = false;
// Its stdout is the pair's other end, read here without blocking (a pipe from popen is a stdio stream: lines
// that arrive together would wait in its buffer, unseen by the loop). That end is lent to this process's stdin
// for the fork alone, where the shell can name it (a redirection takes one digit, and the pair's own numbers are
// past 9 here; this process never reads its stdin), then stdin is /dev/null again: nothing else started later
// holds the pair open.
dup2(pr[1].fileno(), 0);
helper = fork_exec('/bin/sh', [ '-c', 'exec "$0" "$@" >&0 </dev/null', exe, '-l', '3000', '-u', UEVENTS ],
ENV, (code) => helper_ended(code));
let nul = open('/dev/null', 'r');
if (nul) {
dup2(nul.fileno(), 0);
nul.close();
}
else
fdopen(0, 'r')?.close();
pr[1].close();
helper_sock = pr[0];
helper_h = uloop.handle(helper_sock, () => helper_readable(), uloop.ULOOP_READ);
if (!helper)
helper_ended(-1);
};
// ------------------------------------------------------------------ thermal (thermal-guard)
const HOT = num('MU300_THERMAL_HOT', 85000);
const COOL = num('MU300_THERMAL_COOL', 75000);
const CRIT = num('MU300_THERMAL_CRIT', 105000);
const BATT_HOT = num('MU300_BATTERY_HOT', 500);
const BATT_COOL = num('MU300_BATTERY_COOL', 450);
const WAIT = 5;
const TH = R + '/sys/class/thermal';
const LED = BIN + '/mu300-led';
const CAPS = R + '/run/mu300/thermal-caps';
const ALARM = R + '/run/mu300/thermal-alarm';
let legacy_throttle = true;
let DEVICE = null, th_timer = null;
function thermal_init() {
for (let z in names(TH,'thermal_zone')) if (exists(TH+'/'+z+'/trip_point_0_temp')) legacy_throttle=false;
if (exists(R+'/sys/module/mu300_thermal')) legacy_throttle=true;
// the label boot/init leaves when it says u30air, else mu300-device (its V50 rule is about the other labels)
DEVICE = rd(R + '/run/mu300/device');
if (DEVICE != 'u30air') {
let p = popen(shq(BIN + '/mu300-device') + ' 2>/dev/null', 'r');
DEVICE = p ? trim(p.read('all') ?? '') : '';
p?.close();
}
}
function hottest(zones) {
let t = 0;
for (let z in zones) {
let v = rd(TH + '/' + z + '/temp');
if (integer(v) && +v > t)
t = +v;
}
return t;
}
// the battery's temperature in tenths of a degree (null without one); the U30 Air only. The F50 has no battery, but
// under mainline the PMIC's fuel gauge probes on it too and reports one, at 75 C from an unconnected NTC input. The
// supply that is the battery is looked for again only when its reading fails.
let battery_dir = null;
function battery_temp() {
if (DEVICE != 'u30air')
return null;
let b = battery_dir ? rd(battery_dir + '/temp') : null;
if (b != null && b != '')
return b;
battery_dir = null;
for (let d in names(R + '/sys/class/power_supply', '')) {
d = R + '/sys/class/power_supply/' + d;
if (rd(d + '/type') != 'Battery')
continue;
b = rd(d + '/temp');
if (b != null && b != '') {
battery_dir = d;
return b;
}
}
return null;
}
// Recheck native cooling bindings every round, using thermal-guard's criteria.
function inode(s) { return s.dev.major + ':' + s.dev.minor + ':' + s.inode; }
// qualifies ZONEDIR HOTTEST CDEVS: that zone throttles the CPUs (see above)
function qualifies(z, t, cdevs) {
if (rd(z + '/mode') != 'enabled')
return false;
let tp = null;
for (let i = 0; tp == null; i++) {
let tt = rd(z + '/trip_point_' + i + '_type');
if (tt == null)
break;
let v = (tt == 'passive') ? rd(z + '/trip_point_' + i + '_temp') : null;
if (digits(v) && +v <= HOT)
tp = v;
}
if (tp == null)
return false;
let zt = rd(z + '/temp');
if (!digits(zt) || +zt < t - 15000)
return false;
// cdevK is the link to a cooling device (cdevK_trip_point and cdevK_weight are files)
let bound = {};
for (let l in names(z, 'cdev')) {
let c = ord(l, 4), s = (c >= 48 && c <= 57) ? stat(z + '/' + l) : null;
if (s?.type == 'directory')
bound[inode(s)] = true;
}
for (let d in cdevs) {
let s = stat(d);
if (!s || !bound[inode(s)])
return false;
}
return true;
}
function native_cpu_cooling(t, listing) {
if (!exists(R+'/sys/module/mu300_thermal')) return false;
let cdevs=[];
for (let d in listing)
if (substr(d,0,14)=='cooling_device' && substr(rd(TH+'/'+d+'/type') ?? '',0,8)=='cpufreq-') push(cdevs,TH+'/'+d);
if (!length(cdevs)) return false;
for (let z in listing)
if (substr(z,0,12)=='thermal_zone' && rd(TH+'/'+z+'/type')=='soc-thmzone' && qualifies(TH+'/'+z,t,cdevs)) return true;
return false;
}
function policies() {
let out = [];
for (let p in names(R + '/sys/devices/system/cpu/cpufreq', 'policy'))
push(out, R + '/sys/devices/system/cpu/cpufreq/' + p);
return out;
}
function cap_file(p) { return CAPS + '/' + basename(p); }
function cap_read(p) {
let v=split(rd(cap_file(p)) ?? '', '|');
return length(v)==2 && digits(v[0]) && digits(v[1]) ? {ceiling:+v[0],applied:+v[1]} : null;
}
function cap_save(p, ceiling, applied) {
mkdir_p(CAPS);
writefile(cap_file(p),ceiling+'|'+applied+'\n');
}
function frequencies(p) {
return sort(map(filter(split(trim(readfile(p+'/scaling_available_frequencies') ?? ''), /[ \n]+/), (f)=>digits(f)), (f)=>+f), (a,b)=>a-b);
}
function guard_lower(p) {
let current=rd(p+'/scaling_max_freq');
if (!digits(current)) return;
let saved=cap_read(p), ceiling=saved && +current==saved.applied ? saved.ceiling : +current, next=null;
for (let f in frequencies(p)) if (f < +current) next=f;
if (next != null && writefile(p+'/scaling_max_freq',next+'\n')) cap_save(p,ceiling,next);
}
function guard_release(p) {
let saved=cap_read(p), current=rd(p+'/scaling_max_freq');
if (!saved || !digits(current)) return;
if (+current==saved.applied && !writefile(p+'/scaling_max_freq',saved.ceiling+'\n')) return;
unlink(cap_file(p));
}
function guard_raise(p) {
let saved=cap_read(p), current=rd(p+'/scaling_max_freq');
if (!saved || !digits(current)) return;
if (+current!=saved.applied || +current>=saved.ceiling) { unlink(cap_file(p)); return; }
let next=saved.ceiling;
for (let f in frequencies(p)) if (f > +current && f < next) next=f;
if (!writefile(p+'/scaling_max_freq',next+'\n')) return;
if (next==saved.ceiling) unlink(cap_file(p)); else cap_save(p,saved.ceiling,next);
}
function mark(path, text) { mkdir_p(dirname(path)); writefile(path,text); }
function thermal_round() {
let listing=names(TH,''), zones=filter(listing,(z)=>substr(z,0,12)=='thermal_zone');
let t=hottest(zones), b=battery_temp(), throttle=legacy_throttle, emergency=legacy_throttle;
if (exists(R+'/sys/module/mu300_thermal')) {
throttle=true; emergency=true;
if (native_cpu_cooling(t,listing)) { throttle=false; for (let p in policies()) guard_release(p); }
}
if (t>=CRIT && emergency) {
log('thermal-guard','critical temperature '+t+' mC, powering off'); chain(['poweroff']);
} else if (t>=HOT && throttle) {
for (let p in policies()) guard_lower(p);
log('thermal-guard','hot ('+t+' mC): lowered cpufreq limits');
} else if (t<=COOL && throttle) { for (let p in policies()) guard_raise(p); }
let bn=b==null || b=='' ? 0 : integer(b) ? +b : null, bs=b==null || b=='' ? '-' : b;
if (!exists(ALARM) && (t>=HOT || (bn!=null && bn>=BATT_HOT))) {
mark(ALARM,''); log('thermal-guard','too hot (SoC '+t+' mC, battery '+bs+' dC): LED alarm on'); chain([LED,'alarm','on']);
} else if (exists(ALARM) && t<=COOL && bn!=null && bn<=BATT_COOL) {
unlink(ALARM); log('thermal-guard','cooled down (SoC '+t+' mC, battery '+bs+' dC): LED alarm off'); chain([LED,'alarm','off']);
}
return 5; // Preserve this branch's protection cadence, including without native cooling.
}
function thermal_next() {
let gap = WAIT;
try { gap = thermal_round(); }
catch (e) { log('mu300-sysd', 'a thermal round failed: ' + e); }
th_timer = retimer(th_timer, gap * 1000, () => thermal_next());
}
// ------------------------------------------------------------------ main
idle_check = function() {
if (MODE == '--round') {
if (!running && !chaining)
uloop.end();
}
else if (ONCE && helper_gone && !pressing && !length(presses) && !running)
uloop.end();
};
if (MODE == '--check') {
// the modules loaded (or this program would not run), the calls of this ucode, a helper that knows -u
if (type(socket.pair) != 'function' || type(uloop.process) != 'function' || type(uloop.signal) != 'function') {
warn('mu300-sysd: this ucode lacks socket.pair, uloop.process or uloop.signal\n');
exit(1);
}
let exe = which(KEYS);
let p = exe ? popen(shq(exe) + ' -? 2>&1', 'r') : null;
let usage = p ? (p.read('all') ?? '') : '';
p?.close();
if (index(usage, '-u SUBSYSTEM') < 0) {
warn('mu300-sysd: ' + (exe ? exe + ' does not know -u (an older build)' : 'no ' + KEYS) + '\n');
exit(1);
}
exit(0);
}
uloop.init();
if (MODE == '--round') {
thermal_init();
warn('next look in ' + thermal_round() + ' s\n');
if (running || chaining)
uloop.run();
exit(0);
}
if (MODE != '') {
warn('usage: mu300-sysd [--check | --round]\n');
exit(2);
}
const OWN_DIR = RUN + '/mu300/sysd.lock';
const OWN_PID = +split(readfile('/proc/self/stat'),' ')[0];
function acquire_owner() {
mkdir_p(dirname(OWN_DIR));
for (let attempt=0; attempt<4; attempt++) {
if (mkdir(OWN_DIR,0700)) {
if (writefile(OWN_DIR+'/pid',OWN_PID+'\n')) return true;
rmdir(OWN_DIR); return false;
}
let pid=rd(OWN_DIR+'/pid');
if (pid==null || pid=='') return false;
if (digits(pid) && exists('/proc/'+pid)) return false;
unlink(OWN_DIR+'/pid');
if (!rmdir(OWN_DIR)) return false;
}
return false;
}
if (!acquire_owner()) { log('mu300-sysd','another owner or unavailable runtime directory; not starting a second helper'); exit(0); }
uloop.signal('SIGTERM', () => uloop.end());
uloop.signal('SIGINT', () => uloop.end());
if (parts.keys) button_model();
if (parts.keys || parts.led)
helper_start();
if (parts.led) {
// the first look a little after the start, as mu300-buttons' first tick (the tests' runs end before it)
if (!ONCE)
led_timer = uloop.timer(5000, () => { led_timer = null; led_look(); });
}
if (parts.thermal) {
thermal_init();
thermal_next();
}
uloop.run();
helper_close();
if (rd(OWN_DIR+'/pid')==''+OWN_PID) { unlink(OWN_DIR+'/pid'); rmdir(OWN_DIR); }
+5
View File
@@ -12,6 +12,11 @@
# (sipa_eth*), so it survives mobile data reconnecting, and it lives in its own nftables table (inet mu300_ttl),
# next to OpenWrt's fw4 and the Ubuntu firewall.
export PATH="$PATH:/opt/mu300/bin:/usr/sbin:/sbin"
# OpenWrt uses the same explicit backend as the LuCI page. Ubuntu retains its
# nftables CLI below; this is a platform distinction, never an error fallback.
if [ -f /etc/openwrt_release ]; then
exec /usr/libexec/unisoc-modem/ttl-engine "$@"
fi
CONF=${MU300_TTL_CONF:-/etc/mu300/ttl.conf} # (the variable is for tests/)
TABLE="inet mu300_ttl"
+14 -9
View File
@@ -1,15 +1,20 @@
#!/bin/sh
# Load the wireless regulatory database. cfg80211 asks for regulatory.db before the rootfs is mounted; the direct load
# fails and the request waits 60 s in the sysfs firmware fallback, blocking "iw reg reload". Answer pending requests
# (database, then its signature) through /sys/class/firmware, then reload.
# Load the signed wireless regulatory database. Kernels with the sysfs firmware
# helper can retain a request from before switch_root; answer it before reload.
# With CONFIG_FW_LOADER_USER_HELPER disabled that class does not exist: there
# cannot be a pending sysfs request, so never wait for one. Normal regdb loading
# and kernel signature verification still happen through "iw reg reload".
R=${MU300_SYSROOT:-}
if [ -d "$R/sys/class/firmware" ]; then
for f in regulatory.db regulatory.db.p7s; do
src=/lib/firmware/$f
[ -e "$src" ] || src=/usr/lib/firmware/$f
for n in 1 2 3 4 5 6 7 8 9 10; do [ -d /sys/class/firmware/$f ] && break; sleep 0.3 2>/dev/null || sleep 1; done
s=/sys/class/firmware/$f
[ -d $s ] && [ -e "$src" ] || continue
echo 1 > $s/loading && cat "$src" > $s/data && echo 0 > $s/loading && echo "fed $f to the pending firmware request"
src=$R/lib/firmware/$f
[ -e "$src" ] || src=$R/usr/lib/firmware/$f
for n in 1 2 3 4 5 6 7 8 9 10; do [ -d "$R/sys/class/firmware/$f" ] && break; sleep 0.3 2>/dev/null || sleep 1; done
s=$R/sys/class/firmware/$f
[ -d "$s" ] && [ -e "$src" ] || continue
echo 1 > "$s/loading" && cat "$src" > "$s/data" && echo 0 > "$s/loading" && echo "fed $f to the pending firmware request"
done
fi
for n in $(seq 1 10); do iw reg reload 2>/dev/null && exit 0; sleep 1; done
echo "iw reg reload failed" >&2
exit 1
+16 -8
View File
@@ -46,16 +46,25 @@ grep -q '^sipa_dele ' /proc/modules && { log "already loaded"; exit 0; }
modem_up() {
dmesg | grep -qE 'sprd-sbuf: channel 5-|sbuf ready for pmic wdt init' || return 1
[ -c /dev/stty_nr1 ] || return 1
mu300-at -t 8 'AT+CGATT?' 2>/dev/null | grep -q '+CGATT: *1'
# The channel owner must be ready; this probe never opens a raw tty.
MU300_AT_DAEMON_ONLY=1 mu300-at -t 8 'AT+CGATT?' 2>/dev/null | grep -q '+CGATT: *1'
}
n=0
while [ "$n" -lt "$WAIT" ]; do
uptime_s() { local value=; read -r value _ < /proc/uptime; printf '%s\n' "${value%%.*}"; }
start=$(uptime_s)
while [ "$(( $(uptime_s)-start ))" -lt "$WAIT" ]; do
if modem_up; then
log "modem is up after ${n}s"
insmod "$KO" 2>/dev/null && log "loaded sipa-dele" || log "FAILED sipa-dele"
log "modem is up after $(( $(uptime_s)-start ))s"
if ! insmod "$KO"; then
log "FAILED sipa-dele"
exit 1
fi
log "loaded sipa-dele"
# Both halves of the handshake are pr_info, so this says immediately whether it took.
sleep 3
for probe in $(seq 1 30); do
dmesg | grep -q 'channel 5-120 send open msg' && break
sleep 0.1
done
if dmesg | grep -q 'channel 5-120 send open msg'; then
log "channel open sent; handshake: $(dmesg | grep -c sipa_dele) sipa_dele messages so far"
else
@@ -63,8 +72,7 @@ while [ "$n" -lt "$WAIT" ]; do
fi
exit 0
fi
n=$((n + 2))
sleep 2
sleep 0.5
done
log "packet domain not ready after ${WAIT}s; refusing unsafe delegate load"
@@ -27,6 +27,10 @@ case "${1:-}" in
thermal) "$LED" alarm on ;;
boot|modem|registering|online-4g|online-5g|offline)
echo "$1" > "$RUN/led-status.state"
case "$1" in
boot) "$LED" boot on ;;
online-4g|online-5g|offline) "$LED" boot off ;;
esac
network "$1"
"$LED" battery ;;
*) exit 1 ;;
+23
View File
@@ -0,0 +1,23 @@
#!/usr/bin/ucode
// One read-only readiness check; never enables a disabled radio or AP.
import { cursor } from 'uci';
import { connect } from 'ubus';
let c=cursor(), bus=connect(null,2);
if(!bus)exit(1);
let runtime=bus.call('network.wireless','status',{});
if(runtime==null)exit(1);
let ready=true, configured=0;
c.foreach('wireless','wifi-device',radio=>{
configured++;
if(radio.disabled=='1')return;
let r=runtime[radio['.name']];
if(!r?.up || r.pending || r.failed) {ready=false;return;}
c.foreach('wireless','wifi-iface',iface=>{
if(iface.device!=radio['.name'] || iface.disabled=='1')return;
let actual=null;
for(let i in r.interfaces || [])if(i.section==iface['.name'])actual=i;
if(!actual?.ifname) {ready=false;return;}
if(iface.mode=='ap' && bus.call('hostapd.'+actual.ifname,'get_status',{})?.status!='ENABLED')ready=false;
});
});
exit(ready && configured?0:1);
+3
View File
@@ -4,7 +4,9 @@
# 5.4 vendor kernel: all four are modules. Mainline: the PCIe host is built in, wcn_bsp/sprd_wlan_combo are
# out-of-tree modules in /lib/modules/<release>.
set -e
[ ! -x /opt/mu300/bin/bootmark ] || /opt/mu300/bin/bootmark wifi-index-enter
command -v depmod >/dev/null && depmod -a
[ ! -x /opt/mu300/bin/bootmark ] || /opt/mu300/bin/bootmark wifi-index-ready
[ -e /sys/class/net/wlan0 ] && exit 0 # the WCN drivers cannot be reloaded; never load them twice
for m in pcie-sprd-misc pcie-sprd; do
modprobe "$m" 2>/dev/null || [ -d /sys/bus/platform/drivers/sprd-pcie ]
@@ -18,6 +20,7 @@ for m in wcn_bsp sprd_wlan_combo; do
[ -f "$f" ] || f=$K/extra/$m.ko
[ -f "$f" ] || { echo "missing $m.ko" >&2; exit 1; }
insmod "$f"
[ ! -x /opt/mu300/bin/bootmark ] || /opt/mu300/bin/bootmark "wifi-module-$m-loaded"
done
for n in $(seq 1 30); do [ -e /sys/class/net/wlan0 ] && break; sleep 1; done
# wcn_bsp turns the Marlin3 firmware (ARM) log on at boot; every firmware log packet is printed to the kernel log
@@ -0,0 +1,80 @@
#!/bin/sh
# Adapt the cpu-load event watchdog to this branch's existing recovery loop.
# Keep its thirty-second safety deadline and two-confirmation retry budget.
watch_events=0 watch_event_pid= watch_event= WATCH_NOW=0
watch_clock() {
local up rest
IFS=' ' read -r up rest < /proc/uptime || return 1
WATCH_NOW=${up%.*}
}
watch_events_stop() {
if [ -n "$watch_event_pid" ]; then
kill "$watch_event_pid" 2>/dev/null || true
wait "$watch_event_pid" 2>/dev/null || true
fi
[ "$watch_events" = 0 ] || exec 8<&-
watch_events=0 watch_event_pid=
}
watch_events_start() {
local dir
ubus -t 2 list mu300.modem >/dev/null 2>&1 || return 1
dir=$(mktemp -d "${TMPDIR:-/tmp}/data-events.XXXXXX") || return 1
if ! mkfifo -m 600 "$dir/events"; then rmdir "$dir"; return 1; fi
ubus -S listen mu300.modem.urc mu300.sim-state network.interface ubus.object.remove > "$dir/events" 2>/dev/null </dev/null 8<&- &
watch_event_pid=$!
exec 8< "$dir/events"
rm -f "$dir/events"; rmdir "$dir"
watch_events=1
}
watch_event_decode() {
watch_event=
case "$1" in
*'"ubus.object.remove"'*'"path":"mu300.modem"'*) watch_event=gone; return ;;
*'"network.interface"'*)
case "$1" in *'"interface":"'"${MU300_WAN:-wan}"'"'*) watch_event=network ;; esac
return ;;
*'"mu300.sim-state"'*)
# Either slot can be selected by a completed data-SIM transaction;
# the existing main loop re-resolves that choice before any AT.
watch_event=sim; return ;;
*'"mu300.modem.urc"'*) ;;
*) return ;;
esac
# Only physical unsolicited channels. Query answers on nr1/nr4 must not
# feed our own CEREG checks back into an infinite refresh loop.
case "${MU300_SIM_SLOT:-0}:$1" in
0:*'"channel":"stty_nr0"'*|1:*'"channel":"stty_nr3"'*) ;;
*) return ;;
esac
case "$1" in
*'"line":"+CGEV:'*|*'"line":"NO CARRIER'*|\
*'"line":"+CREG:'*|*'"line":"+CGREG:'*|\
*'"line":"+CEREG:'*|*'"line":"+C5GREG:'*) watch_event=modem ;;
esac
}
watch_next() {
local interval=${MU300_WATCH_INTERVAL:-30} due line status
watch_event=
case "$interval" in ''|*[!0-9]*) echo 'mobile-data: watch interval must be whole seconds' >&2; return 1 ;; esac
[ "$watch_events" = 1 ] || return 1
watch_clock || return 1
due=$((WATCH_NOW + interval))
while [ "$WATCH_NOW" -lt "$due" ]; do
status=0
IFS= read -r -t "$((due - WATCH_NOW))" line <&8 || status=$?
watch_clock || return 1
if [ "$status" != 0 ]; then
# Bash read reports its timer as 128 + SIGALRM. /proc/uptime
# can still round below the deadline: this is not a dead FIFO.
[ "$status" != 142 ] || continue
[ "$WATCH_NOW" -ge "$due" ] || { echo "mobile-data: modem event listener disconnected" >&2; return 1; }
return 0
fi
watch_event_decode "$line"
if [ "$watch_event" = gone ]; then echo "mobile-data: modem service disconnected" >&2; return 1; fi
# An event burst must not shorten the original interval between two
# confirmed detach observations before recovery.
if [ -n "$watch_event" ] && [ "${fails:-0}" = 0 ]; then return 0; fi
done
return 0
}
@@ -0,0 +1,75 @@
#!/bin/sh
# OpenWrt native modem service and model-specific channel layouts.
modemd_require() {
[ -x /opt/mu300/bin/mu300-atd-io ] && [ -r /opt/mu300/bin/mu300-modemd ] &&
/usr/bin/ucode -e "import * as a from 'uloop'; import * as b from 'socket'; import * as c from 'ubus'; import * as d from 'mu300.registration'; import * as e from 'mu300.cellparse'; import * as f from 'uci';" || {
echo 'mu300-atd: native modem runtime is incomplete' >&2; return 1;
}
# Refuse an unsafe in-place transition from an old physical owner. Repair
# the image/reboot; never select a second implementation at runtime.
local pidfile pid
for pidfile in /run/mu300-at*/owner/pid; do
[ -r "$pidfile" ] || continue
IFS= read -r pid < "$pidfile"
case "$pid" in ''|*[!0-9]*) continue ;; esac
if [ -d "/proc/$pid" ]; then
echo 'mu300-atd: a physical channel owner is already running; reboot before switching services' >&2
return 1
fi
done
}
MODEMD_BROKERS=
modemd_broker() {
# Metadata is fixed by this init script, never user input. One line per argv.
MODEMD_BROKERS="${MODEMD_BROKERS}${MODEMD_BROKERS:+
}name=$1,dev=$2,dir=$3,urc=$4,live=$5,reopen=$6,ready=$7"
}
modemd_start() {
procd_open_instance atd-io
procd_set_param command /opt/mu300/bin/mu300-atd-io -s /run/mu300-modem/io.sock
[ "$1" != 1 ] || procd_set_param respawn 3600 10 0
procd_set_param stdout 1
procd_set_param stderr 1
procd_close_instance
procd_open_instance modemd
procd_set_param command /usr/bin/ucode /opt/mu300/bin/mu300-modemd -s /run/mu300-modem/io.sock
while IFS= read -r spec; do
[ -z "$spec" ] || procd_append_param command "$spec"
done <<EOF
$MODEMD_BROKERS
EOF
procd_set_param env "MU300_SMS_POOL=$(mu300_sms_pool)"
# The daemon owns no SIPC descriptor and may safely take over the C bridge.
procd_set_param respawn 3600 5 0
procd_set_param stdout 1
procd_set_param stderr 1
procd_close_instance
}
modemd_single_layout() {
local reopen=1 ready= n urc live
if [ "$(/opt/mu300/bin/mu300-device 2>/dev/null)" = u30air ]; then
reopen=0 ready=sbuf:sbuf_5_006
fi
MODEMD_BROKERS=
modemd_broker atd /dev/stty_nr1 /run/mu300-at 0 /run/mu300-at/urc/stty_nr0.log "$reopen" "$ready"
modemd_broker atd2 /dev/stty_nr2 /run/mu300-at2 '' /run/mu300-at/urc/stty_nr0.log "$reopen" "$ready"
for n in 3 4 5 6 7; do
[ "$n" != 3 ] || [ "$(uci -q get unisoc_modem.main.sim_slots)" != 2 ] || continue
urc= live=/run/mu300-at/urc/stty_nr0.log
if [ "$n" = 4 ] && [ "$(uci -q get unisoc_modem.main.sim_slots)" = 2 ]; then
urc=3 live=/run/mu300-at4/urc/stty_nr3.log
fi
modemd_broker atd$n /dev/stty_nr$n /run/mu300-at$n "$urc" "$live" "$reopen" "$ready"
done
modemd_start "$reopen"
}
modemd_sim2_layout() {
MODEMD_BROKERS=
modemd_broker atd /dev/stty_nr1 /run/mu300-at 0 /run/mu300-at/urc/stty_nr0.log 0 sbuf:sbuf_5_006
modemd_broker atd2 /dev/stty_nr2 /run/mu300-at2 '' /run/mu300-at/urc/stty_nr0.log 0 sbuf:sbuf_5_006
modemd_broker atd4 /dev/stty_nr4 /run/mu300-at4 3 /run/mu300-at4/urc/stty_nr3.log 0 sbuf:sbuf_5_006
modemd_broker atd5 /dev/stty_nr5 /run/mu300-at5 '' /run/mu300-at4/urc/stty_nr3.log 0 sbuf:sbuf_5_006
modemd_start 0
}
@@ -0,0 +1,79 @@
#!/bin/sh
# Event waiting adapted from liuwang97/cpu-load ccf89bb6. Route policy remains
# in ndp-learn; monitor our neighbours too, since this branch retains /128 pins.
ndp_events=0 ndp_event_pid= NDP_DIRTY=0 NDP_NOW=0 NDP_FULL_AT=0 NDP_WITHDRAW_AT=0
NDP_INTERVAL=10
ndp_clock() {
local up rest
IFS=' ' read -r up rest < /proc/uptime || return 1
NDP_NOW=${up%.*}
}
ndp_events_stop() {
if [ -n "$ndp_event_pid" ]; then
kill "$ndp_event_pid" 2>/dev/null || true
wait "$ndp_event_pid" 2>/dev/null || true
fi
[ "$ndp_events" = 0 ] || exec 8<&-
ndp_events=0 ndp_event_pid=
}
ndp_events_start() {
local dir
ndp_clock || return 1
dir=$(mktemp -d "${TMPDIR:-/tmp}/ndp-events.XXXXXX") || return 1
if ! mkfifo -m 600 "$dir/monitor"; then rmdir "$dir"; return 1; fi
ip -o -6 monitor label address route neigh > "$dir/monitor" 2>/dev/null </dev/null 8<&- &
ndp_event_pid=$!
exec 8< "$dir/monitor"
rm -f "$dir/monitor"; rmdir "$dir"
ndp_events=1
NDP_TICK_AT=$((NDP_NOW + NDP_INTERVAL))
}
# Only stable routing fields. Packet/reference counters must not turn ordinary
# traffic into a route change. No helper processes are needed for this snapshot.
ndp_snapshot() {
local ad ix pl sc fl dev dst dp src sp gw metric refs uses flags rest
[ -r "$IF_INET6" ] && [ -r "${MU300_IPV6_ROUTE:-/proc/net/ipv6_route}" ] || return 1
NDP_SNAPSHOT= NDP_GLOBAL=0
while read -r ad ix pl sc fl dev; do
case "$dev" in "${IFACE:-sipa_eth0}"|br-lan)
NDP_SNAPSHOT="$NDP_SNAPSHOT|a:$ad:$ix:$pl:$sc:$fl:$dev" ;;
esac
[ "$dev" != "${IFACE:-sipa_eth0}" ] || [ "$sc" != 00 ] || NDP_GLOBAL=1
done < "$IF_INET6"
NDP_ADDRESSES=$NDP_SNAPSHOT
while read -r dst dp src sp gw metric refs uses flags dev rest; do
case "$dev" in "${IFACE:-sipa_eth0}"|br-lan)
NDP_SNAPSHOT="$NDP_SNAPSHOT|r:$dst:$dp:$src:$sp:$gw:$metric:$flags:$dev" ;;
esac
done < "${MU300_IPV6_ROUTE:-/proc/net/ipv6_route}"
}
ndp_event_relevant() {
case " $1 " in *'[ADDR]'*|*" ${IFACE:-sipa_eth0} "*|*' br-lan '*) ;; *) return 1 ;; esac
# A deletion can race our post-write snapshot. Force a pass even then;
# idempotent replacements do not delete routes on subsequent passes.
case "$1" in *'[NEIGH]'*|*Deleted*) NDP_DIRTY=1 ;; esac
return 0
}
ndp_events_wait() {
local due line status
NDP_DIRTY=0
ndp_clock || return 1
due=$NDP_TICK_AT
[ "$NDP_FULL_AT" -ge "$due" ] || due=$NDP_FULL_AT
while [ "$NDP_NOW" -lt "$due" ]; do
status=0
IFS= read -r -t "$((due - NDP_NOW))" line <&8 || status=$?
ndp_clock || return 1
if [ "$status" != 0 ]; then
# Bash timeout is not EOF, even if uptime rounds below due.
[ "$status" != 142 ] || continue
# A dead monitor is a failed service, not permission to silently
# start a different observer implementation.
[ "$NDP_NOW" -ge "$due" ] || { echo "ndp-learn: route monitor disconnected" >&2; return 1; }
break
fi
ndp_event_relevant "$line" && return 0
done
if [ "$NDP_NOW" -ge "$NDP_TICK_AT" ]; then NDP_TICK_AT=$((NDP_NOW + NDP_INTERVAL)); fi
return 0
}
@@ -0,0 +1,22 @@
#!/bin/sh
# Reuse the platform's authoritative data-SIM/device mapping. Cache its inputs
# with shell reads; unchanged event notifications must not spawn uci/device.
IFACE=${IFACE:-sipa_eth0}
ndp_iface_refresh() {
local root=${MU300_NDP_RUN:-/run} lib=${MU300_NDP_SIM_ENV:-/opt/mu300/bin/mu300-sim-env}
local file=${MU300_NDP_CONFIG:-/etc/config/unisoc_modem} signature= line=
[ ! -e "$root/mu300/sim-switching" ] && [ ! -e "$root/mu300/sim-active-unknown" ] &&
[ ! -d "$root/unisoc-data-sim-switch" ] || return 75
[ -r "$lib" ] || { echo "ndp-learn: SIM mapping library is missing" >&2; return 1; }
if [ -r "$file" ]; then
while IFS= read -r line || [ -n "$line" ]; do signature="$signature
$line"; done < "$file"
fi
[ "${ndp_iface_signature:-unset}" != "$signature" ] || return 0
. "$lib" || return 1
mu300_sim_env "" || return 1
case "$MU300_SIM_DEVICE" in ''|*[!a-zA-Z0-9_.:-]*) return 1 ;; esac
[ "${#MU300_SIM_DEVICE}" -le 15 ] || return 1
IFACE=$MU300_SIM_DEVICE
ndp_iface_signature=$signature
}
-156
View File
@@ -1,156 +0,0 @@
# U30 Air native dual-SIM policy, ported from upstream 0d520f4.
# This fork stores boot intent with the shared per-SIM APN/traffic configuration.
sim_wan=$(uci -q get unisoc_modem.main.data_interface 2>/dev/null || true)
sim_wan=${sim_wan:-wan}
case "$sim_wan" in *[!a-zA-Z0-9_]*) return 1;; esac
# Shared SIM preference storage. Runtime routing uses /run/mu300/sim-slot, never this preference.
# The caller sets SIM_CONFIG_U30=1 only after positive U30 Air/OpenWrt identification.
sim_config_root=${MU300_SIM_ROOT:-}
sim_cfg_valid() { case "$1" in 0|1) return 0;; *) echo 'SIM slot must be 0 or 1' >&2; return 1;; esac; }
sim_cfg_default() {
local slot
if command -v uci >/dev/null 2>&1; then
if slot=$(uci -q get unisoc_modem.main.data_sim); then :
elif [ "${SIM_CONFIG_U30:-0}" = 1 ]; then
slot=$(cat "$sim_config_root/etc/mu300-sim-slot" 2>/dev/null || true)
fi
else
slot=$(cat "$sim_config_root/etc/mu300/sim-slot" 2>/dev/null || true)
fi
slot=${slot:-0}
sim_cfg_valid "$slot" || return 1
printf '%s\n' "$slot"
}
sim_cfg_hot() {
local hot
[ "${SIM_CONFIG_U30:-0}" = 1 ] || { echo 0; return 0; }
if hot=$(uci -q get unisoc_modem.main.u30_sim_hot); then :
else hot=$(cat "$sim_config_root/etc/mu300-sim-hot" 2>/dev/null || true); fi
hot=${hot:-0}
case "$hot" in 0|1) printf '%s\n' "$hot";; *) echo 'Invalid SIM hot-switch policy' >&2; return 1;; esac
}
sim_cfg_write() {
local option=$1 value=$2 old present=0
case "$option" in data_sim|u30_sim_hot) ;; *) return 1;; esac
if old=$(uci -q get "unisoc_modem.main.$option"); then present=1; fi
uci set "unisoc_modem.main.$option=$value" || return 1
if uci commit unisoc_modem; then return 0; fi
# A failed commit must not advertise the unsaved staged value as the next-boot preference.
if [ "$present" = 1 ]; then uci set "unisoc_modem.main.$option=$old" || true
else uci -q delete "unisoc_modem.main.$option" || true; fi
return 1
}
sim_cfg_save_default() {
local tmp
sim_cfg_valid "$1" || return 1
if command -v uci >/dev/null 2>&1; then
sim_cfg_write data_sim "$1"
else
mkdir -p "$sim_config_root/etc/mu300" || return 1
tmp=$(mktemp "$sim_config_root/etc/mu300/sim-slot.XXXXXX") || return 1
printf '%s\n' "$1" > "$tmp" && mv -f "$tmp" "$sim_config_root/etc/mu300/sim-slot"
fi
}
sim_cfg_save_hot() {
sim_cfg_valid "$1" || return 1
[ "${SIM_CONFIG_U30:-0}" = 1 ] && command -v uci >/dev/null 2>&1 || return 1
sim_cfg_write u30_sim_hot "$1"
}
sim_cfg_unstage_added() {
local key
for key in "$@"; do
case "$key" in data_sim|u30_sim_hot) uci -q delete "unisoc_modem.main.$key" || true;; esac
done
}
sim_cfg_migrate() {
local slot hot saved_slot saved_hot slot_present=0 hot_present=0 touched= key value old destination
[ "${SIM_CONFIG_U30:-0}" = 1 ] || return 0
command -v uci >/dev/null 2>&1 || return 1
if saved_slot=$(uci -q get unisoc_modem.main.data_sim); then slot_present=1; fi
if saved_hot=$(uci -q get unisoc_modem.main.u30_sim_hot); then hot_present=1; fi
[ "$slot_present" = 0 ] || sim_cfg_valid "${saved_slot:-0}" || return 1
[ "$hot_present" = 0 ] || sim_cfg_valid "${saved_hot:-0}" || return 1
slot=$(cat "$sim_config_root/etc/mu300-sim-slot" 2>/dev/null || true)
hot=$(cat "$sim_config_root/etc/mu300-sim-hot" 2>/dev/null || true)
# Validate every legacy value before making any staged change.
[ "$slot_present" = 1 ] || [ -z "$slot" ] || sim_cfg_valid "$slot" || return 1
[ "$hot_present" = 1 ] || [ -z "$hot" ] || sim_cfg_valid "$hot" || return 1
if [ "$slot_present" = 0 ] && [ -n "$slot" ]; then
uci set "unisoc_modem.main.data_sim=$slot" || { sim_cfg_unstage_added $touched; return 1; }
touched="data_sim"
fi
if [ "$hot_present" = 0 ] && [ -n "$hot" ]; then
uci set "unisoc_modem.main.u30_sim_hot=$hot" || { sim_cfg_unstage_added $touched; return 1; }
touched="$touched u30_sim_hot"
fi
if [ -n "$touched" ] && ! uci commit unisoc_modem; then
sim_cfg_unstage_added $touched
return 1
fi
for old in "$sim_config_root/etc/mu300-sim-slot" "$sim_config_root/etc/mu300-sim-hot"; do
[ -e "$old" ] || continue
mkdir -p "$sim_config_root/etc/mu300/sim-migration" || return 1
destination=$sim_config_root/etc/mu300/sim-migration/${old##*/}.migrated
[ ! -e "$destination" ] || destination=$destination.$(date +%s).$$
mv "$old" "$destination" || return 1
done
}
# --- which cards have had mobile data under Linux (U30 Air dual SIM) ---
# /etc/mu300/sim-data-seen: one stored slot number (0 or 1) per line, root's alone; it holds no identity. A card is
# written here the first time netifd has an address on its bearer. The boot check (mu300-sim2-warmup) reads it: a
# second card that has never had data and gets none within the time is given up for SIM1; one that has had data
# before is never taken away for an outage.
sim_seen_file=$sim_config_root/etc/mu300/sim-data-seen
sim_seen() {
case "$1" in 0|1) ;; *) return 1 ;; esac
grep -qx "$1" "$sim_seen_file" 2>/dev/null
}
sim_seen_add() {
local tmp
case "$1" in 0|1) ;; *) return 1 ;; esac
if sim_seen "$1"; then return 0; fi
mkdir -p "${sim_seen_file%/*}" || return 1
tmp=$(umask 077; mktemp "$sim_seen_file.XXXXXX") || return 1
{ grep -x '[01]' "$sim_seen_file" 2>/dev/null || true; printf '%s\n' "$1"; } > "$tmp" &&
mv -f "$tmp" "$sim_seen_file" || { rm -f "$tmp"; return 1; }
}
# sim_cfg_data_wait: the seconds a second card chosen for the boot has to get its first data
# (network.$sim_wan.sim_data_wait, 300 by default; 0: never give it up). Anything else is the default.
sim_cfg_data_wait() {
local wait
wait=$(uci -q get network.$sim_wan.sim_data_wait 2>/dev/null || true)
case $wait in ''|*[!0-9]*|??????*) wait=300 ;; esac
printf '%s\n' "$wait"
}
# sim_cfg_auto_restart: 1 unless network.$sim_wan.sim_restart is '0'. The dual-SIM path restarts the device by itself in
# the two cases where nothing else brings the data back: a radio left in an unknown state, and a second card that
# was given up after the radio had been told to start it. With 0 those stay as they are until somebody reboots.
sim_cfg_auto_restart() {
if [ "$(uci -q get network.$sim_wan.sim_restart 2>/dev/null || true)" = 0 ]; then echo 0; else echo 1; fi
}
# sim_wan_up BEARER: netifd has the wan up, on BEARER, with an address. Reads netifd's status; no AT command.
sim_wan_up() {
local st
st=$(ubus call network.interface.$sim_wan status 2>/dev/null | tr -d ' \n\t') || return 1
case $st in *'"up":true'*) ;; *) return 1 ;; esac
case $st in *\"l3_device\":\"$1\"*|*\"device\":\"$1\"*) ;; *) return 1 ;; esac
case $st in *'"ipv4-address":[{'*|*'"ipv6-address":[{'*) return 0 ;; esac
return 1
}
# sim_wan_held_down: somebody took the wan down and it stays down until somebody brings it up (ifdown, the page's
# button): netifd's "autostart" is false then. Not the marker mobile-data leaves (/run/mu300-mobile-data-down): every
# failed dial of netifd's own goes through a teardown that leaves it for a moment (measured: a boot check that
# looked in that moment took a card netifd was dialling every minute for one nobody was dialling).
sim_wan_held_down() {
local st
st=$(ubus call network.interface.$sim_wan status 2>/dev/null | tr -d ' \n\t') || return 1
case $st in *'"autostart":false'*) return 0 ;; esac
return 1
}
# The data route. AT+SPSWDATA tells the modem which card carries packet data, and whether the modem forgets that
# at a restart was never measured. So the dual-SIM path leaves this mark before it gives the route to the second
# card, and the SIM1 dial (mobile-data) asks the modem, puts the route back and removes the mark. Without the mark
# nothing asks and nothing is sent: a device that never used the second card sees none of it.
sim_route_mark=$sim_config_root/etc/mu300/sim-data-route-2
sim_route_mark_set() { mkdir -p "${sim_route_mark%/*}" && : > "$sim_route_mark"; }
@@ -0,0 +1,72 @@
#!/bin/sh
# Event wait adapted from liuwang97/cpu-load ccf89bb6; local per-SIM semantics.
# Transport is ubus' compact JSON, never modem text or message contents.
sms_events=0 sms_event= sms_event_pid=
sms_clock() {
local up rest
IFS=' ' read -r up rest < /proc/uptime || return 1
SMS_NOW=${up%.*}
}
sms_events_stop() {
if [ -n "$sms_event_pid" ]; then
kill "$sms_event_pid" 2>/dev/null || true
wait "$sms_event_pid" 2>/dev/null || true
fi
[ "$sms_events" = 0 ] || exec 8<&-
sms_event_pid= sms_events=0
}
sms_events_start() {
ubus -t 2 list mu300.modem >/dev/null 2>&1 || return 1
local fifo=$LOCK/events
rm -f "$fifo"
mkfifo -m 600 "$fifo" || return 1
ubus -S listen mu300.modem.urc mu300.sim-state ubus.object.remove > "$fifo" 2>/dev/null </dev/null 8<&- 9<&- &
sms_event_pid=$!
exec 8< "$fifo"
rm -f "$fifo"
sms_events=1
}
# Only the physical bank owned by this receiver may trigger its import/ACK.
# NR6/7 are additional SIM0 command channels, not a third SIM.
sms_event_decode() {
sms_event=
case "$1" in
*'"ubus.object.remove"'*'"path":"mu300.modem"'*) sms_event=gone; return ;;
*'"mu300.sim-state"'*)
case "$1" in *'"slot":'"${MU300_SIM_SLOT:-0}"'}'*) sms_event=sim ;; esac
return ;;
*'"mu300.modem.urc"'*) ;;
*) return ;;
esac
case "${MU300_SIM_SLOT:-0}:$1" in
0:*'"channel":"stty_nr0"'*|0:*'"channel":"stty_nr1"'*|0:*'"channel":"stty_nr2"'*|0:*'"channel":"stty_nr6"'*|0:*'"channel":"stty_nr7"'*|1:*'"channel":"stty_nr3"'*|1:*'"channel":"stty_nr4"'*|1:*'"channel":"stty_nr5"'*) ;;
*) return ;;
esac
case "$1" in
*'"line":"+CMT (PDU spooled)"'*|*'"line":"+CMT (not spooled)"'*) sms_event=spool ;;
*'"line":"+CMTI:'*) sms_event=sync ;;
esac
}
# Wait until a relevant event or the real monotonic deadline. Unrelated radio
# traffic does not start processes, scan logs or move the safety-sync deadline.
sms_events_wait() {
local due=$1 line status
sms_event=
while :; do
sms_clock || return 1
[ "$SMS_NOW" -lt "$due" ] || return 0
status=0
IFS= read -r -t "$((due - SMS_NOW))" line <&8 || status=$?
if [ "$status" != 0 ]; then
sms_clock || return 1
# Bash's timer can fire just before /proc/uptime rounds up.
# Preserve the deadline; a real EOF still fails below.
[ "$status" != 142 ] || continue
[ "$SMS_NOW" -ge "$due" ] || { echo "mu300-smsd: modem event listener disconnected" >&2; return 1; }
return 0
fi
sms_event_decode "$line"
if [ "$sms_event" = gone ]; then echo "mu300-smsd: modem service disconnected" >&2; return 1; fi
[ -z "$sms_event" ] || return 0
done
}
@@ -0,0 +1,399 @@
// mu300.cellparse -- the cellular collector's readings, from the modem's answers to JSON (FINDINGS 206).
//
// Pure functions, no AT and no files: shared by the collector program (/usr/libexec/unisoc-modem/cell) and the modem
// daemon (/opt/mu300/bin/mu300-modemd), so both write the same sig.json and cell.json. They were the awk and sed
// fragments of the shell collector; each keeps that one's rules (comments below). busybox awk's 32-bit integers are
// no longer a concern (ucode's are 64-bit), but the cell ids stay strings, as the page expects them.
'use strict';
function safe_iface(name, dflt) {
return (type(name) == 'string' && match(name, /^[A-Za-z0-9][A-Za-z0-9_.-]*$/) && length(name) <= 15) ? name : dflt;
}
function safe_state_dir(path, dflt) {
if (type(path) != 'string' || !match(path, /^\/etc\/(unisoc-modem|mu300)(\/.*)?$/))
return dflt;
if (match(path, /\/\./) || index(path, '//') >= 0 || substr(path, -1) == '/' || match(path, /[^A-Za-z0-9_.\/-]/))
return dflt;
return path;
}
function data_cid(dev, slot) {
let m = match(dev, /^sipa_eth([0-9]+)$/);
if (!m)
return null;
let n = +m[1];
if (slot == '0' && n <= 7 && length(m[1]) == 1) return n + 1;
if (slot == '1' && ((n >= 8 && n <= 9 && length(m[1]) == 1) || (n >= 10 && n <= 15 && length(m[1]) == 2))) return n - 7;
return null;
}
const FINAL = /(^|\n)(OK|ERROR|\+CME ERROR|\+CMS ERROR|CONNECT|NO CARRIER)/;
function lines(text) { let l = split(text ?? '', '\n'); return filter(l, (x, i) => !(i == length(l) - 1 && x == '')); }
function first_with(text, prefix) {
for (let l in lines(text))
if (substr(l, 0, length(prefix)) == prefix)
return l;
return '';
}
function after_prefix(text, prefix) {
for (let l in lines(text))
if (substr(l, 0, length(prefix)) == prefix)
return ltrim(substr(l, length(prefix)), ' ');
return '';
}
function eng_line(text) {
for (let l in lines(text))
if (substr(l, 0, 2) != 'AT' && index(l, '-') >= 0)
return l;
return '';
}
function n_or_null(s) { return match(s ?? '', /^[0-9]+$/) ? +s : null; }
// ---------------------------------------------------------------- awk's numbers
// x+0 as awk takes it: the leading number of the text, 0 for none
function anum(x) {
let m = match('' + (x ?? ''), /^[ \t\n]*([-+]?([0-9]+\.?[0-9]*|\.[0-9]+)([eE][-+]?[0-9]+)?)/);
return m ? +m[1] : 0;
}
function fmt1(v) { return +sprintf('%.1f', v); }
// ------------------------------------------------------------- identity
// ident_token REPLY ERE: the first line of an identity answer that is the value alone, after an optional
// "+CGSN: "-like prefix and quotes; an error line ("+CME ERROR: 10") is never a value
function ident_token(reply, re) {
for (let l in lines(replace(replace(reply, /\r/g, ''), /"/g, ''))) {
if (match(l, /error/i))
continue;
l = rtrim(ltrim(replace(l, /^[+^][A-Za-z]*: */, ''), ' '), ' '); // (no replace() with a pattern that can match nothing: ucode repeats the text then)
if (match(l, re))
return l;
}
return '';
}
function iccid_value(v) {
v = replace(v, /[abcdef]/g, (c) => uc(c));
if (!match(v, /[^0-9F]/) && match(v, /[0-9]F$/)) {
v = substr(v, 0, length(v) - 1);
if (length(v) < 18)
v = '';
}
return v;
}
// ------------------------------------------------------------- own number
// cnum_number: the first number of an AT+CNUM answer, +CNUM: "alpha","number",type[,...]: digits (spaces, dashes and
// brackets dropped), 3 to 15 of them (E.164), "+" put in front for type 145 (international)
function cnum_number(text) {
for (let l in lines(text)) {
if (!match(l, /^\+CNUM:/))
continue;
let f = split(l, '"');
let n = replace(f[3] ?? '', /[ ()-]/g, '');
if (!match(n, /^\+?[0-9][0-9]+[0-9]$/))
continue;
let d = replace(n, /^\+/, '');
if (length(d) > 15)
continue;
if (match(f[4] ?? '', /^[ \t]*,[ \t]*145([ \t]*,|[ \t]*$)/) && !match(n, /^\+/))
n = '+' + n;
return n;
}
return '';
}
function ims_number(text) {
let sip = '';
for (let l in lines(text)) {
if (!match(l, /^\+SPPAURI:/))
continue;
l = replace(l, /^\+SPPAURI:[ \t]*/, '');
for (let uri in split(l, /[ \t",<>]+/)) {
let lower = lc(uri);
if (!match(lower, /^(tel|sips?):/))
continue;
let n = replace(replace(replace(uri, /^[^:]*:/, ''), /[@;?].*$/, ''), /[ ().-]/g, '');
let d = replace(n, /^\+/, '');
if (!match(d, /^[0-9]+$/) || length(d) < 3 || length(d) > 15)
continue;
if (match(lower, /^tel:/))
return n;
if (match(n, /^\+/) && sip == '')
sip = n;
}
}
return sip;
}
// ------------------------------------------------------------- SPENGMD decode
// Unisoc separates fields with "-" and writes negatives as "+<abs>":
// "1-300-211--11747--654" = band 1, EARFCN 300, PCI 211, RSRP -117.47, RSRQ -6.54.
// Normalize ",-" -> ",+" and "--" -> "-+" first, then split on "-". A token may
// carry a comma list (bandwidth codes, CA flags); the scalar is the first field.
// dB values are centi-units.
function norm(l) {
let s = replace(l, /\r/g, '');
s = replace(s, /,-/g, ',+');
s = replace(s, /--/g, '-+');
s = replace(s, /^-/, '+');
return map(split(s, '-'), (x) => replace(x, / /g, ''));
}
function f(x) {
let v = replace(replace(x ?? '', /,.*/, ''), /\+/g, '-');
return (v == '' || v == 'NA' || v == 'N/A') ? '' : anum(v);
}
function nnum(x) { return (x === '') ? null : x; }
function c1(x) { return (x === '') ? null : fmt1(x / 100.0); }
function fs_(x) {
let v = replace(x ?? '', /,.*/, '');
if (substr(v, 0, 1) == '+')
v = '' + (4294967296 - (+substr(v, 1) || 0));
return (v == '' || v == 'NA' || v == 'N/A') ? null : v;
}
function d(x) { return (x === '') ? 0 : int(x); }
const LTE_BANDS = [[1, 0, 599], [2, 600, 1199], [3, 1200, 1949], [4, 1950, 2399], [5, 2400, 2649], [6, 2650, 2749], [7, 2750, 3449], [8, 3450, 3799], [9, 3800, 4149], [10, 4150, 4749], [11, 4750, 4949], [12, 5010, 5179], [13, 5180, 5279], [14, 5280, 5379], [17, 5730, 5849], [18, 5850, 5999], [19, 6000, 6149], [20, 6150, 6449], [21, 6450, 6599], [22, 6600, 7399], [23, 7500, 7699], [24, 7700, 8039], [25, 8040, 8689], [26, 8690, 9039], [27, 9040, 9209], [28, 9210, 9659], [29, 9660, 9769], [30, 9770, 9869], [31, 9870, 9919], [32, 9920, 10359], [33, 36000, 36199], [34, 36200, 36349], [35, 36350, 36949], [36, 36950, 37549], [37, 37550, 37749], [38, 37750, 38249], [39, 38250, 38649], [40, 38650, 39649], [41, 39650, 41589], [42, 41590, 43589], [43, 43590, 45589], [44, 45590, 46589], [45, 46590, 46789], [46, 46790, 54539], [47, 54540, 55239], [48, 55240, 56739], [49, 56740, 58239], [50, 58240, 59089], [51, 59090, 59139], [52, 59140, 60139], [65, 65536, 66435], [66, 66436, 67335], [67, 67336, 67535], [68, 67536, 67835], [69, 67836, 68335], [70, 68336, 68585], [71, 68586, 68935], [72, 68936, 68985], [73, 68986, 69035], [74, 69036, 69465], [75, 69466, 70315], [76, 70316, 70365], [85, 70366, 70545]];
const NR_BANDS = [ [1,422000,434000],[3,361000,376000],[5,173800,178800],[8,185000,192000],[28,151600,160600],
[40,460000,480000],[41,499200,537999],[78,620000,653333],[77,620000,680000],[79,693334,733333] ];
function band_of(table, fr) {
for (let b in table)
if (fr >= b[1] && fr <= b[2])
return b[0];
return 0;
}
function eq0(x) { return x !== '' && x == 0; }
function sp_lte(line, phy) {
if (line == '')
return null;
let t = norm(line);
let band = f(t[0]), earfcn = f(t[1]), pci = f(t[2]);
if ((eq0(band) || band === '') && eq0(earfcn) && eq0(pci))
return null;
let bw = '';
if (t[7] != null && t[7] != '')
for (let c in split(t[7], ',')) {
let v = anum(c);
let w = (v == 0) ? '1.4' : (v == 1) ? '3' : (v == 2) ? '5' : (v == 3) ? '10' : (v == 4) ? '15' : (v == 5) ? '20' : null;
if (w != null)
bw += ((bw == '') ? '' : '+') + w + 'M';
}
let enb = f(t[11]), cidl = f(t[12]);
let tac = f(t[28]);
if (tac === '' || tac == 0)
tac = f(t[29]);
let ca = t[13] ?? '';
// 0,0,6 carries the LTE PHY: token 2 = SINR (centi-dB), 3/4 = the UL/DL MCS histograms (the dominant index is
// the live MCS), 5/6 = BLER. This device answers all zeros while camped on 5G SA (no LTE anchor), and an idle
// histogram is all zeros too - both mean "no reading", not "0 dB".
let psinr = null, pmcs = null, pumcs = null, publer = null, pdbler = null;
if (phy != '') {
let u = norm(phy);
let s2 = f(u[2]);
if (s2 !== '' && s2 >= -2000 && s2 <= 4000)
psinr = fmt1(s2 / 100.0);
publer = c1(f(u[5]));
pdbler = c1(f(u[6]));
for (let dir = 3; dir <= 4; dir++) {
let h = split(u[dir] ?? '', ','), best = -1, bestn = 0, total = 0;
if ((u[dir] ?? '') == '')
h = [];
for (let i = 0; i < length(h); i++) {
let hv = anum(h[i]);
total += hv;
if (hv > bestn) { bestn = hv; best = i; }
}
if (total > 0 && best >= 0) {
if (dir == 4) pmcs = best; else pumcs = best;
}
}
}
return { band: d(band), earfcn: d(earfcn), pci: d(pci), rsrp: c1(f(t[3])), rsrq: c1(f(t[4])), bw: bw,
enb: nnum(enb), cid: nnum(cidl), tac: (tac === '') ? '' : sprintf('%x', tac), ca: (index(ca, 'DL_CA') >= 0) ? 'DL_CA' : '',
sinr: psinr, dl_mcs: pmcs, ul_mcs: pumcs, dl_bler: pdbler, ul_bler: publer };
}
function sp_nr(line) {
if (line == '')
return null;
let t = norm(line);
let band = f(t[0]), arfcn = f(t[1]), pci = f(t[2]);
if ((eq0(band) || band === '') && eq0(arfcn) && eq0(pci))
return null;
return { band: d(band), arfcn: d(arfcn), pci: d(pci), rsrp: c1(f(t[3])), rsrq: c1(f(t[4])), sinr: c1(f(t[15])),
bw_mhz: nnum(f(t[7])), gnb: fs_(t[8]), cid: fs_(t[9]), ul_mcs: nnum(f(t[16])), dl_mcs: nnum(f(t[17])),
ul_bler: c1(f(t[18])), dl_bler: c1(f(t[19])) };
}
// eight 12-field slots, the first four EARFCN/PCI/RSRP/RSRQ
function sp_ltenb(line) {
if (line == '') return [];
let out = [];
for (let row in norm(line)) {
let t = split(row, ',');
if (length(t) < 4) continue;
let earfcn = f(t[0]), pci = f(t[1]);
if (eq0(earfcn) && eq0(pci)) continue;
push(out, {rat:'lte',band:band_of(LTE_BANDS, earfcn),arfcn:d(earfcn),pci:d(pci),rsrp:c1(f(t[2])),rsrq:c1(f(t[3]))});
}
return out;
}
// SPQ5GNCELLEX CSV: the serving 8-tuple, the count at index 8, then 8-tuples (arfcn, pci, rsrp, rsrq, sinr, ...)
function nr_neighbours(line, source) {
if (source == 'spengmd') {
let rows = map(norm(line), (row) => split(row, ',')), out = [];
if (length(rows) < 6) return out;
let count = min(...map(slice(rows,0,6), (r) => length(r)));
for (let i=0; i<count; i++) {
if (!match(rows[0][i], /^[0-9]+$/) || !match(rows[1][i], /^[0-9]+$/) || !match(rows[2][i], /^[0-9]+$/)) continue;
if (+rows[0][i] == 0 || +rows[1][i] == 0) continue;
let valid = true;
for (let j in [3,4,5]) if (!match(rows[j][i], /^\+?[0-9]+$/)) valid=false;
if (!valid) continue;
push(out,{rat:'nr',band:+rows[0][i],arfcn:+rows[1][i],pci:+rows[2][i],
rsrp:c1(f(rows[3][i])),rsrq:c1(f(rows[4][i])),sinr:c1(f(rows[5][i]))});
}
return out;
}
if (line == '')
return [];
let a = split(line, ','), m = length(a), cnt = anum(a[8]), out = [];
for (let i = 0; i < cnt && i < 8; i++) {
let b = 9 + i * 8; // awk's a[b+1] is a[b] here
if (b + 5 > m)
break;
let fr = anum(a[b]), pci = anum(a[b + 1]);
if (fr == 0 && pci == 0)
continue;
push(out, { rat: 'nr', band: (fr >= 620000 && fr <= 653333) ? null : (band_of(NR_BANDS, fr) || null),
band_candidates: (fr >= 620000 && fr <= 653333) ? [77,78] : [], arfcn: int(fr), pci: int(pci),
rsrp: fmt1(anum(a[b + 2]) / 100.0), rsrq: fmt1(anum(a[b + 3]) / 100.0), sinr: fmt1(anum(a[b + 4]) / 100.0) });
}
return out;
}
// registration line "+CEREG: 2,1,\"01F0\",\"0ABCD123\",13" -> stat/tac/cid/act
function reg_fragment(line) {
if (line == '')
return null;
let f = split(replace(replace(line, /^\+C5*EREG: */, ''), /"/g, ''), ',');
let rn = (x) => { x = replace(x ?? '', / /g, ''); return match(x, /^[0-9]+$/) ? +x : null; };
let rs = (x) => (x == null || x == '') ? null : x;
return { stat: rn(f[1]), tac: rs(f[2]), cid: rs(f[3]), act: rn(f[4]) };
}
// ---------------------------------------------------------------- operator
// cops_fragment COPS [NAMED CSCS] -> name/plmn/act. <format> 2 is the numeric PLMN, 0 and 1 a name. NAMED is the same
// answer in the long-name format (operator_name), CSCS the character set the modem said it uses. A name is read as
// UCS2 hex when the character set is UCS2, and then passed on as JSON \u escapes (valid UTF-16, no control
// character); under any other character set only a text that cannot reasonably be a name (issue #174) is read so.
function hexv(s) {
let v = 0;
for (let i = 0; i < length(s); i++)
v = v * 16 + index('0123456789ABCDEF', substr(s, i, 1));
return v;
}
function ucs2(s, strict) {
if (length(s) % 4 || !match(s, /^[0-9A-Fa-f]+$/))
return null;
if (strict && (length(s) < 8 || match(s, /^[0-9]+$/)))
return null;
let out = '', hi = false, units = [];
for (let i = 0; i < length(s); i += 4) {
let u = uc(substr(s, i, 4)), v = hexv(u);
if (v < 32 || (v >= 127 && v < 160))
return null;
if (strict && ((v >= 57344 && v <= 63743) || (v >= 64976 && v <= 65007) || v >= 65534))
return null;
if (v >= 55296 && v <= 56319) { if (hi) return null; hi = true; }
else if (v >= 56320 && v <= 57343) { if (!hi) return null; hi = false; }
else if (hi) return null;
push(units, v);
}
if (hi)
return null;
// the code units as text (what the \u escapes of the shell version decode to)
for (let i = 0; i < length(units); i++) {
let v = units[i];
if (v >= 55296 && v <= 56319) {
v = 65536 + ((v - 55296) << 10) + (units[i + 1] - 56320);
i++;
}
out += uchr(v);
}
return out;
}
function cops_parse(l) {
let m = match(l ?? '', /^\+COPS: *[0-9]+ *, *([0-9]+) *, *"([^"]*)"(.*)$/);
if (!m)
return null;
let a = replace(replace(m[3], /^ *, */, ''), /[^0-9].*$/, '');
return { F: m[1], T: m[2], A: a };
}
function name_json(t, cscs) {
if (t == '')
return null;
let u = ucs2(t, uc(cscs ?? '') != 'UCS2');
return (u != null) ? u : t;
}
function cops_fragment(line, named, charset) {
let m = match(line, /\+COPS: *([0-9]+), *([0-9]+), *"([^"]*)"(, *([0-9]+))?/);
if (!m) return null;
let name = m[3] || null;
if (name && (m[2]=='0' || m[2]=='1') && uc(charset ?? '')=='UCS2' && match(name,/^([0-9A-Fa-f]{4})+$/)) {
let decoded = ucs2(name);
if (decoded != null) name = decoded;
}
return {name:m[2]=='2' ? null : name,plmn:m[2]=='2' ? name : null,act:m[5]!=null ? int(m[5]) : null};
}
function cesq_fragment(line) {
if (line == '')
return null;
let f = split(replace(line, /^\+CESQ: */, ''), ',');
let f5 = f[4] ?? '', f6 = f[5] ?? '';
let rsrp = (f6 != '' && anum(f6) != 255) ? anum(f6) - 140 : null;
let rsrq = (f5 != '' && anum(f5) != 255) ? fmt1(-19.5 + anum(f5) * 0.5) : null;
return { rsrp: rsrp, rsrq: rsrq };
}
function qos_fragment(line) {
if (line == '')
return null;
let f = split(replace(replace(line, /OK$/, ''), /^\+CGEQOSRDP: */, ''), ',');
if (!match(trim(f[0] ?? ''), /^[0-9]+$/) || !match(trim(f[1] ?? ''), /^[0-9]+$/) || +f[1] < 1 || +f[1] > 255)
return null;
let v7 = f[6] ?? '', v8 = f[7] ?? '';
return { qci: int(anum(f[1])), dl: (v7 != '' && anum(v7) > 0) ? fmt1(anum(v7) / 1000.0) : null,
ul: (v8 != '' && anum(v8) > 0) ? fmt1(anum(v8) / 1000.0) : null };
}
// Engineering reads, neighbours and bearer QoS have no useful answer while the
// modem is searching/no-service. Skipping them avoids a chain of AT timeouts.
function reg_stat(l) { return replace(split(replace(l, /"/g, ''), ',')[1] ?? '', / /g, ''); }
export { safe_iface, safe_state_dir, data_cid, lines, first_with, after_prefix, eng_line, n_or_null, anum, fmt1,
ident_token, iccid_value, cnum_number, ims_number, norm, f, nnum, c1, fs_, d, band_of, eq0, sp_lte, sp_nr, sp_ltenb,
nr_neighbours, reg_fragment, hexv, ucs2, cops_parse, name_json, cops_fragment, cesq_fragment, qos_fragment, reg_stat,
LTE_BANDS, NR_BANDS, FINAL };
@@ -0,0 +1,84 @@
// Compatibility with lib/registration.sh: passive state from the one AT owner.
// Keep the on-disk schema and ubus events consumed by network recovery. No AT I/O.
import { readfile, open, mkdir, lstat, chmod, rename, unlink } from 'fs';
function cache(root, notify) {
function prepare() {
mkdir(root, 0700);
let s = lstat(root);
if (!s || s.type != 'directory' || s.uid != 0) return false;
return chmod(root, 0700);
}
function put(name, value) {
let path = root + '/' + name;
if (readfile(path) == value) return false;
if (!prepare()) return false;
let temp = path + '.modemd-part';
let f = open(temp, 'w', 0600);
if (!f) return false;
let ok = f.write(value) == length(value);
f.close();
if (ok && rename(temp, path)) return true;
unlink(temp);
return false;
}
function event(slot, line) {
if (slot != 0 && slot != 1) return false;
let m = match(line, /^\+ECIND:\s*([0-9]+(\s*,\s*[0-9]+)+)\s*$/);
if (!m) return false;
let fields = split(m[1], /\s*,\s*/);
for (let v in fields) if (length(v) > 10 || +v > 4294967295) return false;
let t = +fields[0], v = +fields[1], c = fields[2] != null ? +fields[2] : null;
if (t != 3 || (v == 1 ? index([1, 2, 7, 25, 34], c) < 0 : index([0, 2, 4, 100], v) < 0)) return false;
notify('mu300.sim-change', {slot});
return true;
}
function registration(slot, line, query) {
if (slot != 0 && slot != 1) return false;
let m = match(line, /^\+CEREG:\s*(.*)$/);
if (!m) return false;
let f = split(m[1], ','), s = trim(f[query ? 1 : 0] ?? ''), r = trim(f[query ? 4 : 3] ?? '');
if (!match(s, /^([0-9]|10)$/)) return false;
let rat = match(r, /^(0|[1-9][0-9]{0,2})$/) ? +r : null;
let value = sprintf('{"slot":%d,"stat":%d,"rat":%J}\n', slot, +s, rat);
if (!put('slot' + slot + '.json', value)) return false;
notify('mu300.registration', {slot});
return true;
}
function sim(slot, state) {
if (put('sim' + slot + '.json', sprintf('{"slot":%d,"state":%J}\n', slot, state)))
notify('mu300.sim-state', {slot});
}
function reply(command, text) {
let m = match(command, /^AT\+SPACTCARD=([01]);(\+CPIN\?|\+SFUN=[234]|\+CFUN=0|\+CFUN\?)$/);
if (!m) return;
let slot = +m[1], cmd = m[2], state = null, power = root + '/sim-power' + slot;
for (let line in split(replace(text, /\r/g, ''), '\n')) {
if (line == '+CFUN: 1') state = 'powered';
else if (line == '+CPIN: READY') state = 'ready';
else if (match(line, /^\+CPIN: (SIM PIN2?|SIM PUK2?|PH-.*)$/)) state = 'locked';
else if (line == '+CPIN: NOT INSERTED' || line == '+CPIN: SIM NOT INSERTED') state = 'absent';
else if (line == '+CME ERROR: 10' || line == '+CME ERROR: SIM not inserted') {
if (cmd == '+CPIN?' && lstat(power)) sim(slot, 'absent');
return;
}
else if (line == 'OK') {
if (cmd == '+SFUN=2' || cmd == '+SFUN=4' || (cmd == '+CFUN?' && state == 'powered')) put('sim-power' + slot, '');
else if (cmd == '+SFUN=3' || cmd == '+CFUN=0') {
unlink(power); unlink(root + '/sim' + slot + '.json');
}
else if (cmd == '+CPIN?' && index(['ready', 'locked', 'absent'], state) >= 0) {
if (state == 'absent' && !lstat(power)) return;
put('sim-power' + slot, ''); sim(slot, state);
}
return;
}
}
}
function reset(slot) {
if (slot != 0 && slot != 1) return;
for (let name in ['slot' + slot + '.json', 'sim' + slot + '.json', 'sim-power' + slot]) unlink(root + '/' + name);
}
return {event, registration, reply, reset};
}
export {cache};
@@ -0,0 +1,36 @@
// procd userspace placement only. No CPU hotplug, DVFS, IRQ or thermal writes.
import * as fs from 'fs';
export function apply(root,mode) {
if(!(mode in ['little','all']))return {ok:false,error:'Expected little or all'};
const group=root+'/sys/fs/cgroup', cpu=root+'/sys/devices/system/cpu';
function rd(p) { return trim(fs.readfile(p) || ''); }
if(!fs.stat(group+'/services'))return {ok:false,error:'procd services cgroup is unavailable'};
if(index(split(rd(group+'/cgroup.controllers'),/[ \t]+/),'cpuset')<0)
return {ok:false,error:'cpuset controller is required'};
let cpus=[], lowest=null;
for(let dir in fs.glob(cpu+'/cpu[0-9]*') || []) {
let value=rd(dir+'/cpu_capacity');
if(!match(value,/^[0-9]+$/))continue;
let capacity=+value;
if(lowest==null || capacity<lowest) {lowest=capacity;cpus=[];}
if(capacity==lowest && rd(dir+'/online')!='0')push(cpus,replace(dir,/.*\/cpu/,''));
}
if(mode=='little' && !length(cpus))return {ok:false,error:'No online little-cluster CPU was identified'};
if(index(split(rd(group+'/cgroup.subtree_control'),/[ \t]+/),'cpuset')<0 &&
!fs.writefile(group+'/cgroup.subtree_control','+cpuset\n'))
return {ok:false,error:'Unable to enable cpuset controller'};
let requested=mode=='all'?'':join(',',cpus), path=group+'/services/cpuset.cpus';
if(fs.writefile(path,requested+'\n')==null)return {ok:false,error:'Unable to set service CPUs'};
// The kernel normalizes a comma list into ranges. Compare CPU membership.
let applied=[];
for(let part in split(rd(path),',')) {
if(!part)continue;
let range=split(part,'-'), a=int(range[0]), b=int(range[1] ?? range[0]);
if(b-a>4096)return {ok:false,error:'Invalid cpuset readback'};
for(let n=a;n<=b;n++)push(applied,''+n);
}
let expected=mode=='all'?[]:cpus;
if(length(applied)!=length(expected) || length(filter(expected,n=>index(applied,n)<0)))
return {ok:false,error:'Service CPU readback differs'};
return {ok:true,mode,cpus:requested};
};
+4 -1
View File
@@ -3,11 +3,14 @@
// mu300-openwrt-base:25.12.5 /src/tests/dashboard_backport.uc
import { popen, writefile, mkdir, readfile } from 'fs';
if (getenv('MU300_TEST_CONTAINER') != '1') die('Disposable container required\n');
const lib = '/src/openwrt/luci-app-mu300/root/usr/libexec/unisoc-modem/';
const repo = ARGV[0] || '/src';
const lib = repo + '/openwrt/luci-app-mu300/root/usr/libexec/unisoc-modem/';
let checks = 0;
function check(ok, label) { if (!ok) die('FAIL: ' + label + '\n'); checks++; }
function quote(s) { return "'" + replace(s, /'/g, "'\\''") + "'"; }
function run(cmd) {
if (substr(cmd, 0, 6) == 'ucode ')
cmd = 'ucode -L ' + quote(repo + '/openwrt/luci-app-mu300/root/usr/share/ucode/*.uc') + ' ' + substr(cmd, 6);
const p = popen(cmd, 'r');
const out = p.read('all');
check(p.close() == 0, 'command: ' + cmd);
+3 -2
View File
@@ -31,10 +31,11 @@ writefile(dir + '/rates-test-ubus.uc',
" if(reply=='call-error')die('fixture RPC failure');\n" +
" return json(reply);\n" +
" }};\n};\n");
let source = readfile(repo + '/openwrt/luci-app-mu300/root/usr/libexec/unisoc-modem/dashboard-rates');
let source = readfile(repo + '/openwrt/luci-app-mu300/root/usr/share/ucode/mu300/rates.uc');
source = replace(source, "from 'ubus'", "from './rates-test-ubus.uc'");
source = replace(source, "'/sys/class/net/'", sprintf('%J', dir + '/net/'));
writefile(dir + '/rates.uc', source);
writefile(dir + '/sampler.uc', source);
writefile(dir + '/rates.uc', "import { sample } from './sampler.uc'; printf('%J\\n', sample());\n");
function sample(wan, configured) {
writefile('/etc/config/unisoc_modem', "config core 'main'\n option data_interface 'customwan'\n" +
(configured == null ? '' : " option data_device '" + configured + "'\n"));
+16
View File
@@ -0,0 +1,16 @@
"use strict";
const assert=require('assert'),fs=require('fs'),path=require('path');
const source=fs.readFileSync(path.join(__dirname,'../openwrt/luci-app-mu300/htdocs/luci-static/resources/mu300/common.js'),'utf8');
const code=source.slice(source.indexOf('var callRates ='),source.indexOf('var callCells ='));
let calls=[];
const failure=new Error('native service unavailable');
let reply=()=>Promise.resolve({available:true,device:'sipa_eth8',rx:123});
const rpc={declare:options=>()=>{calls.push(options.object);return reply();}};
const call=new Function('rpc',code+'return callRates;')(rpc);
(async()=>{
assert.strictEqual((await call()).device,'sipa_eth8');
reply=()=>Promise.resolve({available:false});assert.strictEqual((await call()).available,false);
reply=()=>Promise.reject(failure);await assert.rejects(call(),error=>error===failure);
assert.deepStrictEqual(calls,['mu300rates','mu300rates','mu300rates']);
console.log('rates: one native route, explicit failure, no alternative RPC');
})().catch(error=>{console.error(error);process.exitCode=1;});
+9 -17
View File
@@ -42,7 +42,7 @@ const tick=async()=>{for(let i=0;i<30;i++)await Promise.resolve();};
}
{
common.selectViewedSlot('0');
const state={ok:1,native:true,hot:0,ready:false,saved_sim:0,actual_sim:0,data_connected:true};
const state={ok:1,ready:false,saved_sim:0,actual_sim:0,data_connected:true};
const requests=[];
const M={injectCss(){},localizeMenu(){},translate:s=>s,
selectViewedSlot:common.selectViewedSlot,
@@ -51,9 +51,7 @@ const tick=async()=>{for(let i=0;i<30;i++)await Promise.resolve();};
if(o.method==='data_sim_get')return Promise.resolve({...state});
if(o.method==='data_sim_set') {
requests.push(target);
if(target.startsWith('u30-hot-'))state.hot=Number(target.slice(-1));
else if(target.startsWith('u30-default-'))state.saved_sim=Number(target.slice(-1));
else {state.actual_sim=Number(target);state.saved_sim=Number(target);}
state.actual_sim=Number(target);state.saved_sim=Number(target);
return Promise.resolve({ok:1,id:'abcdefghij'});
}
return Promise.resolve({id:'abcdefghij',state:'done',ok:1});
@@ -62,21 +60,15 @@ const tick=async()=>{for(let i=0;i<30;i++)await Promise.resolve();};
{extend:o=>o},rpc,{add(){},remove(){}},M,{createElement:element},{attach:()=>({refresh:()=>Promise.resolve(),dispose(){}})});
const root=view.render([{slots:2},{...state}]);
function all(n,tag){return (n.tag===tag?[n]:[]).concat(...n.children.map(c=>all(c,tag)));}
const [switchButton,saveButton]=all(root,'button');
const select=find(root,'select'), hot=find(root,'input');
assert(switchButton.disabled,'cold SIM1 boot must not offer an unprepared live switch');
assert(!select.disabled,'next-boot selection must remain available');
select.value='1';saveButton.onclick();await tick();
assert.deepEqual(requests,['u30-default-1']);
assert.equal(state.actual_sim,0,'saving boot preference must not change current radio');
assert.equal(common.selectedSlot(),'0','configuration does not change viewed slot');
hot.checked=true;hot.onchange();await tick();
assert.equal(requests[1],'u30-hot-1');
assert(switchButton.disabled,'enabling policy alone is not broker initialization');
const buttons=all(root,'button');
assert.equal(buttons.length,1,'U30 has no separate hot-switch policy controls');
const switchButton=buttons[0], select=find(root,'select');
assert(switchButton.disabled,'uninitialized dual stacks require cold boot');
assert(!select.disabled);
state.ready=true;await view.refresh();
assert(!switchButton.disabled,'ready state must enable the live control without a page reload');
select.value='1';switchButton.onclick();await tick();
assert.equal(requests[2],'1');
assert.deepEqual(requests,['1']);
assert.equal(common.selectedSlot(),'1');
view.unload();
}
@@ -106,5 +98,5 @@ const tick=async()=>{for(let i=0;i<30;i++)await Promise.resolve();};
physical.ready=false;await view.refresh();assert(button.disabled);
view.unload();
}
console.log('SIM UI: scoped RPC, U30 controls and four V50 hardware variants pass');
console.log('SIM UI: scoped RPC, shared U30 controls and four V50 hardware variants pass');
})().catch(e=>{console.error(e);process.exitCode=1;});
+25
View File
@@ -0,0 +1,25 @@
'use strict';
const assert=require('assert'),fs=require('fs'),path=require('path');
const source=fs.readFileSync(path.join(__dirname,'../openwrt/luci-app-mu300/htdocs/luci-static/resources/mu300/common.js'),'utf8');
const code=source.slice(source.indexOf('var smsWatch ='),source.indexOf('\nfunction confirmBox('));
let tick,slot='0',head={next_id:1,count:1,mtime:1},listCalls=0,fail=false,pending;
let msgs=[{id:1,dir:'mt',peer:'first',preview:'baseline'}],notifications=[];
const document={hidden:false},window={setInterval:fn=>{tick=fn;}};
const watch=new Function('window','document','selectedSlot','callSmsHead','callSmsList','notify',code+'return watchSms;')(
window,document,()=>slot,()=>pending || Promise.resolve(head),()=>{
listCalls++;return fail?Promise.reject(new Error('unavailable')):Promise.resolve({msgs});
},(...args)=>notifications.push(args));
const flush=async()=>{for(let n=0;n<20;n++)await Promise.resolve();};
(async()=>{
watch();watch();tick();await flush();assert.equal(listCalls,1);assert.equal(notifications.length,0);
tick();await flush();assert.equal(listCalls,1,'unchanged pool does not parse the message list');
head={next_id:2,count:2,mtime:2};msgs=[{id:2,dir:'mt',peer:'new',preview:'message'}];
fail=true;tick();await flush();assert.equal(listCalls,2);
fail=false;tick();await flush();assert.equal(listCalls,3);assert.equal(notifications.length,1);
tick();await flush();assert.equal(listCalls,3);assert.equal(notifications.length,1);
document.hidden=true;tick();await flush();assert.equal(listCalls,3);document.hidden=false;
let resolve;pending=new Promise(r=>{resolve=r;});tick();slot='1';resolve(head);await flush();
assert.equal(listCalls,3,'a late SIM0 signature must not read SIM1 messages');pending=null;
tick();await flush();assert.equal(listCalls,4);assert.equal(notifications.length,1,'SIM1 starts with its own baseline');
console.log('SMS signature watcher: unchanged, retry, visibility, SIM race and baseline passed');
})().catch(e=>{console.error(e);process.exitCode=1;});
+140
View File
@@ -0,0 +1,140 @@
/* Execute the production module against private MMIO and kernel API fixtures.
* No /dev/mem, kernel module loading or host register access. */
#include <assert.h>
#include <errno.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define __iomem
#define __init
#define __exit
#define BIT(n) (1U << (n))
#define HZ 100
#define module_param(...)
#define MODULE_PARM_DESC(...)
#define MODULE_LICENSE(...)
#define MODULE_DESCRIPTION(...)
#define module_init(...)
#define module_exit(...)
#define pr_info(...) ((void)0)
#define pr_warn(...) ((void)0)
#define DEFINE_SPINLOCK(n) int n
#define spin_lock_irqsave(lock, flags) ((void)(lock), (flags) = 0)
#define spin_unlock_irqrestore(lock, flags) ((void)(lock), (void)(flags))
typedef uint32_t u32;
typedef uintptr_t phys_addr_t;
struct device_node { int unused; };
struct work_struct { int unused; };
struct delayed_work { void (*fn)(struct work_struct *); int deferrable; };
struct syscore_ops { int (*suspend)(void *); void (*resume)(void *); };
struct syscore { const struct syscore_ops *ops; };
static u32 gic_regs[128], intc_regs[8][4], gate_reg;
static const uintptr_t bases[] = {
0x640c0000, 0x640d0000, 0x640e0000, 0x640f0000,
0x64100000, 0x64110000, 0x645b0000, 0x645c0000
};
static int compatible = 1, has_gic = 1, bad_gic_map, bad_gate_map;
static int bad_block = -1, maps, unmaps, writes, queues, registered, cancelled;
static unsigned long queued_delay;
static void *system_power_efficient_wq = (void *)1;
static struct device_node node;
static int of_machine_is_compatible(const char *s)
{ assert(!strcmp(s, "sprd,ums9620")); return compatible; }
static struct device_node *of_find_compatible_node(void *a, void *b, const char *s)
{ (void)a; (void)b; assert(!strcmp(s,"arm,gic-v3")); return has_gic ? &node : NULL; }
static void of_node_put(struct device_node *n) { assert(n == &node); }
static void *of_iomap(struct device_node *n, int index)
{ assert(n == &node && !index); if (bad_gic_map) return NULL; maps++; return gic_regs; }
static void *ioremap(uintptr_t address, unsigned size)
{
if (address == 0x64900008) {
assert(size == 4); if (bad_gate_map) return NULL; maps++; return &gate_reg;
}
for (int n=0; n<8; n++) if (address == bases[n]) {
assert(size == 0x10); assert(gate_reg & BIT(11+n));
if (n == bad_block) return NULL;
maps++; return intc_regs[n];
}
assert(!"unexpected MMIO address"); return NULL;
}
static void iounmap(void *p) { assert(p); unmaps++; }
static u32 readl_relaxed(void *p) { return *(u32 *)p; }
static u32 readl(void *p) { return readl_relaxed(p); }
static void writel_relaxed(u32 value, void *p)
{
for (int n=0; n<8; n++) {
assert((gate_reg & BIT(11+n)) || (p != &intc_regs[n][2] && p != &intc_regs[n][3]));
if (p == &intc_regs[n][2]) { intc_regs[n][2] |= value; writes++; return; }
if (p == &intc_regs[n][3]) { intc_regs[n][2] &= ~value; writes++; return; }
}
assert(!"write outside INTC set/clear registers");
}
#define INIT_DEFERRABLE_WORK(w, cb) ((w)->fn = (cb), (w)->deferrable = 1)
static void queue_delayed_work(void *q, struct delayed_work *w, unsigned long delay)
{ assert(q == system_power_efficient_wq && w->deferrable); queues++; queued_delay = delay; }
static void cancel_delayed_work_sync(struct delayed_work *w)
{ assert(w->deferrable); cancelled++; }
static void register_syscore(struct syscore *s)
{ assert(s->ops->suspend && s->ops->resume); registered++; }
static void unregister_syscore(struct syscore *s)
{ assert(s->ops); assert(cancelled); registered--; }
#include "../../upstream/modules/ums9620_lpintc/ums9620_lpintc.c"
int main(int argc, char **argv)
{
assert(argc == 2);
gate_reg = 0x7f800;
if (!strcmp(argv[1], "lifecycle")) {
u32 original[8] = {0xf5085c00, 0x2080b9fc, 0, 0, 0, 0, 0, 0x40};
for (int n=0; n<8; n++) intc_regs[n][2] = original[n];
gic_regs[0x104/4 + 4] = BIT(14) | BIT(8); /* USB + IPA */
gic_regs[0x104/4 + 6] = BIT(18); /* PCIe MSI */
assert(lpintc_init() == 0 && registered == 1);
assert(added[4] == (BIT(14)|BIT(8)) && added[6] == BIT(18));
assert(queued_delay == 5*HZ && queues == 1);
int first_writes = writes;
lpintc_work.fn(NULL);
assert(writes == first_writes && queues == 2); /* no repeated MMIO writes */
gic_regs[0x104/4 + 4] = 0;
gic_regs[0x104/4 + 2] = BIT(5); /* driver enabled later */
lpintc_work.fn(NULL);
assert(intc_regs[4][2] == (BIT(14)|BIT(8)) && added[2] == BIT(5));
intc_regs[3][2] = BIT(1); /* an unrelated owner adds a bit after load */
for (int i=0; i<3; i++) {
assert(lpintc_syscore.ops->suspend(NULL) == 0);
for (int n=0; n<8; n++)
assert(intc_regs[n][2] == (original[n] | (n==3 ? BIT(1) : 0)));
lpintc_syscore.ops->resume(NULL);
for (int n=0; n<8; n++)
assert(intc_regs[n][2] == (original[n] | added[n] | (n==3 ? BIT(1) : 0)));
}
lpintc_exit();
assert(!registered && cancelled == 1 && maps == unmaps);
for (int n=0; n<8; n++)
assert(intc_regs[n][2] == (original[n] | (n==3 ? BIT(1) : 0)));
} else if (!strcmp(argv[1], "clock-off")) {
gate_reg &= ~BIT(15);
gic_regs[0x104/4 + 4] = BIT(14);
period = 0;
assert(lpintc_init() == 0 && !intc[4] && !added[4]);
assert(period == 1 && queued_delay == HZ && !writes);
lpintc_exit(); assert(maps == unmaps);
} else {
int expected = -ENODEV;
if (!strcmp(argv[1], "wrong-soc")) compatible = 0;
else if (!strcmp(argv[1], "no-gic")) has_gic = 0;
else if (!strcmp(argv[1], "all-clocks-off")) gate_reg = 0;
else if (!strcmp(argv[1], "bad-gic")) { bad_gic_map=1; expected=-ENOMEM; }
else if (!strcmp(argv[1], "bad-gate")) { bad_gate_map=1; expected=-ENOMEM; }
else if (!strcmp(argv[1], "partial-map")) { bad_block=4; expected=-ENOMEM; }
else assert(!"unknown scenario");
assert(lpintc_init() == expected);
assert(!writes && !registered && !queues && maps == unmaps);
}
puts("OK");
return 0;
}
+43 -1
View File
@@ -13,6 +13,43 @@ from pathlib import Path
TOP = Path(__file__).resolve().parents[1]
BIN = TOP / 'rootfs' / 'overlay' / 'opt' / 'mu300' / 'bin'
GIT_CHECKOUT = bool(shutil.which('git')) and subprocess.run(
['git', '-C', str(TOP), 'rev-parse', '--git-dir'], capture_output=True).returncode == 0
UCODE_STUBS = TOP / 'tests/ucode-stubs'
UCODE_MODULES = TOP / 'openwrt/luci-app-mu300/root/usr/share/ucode'
UCODE_BASE_MODULES = TOP / 'rootfs/overlay/usr/share/ucode'
def ucode_paths():
return ['-L', f'{UCODE_STUBS}/*.uc', '-L', f'{UCODE_MODULES}/*.uc',
'-L', f'{UCODE_BASE_MODULES}/*.uc']
def ucode():
"""Use an explicitly selected interpreter, or the installed native one."""
import shlex
cmd = shlex.split(os.environ.get('MU300_TEST_UCODE', '')) or ([shutil.which('ucode')] if shutil.which('ucode') else [])
if not cmd:
return None
try:
if subprocess.run(cmd + ['-e', 'print(1)'], capture_output=True, timeout=10).returncode == 0:
return cmd
except (OSError, subprocess.TimeoutExpired):
pass
return None
def is_ucode(path):
try:
with open(path, 'rb') as f:
return f.readline().startswith(b'#!/usr/bin/ucode')
except OSError:
return False
def ucode_argv(path):
cmd = ucode()
return cmd + ucode_paths() + [str(path)] if cmd else None
def _works(argv):
@@ -82,4 +119,9 @@ class ShellTest(unittest.TestCase):
def each_shell(self):
for s in self.shells:
with self.subTest(shell=' '.join(s)):
yield s
try:
yield s
except GeneratorExit:
# The caller's skip/failure remains the test outcome; closing
# the iterator must not produce a second subtest error.
return
+69
View File
@@ -0,0 +1,69 @@
"""Execute production ucode with private files/UCI and deterministic netlink/RPC."""
import json
import os
import subprocess
import unittest
from pathlib import Path
from helpers import TOP, ucode
APP=TOP/'openwrt/luci-app-mu300/root'
DASH=APP/'usr/share/ucode/mu300/dash.uc'
class Snapshot:
def __init__(self, root):
self.root=Path(root);self.root.mkdir(parents=True,exist_ok=True)
self.module=self.root/'modules'; self.module.mkdir(exist_ok=True)
self.config=self.root/'config';self.config.mkdir(exist_ok=True)
self.responses={};self.stations=[];self.addresses=[]
for name,source in {
'bus':"export function connect(path,timeout) {return {call:(o,m,a)=>{let p=json(readfile(getenv('DASH_FIXTURE')+'/rpc.json'));writefile(getenv('DASH_FIXTURE')+'/last-call.json',sprintf('%J',{o,m,a,timeout}));return p[o+'.'+m] ?? null;}};};",
'nl':"export const constants={NL80211_CMD_GET_STATION:19,NLM_F_DUMP:768}; export function request(c,f,a) {return json(readfile(getenv('DASH_FIXTURE')+'/stations.json'));};",
'rt':"export const constants={RTM_GETADDR:22,NLM_F_DUMP:768,AF_INET:2,AF_INET6:10}; export function request(c,f,a) {return filter(json(readfile(getenv('DASH_FIXTURE')+'/addresses.json')),r=>r.family==a.family);};"
}.items():
(self.module/(name+'.uc')).write_text("import {readfile,writefile} from 'fs';\n"+source)
source=DASH.read_text().replace('nl.const.','nl.constants.').replace('rt.const.','rt.constants.')
for old,new in [('ubus','bus'),('nl80211','nl'),('rtnl','rt')]:
source=source.replace("from '"+old+"'","from './"+new+".uc'")
for name in ['hotspot','apn']:
source=source.replace("'/usr/libexec/unisoc-modem/"+name+".uc'",json.dumps(str(APP/'usr/libexec/unisoc-modem'/(name+'.uc'))))
(self.module/'dash.uc').write_text(source)
(self.module/'main.uc').write_text("import * as dash from './dash.uc'; let action=ARGV[0]; print(sprintf('%J\\n',dash[action](ARGV[1] ?? null,ARGV[2]=='cells')));\n")
self.write('proc/uptime','123.4 5\n')
self.write('proc/stat','cpu 10 0 5 85 0 0 0 0\n')
self.write('proc/cpuinfo','processor : 0\nprocessor : 1\n')
self.write('proc/meminfo','MemTotal: 1024 kB\nMemAvailable: 512 kB\n')
self.write('proc/sys/kernel/osrelease','7.2.8-fixture\n')
self.write('run/mu300/device','u30air\n')
self.write('tmp/sysinfo/model','Fixture board\n')
self.write('etc/openwrt_release',"DISTRIB_DESCRIPTION='Fixture OpenWrt'\n")
self.write('tmp/dhcp.leases','1000 E6:7A:77:59:7E:47 192.168.77.105 Xiaomi-17-Pro *\n1000 aa:bb:cc:dd:ee:ff 192.168.77.106 * *\n')
for dev in ['sipa_eth0','sipa_eth3','br-lan','wlan0','usb0']:
for path,value in [('statistics/rx_bytes','101'),('statistics/tx_bytes','202'),('operstate','up')]:
self.write('sys/class/net/'+dev+'/'+path,value+'\n')
self.setup_config()
self.responses={
'network.interface.wan.status':{'up':True,'l3_device':'sipa_eth3','proto':'mu300cell','uptime':42,'dns-server':['1.1.1.1']},
'network.interface.wan6.status':{'up':True,'dns-server':['2001:4860:4860::8888','1.1.1.1']},
'network.wireless.status':{'radio0':{'up':True,'interfaces':[{'section':'default_radio0','ifname':'wlan0'}]}},
'hostapd.wlan0.get_status':{'status':'ENABLED'},
'hostapd.wlan0.get_clients':{'clients':{}},
'mu300.modem.collect':{'started':1}}
self.addresses=[{'family':2,'dev':'br-lan','address':'192.168.1.1/24'},{'family':10,'dev':'sipa_eth3','address':'2001:db8::2/64'}]
def setup_config(self, extra=''):
(self.config/'unisoc_modem').write_text("config core 'main'\n option data_device 'sipa_eth0'\n option data_interface 'wan'\n option sim_slots '2'\n"+extra)
(self.config/'network').write_text("config interface 'wan'\n option proto 'mu300cell'\n option apn 'CMIOT5G'\n")
(self.config/'wireless').write_text("config wifi-device 'radio0'\n option channel '36'\n option band '5g'\n option htmode 'HE80'\n option country 'CN'\nconfig wifi-iface 'default_radio0'\n option mode 'ap'\n option device 'radio0'\n option ssid 'FixtureWiFi'\n option encryption 'psk2'\n")
def write(self, name, text):
p=self.root/name;p.parent.mkdir(parents=True,exist_ok=True);p.write_text(text);return p
def run(self, action='info', slot=None, cells=False):
cmd=ucode()
if not cmd:raise unittest.SkipTest('ucode runtime required; covered in disposable ARM64 container')
for name,value in [('rpc',self.responses),('stations',self.stations),('addresses',self.addresses)]:
(self.root/(name+'.json')).write_text(json.dumps(value))
env=dict(os.environ,MU300_DASH_SYSROOT=str(self.root),MU300_DASH_CONFIG=str(self.config),DASH_FIXTURE=str(self.root))
p=subprocess.run(cmd+[str(self.module/'main.uc'),action]+([] if slot is None else [slot])+(['cells'] if cells else []),env=env,capture_output=True,text=True,timeout=8)
if p.returncode:raise AssertionError(p.stderr)
return json.loads(p.stdout)
+46
View File
@@ -0,0 +1,46 @@
"""Refuse silently reused helpers when the architecture, source or bytes differ."""
import json
import runpy
import struct
import tempfile
import unittest
from pathlib import Path
from helpers import TOP
class Artifact(unittest.TestCase):
def test_static_arm64_and_fingerprint_validation(self):
api=runpy.run_path(str(TOP/'tools/atd-io/artifact.py'))
with tempfile.TemporaryDirectory() as folder:
p=Path(folder)/'bridge'
data=bytearray(64)
data[:6]=b'\x7fELF\x02\x01'
struct.pack_into('<H',data,18,183)
p.write_bytes(data)
meta=Path(str(p)+'.build.json')
record=api['inspect'](p)
meta.write_text(json.dumps(record))
api['check'](p)
p.write_bytes(data+b'changed')
with self.assertRaisesRegex(ValueError,'stale or modified'):api['check'](p)
p.write_bytes(data)
record['source_sha256']='old'
meta.write_text(json.dumps(record))
with self.assertRaisesRegex(ValueError,'stale or modified'):api['check'](p)
def test_wrong_architecture_dynamic_and_truncated_are_rejected(self):
api=runpy.run_path(str(TOP/'tools/atd-io/artifact.py'))
with tempfile.TemporaryDirectory() as folder:
p=Path(folder)/'bridge'
p.write_bytes(b'not ELF')
with self.assertRaisesRegex(ValueError,'AArch64'):api['inspect'](p)
data=bytearray(68)
data[:6]=b'\x7fELF\x02\x01'
struct.pack_into('<H',data,18,62)
p.write_bytes(data)
with self.assertRaisesRegex(ValueError,'AArch64'):api['inspect'](p)
struct.pack_into('<H',data,18,183)
struct.pack_into('<Q',data,32,64)
struct.pack_into('<HH',data,54,4,1)
struct.pack_into('<I',data,64,3)
p.write_bytes(data)
with self.assertRaisesRegex(ValueError,'statically'):api['inspect'](p)
+738
View File
@@ -0,0 +1,738 @@
"""mu300-atd-io (tools/atd-io/mu300-atd-io.c; docs/MODEMD.md, "The bridge protocol"): the C bridge that holds the
modem's AT channels and mu300-at's request FIFOs open for mu300-modemd. Built here with the machine's C compiler (Linux
only, else skipped) and driven through its socket: pseudo-terminals stand in for the SIPC channels (the bridge opens
the slave, the test is the modem on the master), real FIFOs for the request FIFOs, a file for /dev/sipc_sbuf. The rule
above all: a channel is never closed because of its client."""
import errno
import fcntl
import os
import select
import shutil
import signal
import socket
import stat
import struct
import subprocess
import sys
import tempfile
import termios
import time
import unittest
from pathlib import Path
from helpers import TOP
SRC = TOP / 'tools' / 'atd-io' / 'mu300-atd-io.c'
CC = shutil.which('gcc') or shutil.which('cc')
LINUX = sys.platform.startswith('linux')
BRIDGE = None
SIPC = None
_build = None
# Makes the bridge's ptys read like the SIPC pipes of the U30 Air (sprd spipe opened O_NONBLOCK): ENODATA where a pty
# says EAGAIN, and with MU300_TEST_NOTTY=1 not a terminal either (the stty_nr channels are misc devices, not ttys).
SIPC_SHIM = r'''
#define _GNU_SOURCE
#include <dlfcn.h>
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
static ssize_t (*real_read)(int, void *, size_t);
static int (*real_isatty)(int);
static int tty(int fd)
{
if (!real_isatty)
real_isatty = (int (*)(int))dlsym(RTLD_NEXT, "isatty");
return real_isatty(fd);
}
ssize_t read(int fd, void *b, size_t n)
{
if (!real_read)
real_read = (ssize_t (*)(int, void *, size_t))dlsym(RTLD_NEXT, "read");
ssize_t r = real_read(fd, b, n);
int e = errno;
if (r < 0 && e == EAGAIN && tty(fd))
e = ENODATA;
errno = e; /* isatty sets ENOTTY on anything else */
return r;
}
int isatty(int fd)
{
const char *e = getenv("MU300_TEST_NOTTY");
if (e && *e == '1')
return 0;
return tty(fd);
}
'''
def setUpModule():
global BRIDGE, SIPC, _build
if not (CC and LINUX):
return
_build = tempfile.mkdtemp(prefix='mu300-atd-io-build-')
out = Path(_build) / 'mu300-atd-io'
r = subprocess.run([CC, '-O2', '-Wall', '-Wextra', '-Werror', '-o', str(out), str(SRC)], capture_output=True, text=True)
if r.returncode != 0:
raise RuntimeError('mu300-atd-io.c does not build without warnings:\n' + r.stderr)
BRIDGE = out
shim = Path(_build) / 'sipc-shim.c'
shim.write_text(SIPC_SHIM)
r = subprocess.run([CC, '-O2', '-shared', '-fPIC', '-o', str(shim.with_suffix('.so')), str(shim), '-ldl'],
capture_output=True, text=True)
if r.returncode != 0:
raise RuntimeError('the SIPC shim does not build:\n' + r.stderr)
SIPC = shim.with_suffix('.so')
def tearDownModule():
if _build:
shutil.rmtree(_build, ignore_errors=True)
def h(b):
return b.hex().upper()
def fionread(fd):
return struct.unpack('i', fcntl.ioctl(fd, termios.FIONREAD, b'\0\0\0\0'))[0]
class Peer:
"""one client connection; records are str without their newline"""
def __init__(self, path):
end = time.monotonic() + 3
while True:
self.s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
try:
self.s.connect(str(path))
break
except (ConnectionRefusedError, FileNotFoundError): # between bind and listen, or not there yet
self.s.close()
if time.monotonic() > end:
raise
time.sleep(0.01)
self.buf = b''
self.eof = False
self.n = 0
def send(self, *records):
self.s.sendall(b''.join((r if isinstance(r, bytes) else r.encode()) + b'\n' for r in records))
def _fill(self, timeout):
if self.eof or not select.select([self.s], [], [], max(0.0, timeout))[0]:
return False
d = self.s.recv(1 << 20)
if not d:
self.eof = True
return False
self.buf += d
return True
def get(self, timeout=3.0):
"""the next record, or None when none comes within TIMEOUT"""
end = time.monotonic() + timeout
while b'\n' not in self.buf:
if not self._fill(end - time.monotonic()):
return None
line, self.buf = self.buf.split(b'\n', 1)
return line.decode('ascii')
def until(self, want, timeout=3.0):
"""the records up to and including WANT"""
seen = []
end = time.monotonic() + timeout
while True:
r = self.get(end - time.monotonic())
if r is None:
raise AssertionError(f'never came: {want!r}; came: {[s[:80] for s in seen]!r}')
seen.append(r)
if r == want:
return seen
def ping(self, timeout=3.0):
"""everything the bridge sent before it answered a PING"""
self.n += 1
self.send(f'PING t{self.n}')
return self.until(f'PONG t{self.n}', timeout)[:-1]
def closed_by_peer(self, timeout=3.0):
end = time.monotonic() + timeout
while not self.eof and time.monotonic() < end:
self._fill(end - time.monotonic())
return self.eof
def close(self):
self.s.close()
class Pty:
"""a fake channel: the bridge opens PATH (the slave), the test plays the modem on the master. The test keeps a
slave descriptor of its own, so that the pty lives on whatever the bridge does with its one."""
def __init__(self):
self.master, self.slave = os.openpty()
self.path = os.ttyname(self.slave)
os.set_blocking(self.master, False)
def write(self, data):
while data:
try:
data = data[os.write(self.master, data):]
except BlockingIOError:
select.select([], [self.master], [], 1)
def read(self, n, timeout=3.0):
out = b''
end = time.monotonic() + timeout
while len(out) < n and select.select([self.master], [], [], max(0.0, end - time.monotonic()))[0]:
try:
out += os.read(self.master, n - len(out))
except BlockingIOError:
pass
return out
def pending(self, quiet=0.2):
"""whatever the bridge writes until it has been quiet for QUIET seconds"""
out = b''
while select.select([self.master], [], [], quiet)[0]:
try:
out += os.read(self.master, 1 << 16)
except BlockingIOError:
pass
return out
def close_master(self):
if self.master >= 0:
os.close(self.master)
self.master = -1
def close(self):
self.close_master()
os.close(self.slave)
@unittest.skipUnless(CC and LINUX, 'needs a C compiler on Linux')
class Bridge(unittest.TestCase):
def setUp(self):
self.tmp = Path(tempfile.mkdtemp(prefix='mu300-atd-io-'))
self.sock = self.tmp / 'run' / 'io.sock'
self.sbuf = self.tmp / 'sipc_sbuf'
self.peers, self.ptys, self.procs = [], [], []
self.proc = self.start()
def start(self, log='stderr', **env):
err = open(self.tmp / log, 'wb')
p = subprocess.Popen([str(BRIDGE), '-s', str(self.sock)], stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL,
stderr=err, env=dict(os.environ, MU300_SIPC_SBUF=str(self.sbuf), **env))
err.close()
self.procs.append(p)
return p
def restart_as_sipc(self, notty):
"""the bridge again, reading its ptys as it reads the SIPC pipes"""
self.proc.kill()
self.proc.wait()
self.proc = self.start('stderr', LD_PRELOAD=str(SIPC), MU300_TEST_NOTTY='1' if notty else '0')
def tearDown(self):
for c in self.peers:
c.close()
for p in self.procs:
if p.poll() is None:
p.kill()
p.wait()
for t in self.ptys:
t.close()
shutil.rmtree(self.tmp, ignore_errors=True)
def stderr(self, log='stderr'):
return (self.tmp / log).read_text(errors='replace')
def connect(self, pid=None):
c = Peer(self.sock)
self.peers.append(c)
self.assertEqual(c.get(), f'HELLO 1 {pid or self.proc.pid}')
return c
def pty(self):
t = Pty()
self.ptys.append(t)
return t
def channel(self, c, name='nr1'):
t = self.pty()
c.send(f'OPEN {name} {t.path}')
c.until(f'STATE {name} {t.path} open')
return t
def fds_on(self, path):
"""the bridge's descriptors on PATH"""
d = f'/proc/{self.proc.pid}/fd'
out = []
for fd in os.listdir(d):
try:
if os.readlink(f'{d}/{fd}').removesuffix(' (deleted)') == str(path): # a pty without its master
out.append(int(fd))
except OSError:
pass
return out
def switches(self):
with open(f'/proc/{self.proc.pid}/status') as f:
return sum(int(line.split()[1]) for line in f if 'ctxt_switches:' in line)
def drained(self, fifo):
"""wait until the bridge has read everything written to FIFO"""
fd = os.open(fifo, os.O_RDONLY | os.O_NONBLOCK)
try:
end = time.monotonic() + 5
while fionread(fd):
self.assertLess(time.monotonic(), end, 'the bridge does not read its FIFO')
time.sleep(0.005)
finally:
os.close(fd)
def write_sbuf(self, text):
tmp = self.sbuf.with_suffix('.new')
tmp.write_text(text)
os.replace(tmp, self.sbuf)
class Connection(Bridge):
def test_hello_and_the_state_of_everything_held_on_every_connection(self):
c = self.connect()
self.assertEqual(stat.S_IMODE(self.sock.parent.stat().st_mode), 0o700)
st = os.lstat(self.sock)
self.assertTrue(stat.S_ISSOCK(st.st_mode))
self.assertEqual(stat.S_IMODE(st.st_mode), 0o600)
t = self.channel(c)
cmd = self.tmp / 'cmd'
c.send(f'FIFO nr1 {cmd}')
self.assertEqual(c.ping(), [f'STATE nr1 {cmd} open'])
# repeats change nothing and answer the state; another device under a known name changes nothing either
c.send(f'OPEN nr1 {t.path}', f'FIFO nr1 {cmd}', 'OPEN nr1 /dev/null')
self.assertEqual(c.ping(), [f'STATE nr1 {t.path} open', f'STATE nr1 {cmd} open', f'STATE nr1 {t.path} open'])
# a device another channel holds is refused: two readers of a SIPC channel would each get half of every reply
c.send(f'OPEN nr2 {t.path}', f'FIFO nr2 {cmd}')
self.assertEqual(c.ping(), [f'OPENFAIL nr2 {errno.EBUSY}', f'STATE nr2 {t.path} closed',
f'OPENFAIL nr2 {errno.EBUSY}', f'STATE nr2 {cmd} closed'])
self.assertEqual(len(self.fds_on(t.path)), 1)
c2 = self.connect()
self.assertEqual(c2.ping(), [f'STATE nr1 {t.path} open', f'STATE nr1 {cmd} open'])
self.assertIn(f'listening on {self.sock}', self.stderr())
def test_a_new_client_replaces_the_old_one_and_the_channel_stays_open(self):
c1 = self.connect()
t = self.channel(c1)
fds = self.fds_on(t.path)
self.assertEqual(len(fds), 1)
c2 = self.connect() # c1 still connected: it is the one that goes
self.assertEqual(c2.ping(), [f'STATE nr1 {t.path} open'])
self.assertTrue(c1.closed_by_peer())
t.write(b'one\r\n')
self.assertEqual(c2.get(), 'RX nr1 ' + h(b'one'))
# the client goes away, the modem keeps talking: the next client gets what was said meanwhile
c2.close()
t.write(b'two\r\n+CREG: 1\r\n')
c3 = self.connect()
self.assertEqual(c3.get(), f'STATE nr1 {t.path} open')
self.assertEqual(c3.get(), 'RX nr1 ' + h(b'two'))
self.assertEqual(c3.get(), 'RX nr1 ' + h(b'+CREG: 1'))
c3.send('TX nr1 ' + h(b'AT\r'))
self.assertEqual(t.read(3), b'AT\r')
self.assertEqual(self.fds_on(t.path), fds) # the same descriptor all along
self.assertNotIn('end of file', self.stderr())
self.assertIn('client replaced', self.stderr())
def test_a_client_that_stops_reading_is_dropped_and_the_channel_kept(self):
c = self.connect()
t = self.channel(c)
fds = self.fds_on(t.path)
t.write(b'X' * 100 + b'\r\n' + (b'Y' * 100 + b'\r\n') * 10000 + b'END\r\n') # 2 MB of records, unread
end = time.monotonic() + 10
while 'stopped reading' not in self.stderr():
self.assertLess(time.monotonic(), end, self.stderr())
time.sleep(0.01)
self.assertTrue(c.closed_by_peer())
c2 = self.connect()
seen = c2.until('RX nr1 ' + h(b'END'), timeout=10)
self.assertEqual(seen[0], f'STATE nr1 {t.path} open')
self.assertTrue(seen[1].startswith('DROPPED nr1 '), seen[1])
self.assertTrue(all(r == 'RX nr1 ' + h(b'Y' * 100) for r in seen[2:-1]))
self.assertEqual(self.fds_on(t.path), fds)
self.assertNotIn('end of file', self.stderr())
def test_malformed_records_are_ignored_with_one_line_each(self):
c = self.connect()
t = self.channel(c)
secret = h(b'1234 SECRET PIN').encode()
bad = [b'BOGUS nr1', b'TX nr1 ' + secret + b'5', b'TX nr1 ' + secret[:-2] + b'ZZ', b'TX NR1 41', b'TX nr1 41',
b'TX nr1 41 ', b'TX nr1', b'OPEN nr1', b'OPEN seventeen-chars-x /dev/null', b'OPEN nr2 dev/null',
b'OPEN nr2 /dev/null ready', b'OPEN nr2 /dev/null sbuf:a,b', b'FIFO nr2', b'CLOSE', b'PING', b'',
b'TX nr1 41\x01', b'TX nr1 \xc3\xa9', b'TX nr1 ' + b'41' * 70000]
c.send(*bad)
self.assertEqual(c.ping(), [])
self.assertEqual(t.pending(), b'') # nothing reached the channel
c.send(f'OPEN nr1 {t.path}')
self.assertEqual(c.ping(), [f'STATE nr1 {t.path} open'])
err = self.stderr()
self.assertEqual(err.count('record from the client, ignored'), len(bad), err)
self.assertNotIn(secret[:20].decode(), err)
self.assertNotIn('SECRET', err)
# past 20 lines per connection: one line that says so, then silence
c.send(*bad[:5])
self.assertEqual(c.ping(), [])
err = self.stderr()
self.assertEqual(err.count('record from the client, ignored'), 20)
self.assertEqual(err.count('not logged'), 1)
# none of them made a channel
c2 = self.connect()
self.assertEqual(c2.ping(), [f'STATE nr1 {t.path} open'])
class Channels(Bridge):
def test_rx_lines(self):
c = self.connect()
t = self.channel(c)
t.write(b'+CSQ: 23,99\r\nOK\r\n\r\nplain\n\x00\xff\x1a\r\r\n')
for line in (b'+CSQ: 23,99', b'OK', b'', b'plain', b'\x00\xff\x1a\r'):
self.assertEqual(c.get(), 'RX nr1 ' + h(line))
# a line in two writes is one line, without an RXP between them
t.write(b'+CRE')
time.sleep(0.05)
t.write(b'G: 1,5\r\n')
self.assertEqual(c.until('RX nr1 ' + h(b'+CREG: 1,5')), ['RX nr1 ' + h(b'+CREG: 1,5')])
# longer than 8192 bytes: in pieces
long = bytes(range(32, 127)) * 100
t.write(long + b'\r\n')
self.assertEqual(c.get(), 'RX nr1 ' + h(long[:8192]))
self.assertEqual(c.get(), 'RX nr1 ' + h(long[8192:]))
self.assertEqual(c.ping(), [])
def test_a_prompt_without_a_newline_goes_out_after_300_ms_of_quiet(self):
c = self.connect()
t = self.channel(c)
start = time.monotonic()
t.write(b'\r\n> ')
self.assertEqual(c.get(), 'RX nr1 ')
self.assertEqual(c.get(), 'RXP nr1 ' + h(b'> '))
took = time.monotonic() - start
self.assertGreaterEqual(took, 0.28)
self.assertLess(took, 1.5)
t.write(b'+CMGS: 5\r\n')
self.assertEqual(c.get(), 'RX nr1 ' + h(b'+CMGS: 5'))
# the wait starts again with every byte: a line that comes in pieces is not cut
start = time.monotonic()
t.write(b'abc')
time.sleep(0.2)
t.write(b'def')
self.assertEqual(c.get(), 'RXP nr1 ' + h(b'abcdef'))
self.assertGreaterEqual(time.monotonic() - start, 0.48)
def test_tx_bytes_reach_the_channel_exactly(self):
c = self.connect()
t = self.channel(c)
data = bytes(range(256)) + b'AT+CMGS=23\r0891\x1a'
c.send('TX nr1 ' + h(data))
self.assertEqual(t.read(len(data)), data)
c.send('TX nr1 ' + data.hex()) # lower case is hex too
self.assertEqual(t.read(len(data)), data)
c.send('TX nr1 ', 'TX nr9 41') # nothing to write; no such channel
self.assertEqual(c.ping(), [f'TXERR nr9 {errno.ENOENT}'])
self.assertEqual(t.pending(), b'')
def test_a_channel_that_does_not_take_a_tx_fails_it_after_2_s_and_stays_open(self):
c = self.connect()
t = self.channel(c)
chunk = 'TX nr1 ' + h(b'A' * 65536)
for _ in range(100): # until the pty's buffers are full
start = time.monotonic()
c.send(chunk)
got = c.ping(timeout=5)
if got:
break
took = time.monotonic() - start
self.assertEqual(got, [f'TXERR nr1 {errno.ETIMEDOUT}'])
self.assertGreaterEqual(took, 1.9)
self.assertLess(took, 3.5)
t.pending(quiet=0.3)
c.send('TX nr1 ' + h(b'Z\r'))
self.assertTrue(t.pending().endswith(b'Z\r'))
c.send(f'OPEN nr1 {t.path}')
self.assertEqual(c.ping(), [f'STATE nr1 {t.path} open'])
self.assertIn('a write failed', self.stderr())
self.assertNotIn('4141', self.stderr())
def test_end_of_file_closes_the_channel_for_good(self):
c = self.connect()
t = self.channel(c)
t.write(b'last\r\n')
c.until('RX nr1 ' + h(b'last'))
t.close_master()
seen = c.until(f'STATE nr1 {t.path} eof')
self.assertEqual(seen[-2:], ['EOF nr1', f'STATE nr1 {t.path} eof'])
self.assertEqual(self.fds_on(t.path), [])
time.sleep(0.25) # longer than an open retry: none comes
c.send('TX nr1 41', f'OPEN nr1 {t.path}')
self.assertEqual(c.ping(), [f'TXERR nr1 {errno.EBADF}', f'STATE nr1 {t.path} eof'])
self.assertIn('end of file', self.stderr())
# REOPEN opens it again (gone with its master: pending), CLOSE forgets it
c.send('REOPEN nr1')
got = c.ping()
self.assertEqual(got[0], f'STATE nr1 {t.path} pending')
self.assertTrue(got[1].startswith('OPENFAIL nr1 '), got)
c.send('CLOSE nr1')
self.assertEqual(c.ping(), [f'STATE nr1 {t.path} closed'])
c.send('CLOSE nr1') # again: nothing
self.assertEqual(c.ping(), [])
self.assertEqual(self.connect().ping(), [])
def test_a_drained_sipc_channel_reads_enodata_and_stays_open(self):
# the U30 Air, 2026-10-23: every channel read a line and then ENODATA, which closed all three for good
self.restart_as_sipc(notty=False)
c = self.connect()
t = self.channel(c)
for n in range(3):
t.write(b'+CEREG: %d\r\n' % n)
c.until('RX nr1 ' + h(b'+CEREG: %d' % n))
time.sleep(0.05)
t.write(b'> ')
c.until('RXP nr1 ' + h(b'> '))
c.send('TX nr1 ' + h(b'AT\r'))
self.assertTrue(t.pending().endswith(b'AT\r'))
self.assertEqual(c.ping(), [])
self.assertEqual(len(self.fds_on(t.path)), 1)
self.assertNotIn('end of file', self.stderr())
self.assertNotIn('read failed', self.stderr())
def test_a_sipc_channel_is_never_closed_by_a_read_and_does_not_spin(self):
self.restart_as_sipc(notty=True)
c = self.connect()
t = self.channel(c)
t.write(b'OK\n') # not a terminal: left cooked, where \r would be \n
c.until('RX nr1 ' + h(b'OK'))
t.close_master() # the slave now reads EIO and polls POLLHUP for ever
time.sleep(0.3)
before = self.switches()
time.sleep(1.2)
self.assertLess(self.switches() - before, 12) # one read a second, not a loop
self.assertEqual(c.ping(), []) # no EOF, no STATE
self.assertEqual(len(self.fds_on(t.path)), 1)
err = self.stderr()
self.assertEqual(err.count('kept open'), 1, err) # one line per new error
self.assertNotIn('end of file', err)
c.send('TX nr1 41') # the channel is still there to write to (the pty fails it)
got = c.ping()
self.assertTrue(all(r.startswith('TXERR nr1 ') for r in got), got)
self.assertNotIn(f'STATE nr1 {t.path} eof', got)
def test_a_device_that_appears_later_is_opened_by_the_retry(self):
c = self.connect()
dev = self.tmp / 'stty_nr4'
c.send(f'OPEN nr4 {dev}')
self.assertEqual(c.ping(), [f'STATE nr4 {dev} pending', f'OPENFAIL nr4 {errno.ENOENT}'])
time.sleep(0.45) # two retries: one OPENFAIL per pending period
self.assertEqual(c.ping(), [])
t = self.pty()
os.symlink(t.path, dev)
start = time.monotonic()
c.until(f'STATE nr4 {dev} open')
self.assertLess(time.monotonic() - start, 1.0)
t.write(b'OK\r\n')
self.assertEqual(c.get(), 'RX nr4 ' + h(b'OK'))
self.assertIn('opened after', self.stderr())
def test_ready_waits_for_the_sbuf_line(self):
c = self.connect()
t = self.pty()
self.write_sbuf('sbuf_5_006, state: 0, rxbuf 0\n xsbuf_5_006, state: 1,\nsbuf_5_0060, state: 1,\n'
'sbuf_5_006 state: 1,\n')
c.send(f'OPEN nr4 {t.path} sbuf:sbuf_5_006')
self.assertEqual(c.ping(), [f'STATE nr4 {t.path} pending', f'OPENFAIL nr4 {errno.ENODEV}'])
time.sleep(0.45)
self.assertEqual(c.ping(), [])
self.assertEqual(self.fds_on(t.path), []) # never opened before it is ready
self.write_sbuf('sbuf_5_005, state: 1, a\nsbuf_5_006, state: 1, rxbuf 0\n')
c.until(f'STATE nr4 {t.path} open')
self.assertEqual(len(self.fds_on(t.path)), 1)
# without the file at all it is never ready
os.unlink(self.sbuf)
t2 = self.pty()
c.send(f'OPEN nr5 {t2.path} sbuf:sbuf_5_007')
self.assertEqual(c.ping(), [f'STATE nr5 {t2.path} pending', f'OPENFAIL nr5 {errno.ENOENT}'])
def test_no_wakeups_while_nothing_is_pending(self):
c = self.connect()
t = self.channel(c)
c.send(f'FIFO nr1 {self.tmp}/cmd')
c.until(f'STATE nr1 {self.tmp}/cmd open')
t.write(b'> ')
c.until('RXP nr1 ' + h(b'> '))
before = self.switches()
time.sleep(0.5)
self.assertEqual(self.switches(), before)
# a pending open is tried every 200 ms
c.send(f'OPEN nr5 {self.tmp}/missing')
c.ping()
before = self.switches()
time.sleep(0.5)
self.assertGreaterEqual(self.switches() - before, 2)
class Fifos(Bridge):
def test_requests_from_the_fifo(self):
c = self.connect()
d = self.tmp / 'at'
d.mkdir()
cmd = d / 'cmd'
c.send(f'FIFO nr1 {cmd}')
self.assertEqual(c.ping(), [f'STATE nr1 {cmd} open'])
st = os.lstat(cmd)
self.assertTrue(stat.S_ISFIFO(st.st_mode))
self.assertEqual(stat.S_IMODE(st.st_mode), 0o600)
# another process writes a request, the way mu300-at does
subprocess.run(['sh', '-c', 'printf "6 %s AT+CSQ\\n" "$2" > "$1"', 'sh', str(cmd), f'{d}/answer.1'],
check=True, timeout=5)
self.assertEqual(c.get(), 'REQ nr1 ' + h(f'6 {d}/answer.1 AT+CSQ'.encode()))
# a CR inside (the PDU send) and an empty line pass as they are; a line over 8192 bytes is dropped
with open(cmd, 'wb', buffering=0) as w:
w.write(b'9 /x AT+CMGS=23\r0891\x1a\n\n' + b'A' * 9000 + b'\nafter\n')
self.assertEqual(c.get(), 'REQ nr1 ' + h(b'9 /x AT+CMGS=23\r0891\x1a'))
self.assertEqual(c.get(), 'REQ nr1 ')
self.assertEqual(c.get(), 'REQ nr1 ' + h(b'after'))
self.assertIn('longer than 8192 bytes, dropped', self.stderr())
self.assertNotIn('AAAA', self.stderr())
# a request while no client is connected waits for the next one
c.close()
subprocess.run(['sh', '-c', 'printf "7 /x AT+COPS?\\n" > "$1"', 'sh', str(cmd)], check=True, timeout=5)
self.drained(cmd)
c2 = self.connect()
self.assertEqual(c2.get(), f'STATE nr1 {cmd} open')
self.assertEqual(c2.get(), 'REQ nr1 ' + h(b'7 /x AT+COPS?'))
def test_an_existing_fifo_is_kept_and_anything_else_replaced(self):
c = self.connect()
keep = self.tmp / 'keep'
os.mkfifo(keep, 0o644)
ino = os.lstat(keep).st_ino
c.send(f'FIFO a {keep}')
c.until(f'STATE a {keep} open')
self.assertEqual(os.lstat(keep).st_ino, ino)
self.assertEqual(stat.S_IMODE(os.lstat(keep).st_mode), 0o600)
regular, link = self.tmp / 'regular', self.tmp / 'link'
regular.write_text('x')
os.symlink(self.tmp / 'target', link)
for name, p in (('b', regular), ('c', link)):
c.send(f'FIFO {name} {p}')
c.until(f'STATE {name} {p} open')
self.assertTrue(stat.S_ISFIFO(os.lstat(p).st_mode))
self.assertFalse(os.path.lexists(self.tmp / 'target'))
# one that cannot be made
c.send(f'FIFO d {self.tmp}/no/such/cmd')
self.assertEqual(c.ping(), [f'OPENFAIL d {errno.ENOENT}', f'STATE d {self.tmp}/no/such/cmd closed'])
# removed under the bridge: a repeat makes it again, and requests come through the new one
os.unlink(keep)
c.send(f'FIFO a {keep}')
c.until(f'STATE a {keep} open')
with open(keep, 'wb', buffering=0) as w:
w.write(b'again\n')
self.assertEqual(c.get(), 'REQ a ' + h(b'again'))
# CLOSE removes it
c.send('CLOSE a')
self.assertEqual(c.ping(), [f'STATE a {keep} closed'])
self.assertFalse(os.path.lexists(keep))
class Queue(Bridge):
def test_1024_records_per_name_and_256_kib_in_all_while_no_client_is_connected(self):
c = self.connect()
q = self.tmp / 'q'
c.send(f'FIFO q {q}')
c.until(f'STATE q {q} open')
c.close()
with open(q, 'wb', buffering=0) as w:
w.write(b''.join(b'R%d\n' % i for i in range(1100)))
self.drained(q)
c2 = self.connect()
self.assertEqual(c2.get(), f'STATE q {q} open')
self.assertEqual(c2.get(), 'DROPPED q 76')
for i in range(76, 1100):
self.assertEqual(c2.get(), 'REQ q ' + h(b'R%d' % i))
self.assertEqual(c2.ping(), [])
self.assertIn('76 records of q were dropped', self.stderr())
# 16 records of 16007 bytes fit in 256 KiB, the 24 before them do not
c2.close()
with open(q, 'wb', buffering=0) as w:
for i in range(40):
w.write(b'%02d' % i + b'B' * 7998 + b'\n')
self.drained(q)
c3 = self.connect()
self.assertEqual(c3.get(), f'STATE q {q} open')
self.assertEqual(c3.get(), 'DROPPED q 24')
for i in range(24, 40):
self.assertEqual(c3.get(), 'REQ q ' + h(b'%02d' % i + b'B' * 7998))
self.assertEqual(c3.ping(), [])
class Stop(Bridge):
def test_sigterm_closes_everything_and_exits_0(self):
c = self.connect()
self.channel(c)
cmd = self.tmp / 'cmd'
c.send(f'FIFO nr1 {cmd}')
c.until(f'STATE nr1 {cmd} open')
self.proc.send_signal(signal.SIGTERM)
self.assertEqual(self.proc.wait(timeout=5), 0)
self.assertTrue(c.closed_by_peer())
self.assertFalse(os.path.lexists(self.sock))
self.assertFalse(os.path.lexists(cmd))
self.assertIn('stopping', self.stderr())
def test_a_second_instance_waits_for_the_first(self):
c = self.connect()
second = self.start('stderr2')
end = time.monotonic() + 5
while 'waiting for it to end' not in self.stderr('stderr2'):
self.assertLess(time.monotonic(), end, self.stderr('stderr2'))
time.sleep(0.01)
self.assertEqual(c.ping(), []) # the first one still serves
self.proc.send_signal(signal.SIGINT)
self.assertEqual(self.proc.wait(timeout=5), 0)
end = time.monotonic() + 5
while True: # the socket of the first may still be there for a moment
try:
c2 = Peer(self.sock)
first = c2.get()
if first == f'HELLO 1 {second.pid}':
break
c2.close()
except OSError:
pass
self.assertLess(time.monotonic(), end)
time.sleep(0.01)
self.peers.append(c2)
second.send_signal(signal.SIGTERM)
self.assertEqual(second.wait(timeout=5), 0)
class Wiring(unittest.TestCase):
"""the images get the bridge the way they get mu300-keys: built static in the release and the installer, put into
/opt/mu300/bin by both root filesystem builds"""
def test_built_and_installed(self):
for script, d in (('tools/make-release.sh', '$IN'), ('install.sh', '$WORK')):
text = (TOP / script).read_text()
self.assertIn(f'sh "$TOP/tools/atd-io/build.sh" "{d}/tools/atd-io"', text)
self.assertIn(f'-v "{d}/tools/atd-io/mu300-atd-io":/atd-io:ro', text)
assemble = (TOP / 'rootfs/assemble.sh').read_text()
self.assertIn('if [ -e /atd-io ]; then install -m755 /atd-io $R/opt/mu300/bin/mu300-atd-io; fi', assemble)
owrt = (TOP / 'openwrt/build-rootfs.sh').read_text()
self.assertIn('$(opt tools/atd-io/mu300-atd-io atd-io)', owrt)
self.assertIn('[ -e /in/atd-io ] && { cp /in/atd-io $R/opt/mu300/bin/mu300-atd-io; '
'chmod 755 $R/opt/mu300/bin/mu300-atd-io; }', owrt)
if __name__ == '__main__':
unittest.main()
+122
View File
@@ -0,0 +1,122 @@
"""Boot ordering and readiness checks with private command/file fixtures only."""
import json
import os
import subprocess
import tempfile
import unittest
from pathlib import Path
from helpers import TOP, BIN, ShellTest, ucode
class HardwareOrdering(ShellTest):
def setUp(self):
super().setUp()
for name in ['led-status','extra-modules','zram-start','wifi-start','regdb-load','openwrt-wifi-config','mu300-nfc']:
self.stub(name,'echo "'+name+'" >> "$STUBLOG/order"\nexit 0')
self.stub('openwrt-board-check','echo board-check >> "$STUBLOG/order"; exit "${BOARD_FAIL:-0}"')
self.stub('wifi-ready','exit "${READY_FAIL:-0}"')
self.stub('uci','echo CN')
self.stub('iw','echo "iw:$*" >> "$STUBLOG/order"; echo "country CN:"')
self.stub('wifi','echo "wifi:$*" >> "$STUBLOG/order"')
self.stub('sha256sum','echo "${CONFIG_HASH:-same}"')
source=(TOP/'openwrt/overlay/etc/init.d/mu300-hw').read_text()
source=source.replace('/tmp/mu300-',str(self.tmp)+'/mu300-').replace('/opt/mu300/bin/',str(self.stubs)+'/')
source=source.replace('sha256sum ',str(self.stubs/'sha256sum')+' ')
self.code=source+'\nhw_bringup\n'
def test_rules_precede_phy_and_ready_ap_is_not_restarted(self):
for shell in self.each_shell():
(self.tmp/'order').unlink(missing_ok=True)
r=self.sh(shell,self.code);self.assertEqual(r.returncode,0,r.stderr)
events=(self.tmp/'order').read_text().splitlines()
self.assertLess(events.index('board-check'),events.index('wifi-start'))
self.assertLess(events.index('regdb-load'),events.index('wifi-start'))
self.assertLess(events.index('wifi-start'),events.index('extra-modules'))
self.assertNotIn('wifi:down',events);self.assertNotIn('wifi:up',events)
def test_unready_ap_reconciles_once_and_invalid_board_stops_bringup(self):
for shell in self.each_shell():
for fail in [0,1]:
(self.tmp/'order').unlink(missing_ok=True)
r=self.sh(shell,self.code,READY_FAIL=1,BOARD_FAIL=fail)
events=(self.tmp/'order').read_text().splitlines()
if fail:self.assertNotEqual(r.returncode,0);self.assertNotIn('wifi-start',events)
else:self.assertEqual(events.count('wifi:down'),1);self.assertEqual(events.count('wifi:up'),1)
class WirelessReadiness(unittest.TestCase):
def test_all_enabled_interfaces_and_user_disabled_radio(self):
from native_dashboard_fixture import Snapshot
cmd=ucode()
if not cmd:self.skipTest('ucode required')
with tempfile.TemporaryDirectory() as td:
s=Snapshot(td)
source=(BIN/'wifi-ready').read_text().replace("from 'ubus'","from './bus.uc'")
source=source.replace('cursor()','cursor(getenv("MU300_DASH_CONFIG"))')
script=s.module/'wifi-ready';script.write_text(source)
def run():
(s.root/'rpc.json').write_text(json.dumps(s.responses))
return subprocess.run(cmd+[str(script)],env=dict(os.environ,MU300_DASH_CONFIG=str(s.config),DASH_FIXTURE=td),capture_output=True,text=True,timeout=5)
self.assertEqual(run().returncode,0)
s.responses['hostapd.wlan0.get_status']={'status':'DISABLED'};self.assertEqual(run().returncode,1)
s.responses['network.wireless.status']['radio0']['pending']=True;self.assertEqual(run().returncode,1)
(s.config/'wireless').write_text("config wifi-device 'radio0'\n option disabled '1'\n")
self.assertEqual(run().returncode,0,'a disabled radio must stay disabled without a global restart')
class BootContracts(unittest.TestCase):
def test_device_entrypoints_have_unix_line_endings(self):
for name in ['boot/init','openwrt/build-rootfs.sh',
'openwrt/overlay/etc/init.d/mu300-hw',
'openwrt/overlay/etc/init.d/mu300-service-cpus',
'rootfs/overlay/opt/mu300/bin/mu300-led',
'rootfs/overlay/opt/mu300/bin/mu300-modemd',
'rootfs/overlay/opt/mu300/bin/mu300-service-cpus',
'rootfs/overlay/opt/mu300/bin/wifi-ready',
'rootfs/overlay/opt/mu300/bin/sipa-dele-start']:
self.assertNotIn(b'\r\n',(TOP/name).read_bytes(),name)
def test_recovery_and_full_resume_wait_are_retained(self):
init=(TOP/'boot/init').read_text()
self.assertNotIn('.kmodloader-once',init)
self.assertIn('head -c 1 /dev/random',init)
self.assertIn('echo 4 > /proc/sys/kernel/printk',init)
driver=(TOP/'upstream/port/drivers/pci/controller/dwc/pcie-sprd.c').read_text()
probe=driver[driver.index('static int sprd_pcie_probe('):]
self.assertIn('sprd_pcie_link_up_soon(pci)',probe)
self.assertIn('dw_pcie_wait_for_link(pci)',driver[:driver.index('static int sprd_pcie_probe(')])
self.assertIn('sprd_pcie_clear_unhandled_msi',driver)
self.assertFalse((TOP/'openwrt/overlay/lib/preinit/31_mu300_failsafe_wait').exists())
class DelegateReadiness(ShellTest):
def setUp(self):
super().setUp()
(self.tmp/'modules').mkdir();(self.tmp/'modules/sipa-dele.ko').write_text('test file only')
(self.tmp/'loaded-modules').write_text('');(self.tmp/'tty').touch()
self.stub('dmesg',"echo 'sprd-sbuf: channel 5-1'\n[ \"${HANDSHAKE:-1}\" != 1 ] || echo 'channel 5-120 send open msg'")
self.stub('mu300-at',"[ \"$MU300_AT_DAEMON_ONLY\" = 1 ] || exit 99; printf '+CGATT: %s\\n' \"${ATTACHED:-1}\"")
self.stub('insmod','echo load >> "$STUBLOG/loads"; exit "${LOAD_FAIL:-0}"')
self.stub('sleep','echo "$1" >> "$STUBLOG/sleeps"; echo "1.0 0" > "$STUBLOG/uptime"')
source=(BIN/'sipa-dele-start').read_text()
source=source.replace('/lib/modules/$(uname -r)',str(self.tmp/'modules'))
source=source.replace('/proc/modules',str(self.tmp/'loaded-modules')).replace('/proc/uptime',str(self.tmp/'uptime'))
source=source.replace('/dev/stty_nr1',str(self.tmp/'tty')).replace('[ -c ','[ -f ')
for command in ['mu300-at','insmod','dmesg','sleep']:
source=source.replace(command+' ',str(self.stubs/command)+' ')
self.code=source
def run_delegate(self,shell,**env):
for name in ['loads','sleeps']:(self.tmp/name).unlink(missing_ok=True)
(self.tmp/'uptime').write_text('0.0 0')
return self.sh(shell,self.code,MU300_DELE_WAIT=1,**env)
def test_packet_attach_and_handshake_finish_without_fixed_delay(self):
for shell in self.each_shell():
p=self.run_delegate(shell)
self.assertEqual(p.returncode,0,p.stderr)
self.assertEqual((self.tmp/'loads').read_text().splitlines(),['load'])
self.assertFalse((self.tmp/'sleeps').exists())
def test_no_packet_attach_never_loads_and_load_failure_is_not_success(self):
for shell in self.each_shell():
p=self.run_delegate(shell,ATTACHED=0)
self.assertNotEqual(p.returncode,0);self.assertFalse((self.tmp/'loads').exists())
p=self.run_delegate(shell,LOAD_FAIL=1)
self.assertNotEqual(p.returncode,0);self.assertNotIn('channel open sent',p.stdout)
+42
View File
@@ -0,0 +1,42 @@
"""Execute initramfs eMMC polling with file fixtures, never block devices."""
from helpers import TOP, ShellTest
class PartitionWait(ShellTest):
def setUp(self):
super().setUp()
source=(TOP/'boot/init').read_text()
loop=source.split('find_partitions() {',1)[1].split(' detect_linux_slot',1)[0]
# Isolate the real readiness loop before slot detection and writes.
self.loop='poll() {'+loop.replace('/sys/class/block',str(self.tmp/'block')).replace('/dev/',str(self.tmp/'dev')+'/').replace('-b "$misc"','-f "$misc"')+'\n}\npoll\n'
block=self.tmp/'block/mmcblk0p1';block.mkdir(parents=True)
(block/'uevent').write_text('PARTNAME=misc\n')
(self.tmp/'dev').mkdir()
self.stub('usleep','[ "${WAIT_FAST:-1}" = 1 ] || exit 1\n[ "$1" != 0 ] || exit 0\necho fast >> "$STUBLOG/waits"\n[ "${WAIT_READY:-0}" != 1 ] || touch "$STUBLOG/dev/mmcblk0p1"\nexit 0')
self.stub('sleep','echo slow >> "$STUBLOG/waits"\n[ "${WAIT_READY:-0}" != 1 ] || touch "$STUBLOG/dev/mmcblk0p1"\nexit 0')
self.stub('mdev','echo scan >> "$STUBLOG/scans"')
# Standalone ash may prefer built-in applets over PATH. Keep every
# delay/scan inside the fixture, including the zero-duration probe.
self.loop=self.loop.replace('usleep ',str(self.stubs/'usleep')+' ')
self.loop=self.loop.replace('else sleep 1;', 'else '+str(self.stubs/'sleep')+' 1;')
self.loop=self.loop.replace('mdev -s',str(self.stubs/'mdev')+' -s')
def run_poll(self,shell,fast=1,ready=0):
for name in ['waits','scans','dev/mmcblk0p1']:(self.tmp/name).unlink(missing_ok=True)
result=self.sh(shell,self.loop,WAIT_FAST=fast,WAIT_READY=ready)
self.assertEqual((result.returncode,result.stderr),(0,''))
return [(self.tmp/name).read_text().splitlines() if (self.tmp/name).exists() else [] for name in ['waits','scans']]
def test_fast_and_unsupported_usleep_have_same_timeout_and_scan_budget(self):
for shell in self.each_shell():
for fast,count,kind in [(1,200,'fast'),(0,20,'slow')]:
waits,scans=self.run_poll(shell,fast=fast)
self.assertEqual(waits,[kind]*count)
self.assertEqual(scans,['scan']*20)
def test_ready_partition_exits_after_first_wait_in_either_mode(self):
for shell in self.each_shell():
for fast in [0,1]:
waits,scans=self.run_poll(shell,fast=fast,ready=1)
self.assertEqual(len(waits),1)
self.assertEqual(len(scans),0 if fast else 1)
+43
View File
@@ -0,0 +1,43 @@
"""Local dashboard semantics on the imported pure ucode parser."""
import json
import subprocess
import unittest
from helpers import ucode, ucode_paths
from test_dashboard_neighbors import NR_REPLY, LTE_REPLY
@unittest.skipUnless(ucode(), 'ucode required')
class CellParser(unittest.TestCase):
def call(self,name,*args):
code="import * as cp from 'mu300.cellparse'; print(sprintf('%J', cp."+name+"("+','.join(json.dumps(a) for a in args)+")));"
p=subprocess.run(ucode()+ucode_paths()[2:]+['-e',code],capture_output=True,text=True,timeout=10)
self.assertEqual(p.returncode,0,p.stderr)
return json.loads(p.stdout)
def test_nr_array_signed_values_and_reported_band(self):
rows=self.call('nr_neighbours',NR_REPLY,'spengmd')
self.assertEqual(len(rows),6)
self.assertEqual({r['band'] for r in rows},{78})
self.assertEqual(rows[0]['rsrp'],-108.7)
self.assertEqual(rows[0]['sinr'],3.4)
self.assertEqual(rows[2]['sinr'],-7.5)
def test_lte_csv_blocks_and_full_band_table(self):
rows=self.call('sp_ltenb',LTE_REPLY)
self.assertEqual([(r['band'],r['arfcn'],r['pci']) for r in rows],[(3,1650,211),(45,46600,123)])
self.assertEqual(rows[0]['rsrp'],-95)
def test_spq_ambiguous_and_unknown_frequency_never_guesses_band(self):
for frequency, candidates in [(627264,[77,78]),(999999,[])]:
rows=self.call('nr_neighbours',f'0,0,0,0,0,0,0,0,1,{frequency},687,-10830,-1100,330,0,0,0','spq')
self.assertIsNone(rows[0]['band'])
self.assertEqual(rows[0]['band_candidates'],candidates)
def test_operator_decodes_only_explicit_ucs2(self):
for charset,want in [('UCS2','中国'),('GSM','4E2D56FD'),('unknown','4E2D56FD')]:
self.assertEqual(self.call('cops_fragment','+COPS: 0,0,"4E2D56FD",7','',charset)['name'],want)
self.assertEqual(self.call('cops_fragment','+COPS: 0,2,"46001",7','','UCS2')['plmn'],'46001')
def test_qos_rejects_invalid_cid_and_qci(self):
for row in ['x,9,0,0,0,0,1000,2000','1,0','1,256','1,-1']:
self.assertIsNone(self.call('qos_fragment',row))
self.assertEqual(self.call('qos_fragment','1,9,0,0,0,0,1000,2000'),dict(qci=9,dl=1,ul=2))
+3 -1
View File
@@ -185,6 +185,8 @@ class Watchdog(ShellTest):
self.context = MOBILE[MOBILE.index('watch_context_state() {'):MOBILE.index('\nwatch() {')]
self.watch = MOBILE[MOBILE.index('watch() {'):MOBILE.index('\n# Radio quality')]
self.watch = self.watch.replace('/run/', str(self.tmp) + '/')
self.event_transport=self.tmp/'event-transport.sh'
self.event_transport.write_text('watch_events_start() { :; }\nwatch_events_stop() { :; }\nwatch_next() { sleep "${MU300_WATCH_INTERVAL:-30}"; }\n')
self.stub('sleep', '''
n=$(cat "$STUBLOG/round" 2>/dev/null || echo 0); n=$((n+1)); echo "$n" >"$STUBLOG/round"
[ "$n" -le "${ROUNDS:-1}" ] || exit 99
@@ -225,7 +227,7 @@ at() {
}
watch
'''
r = self.sh(['bash'], code, **env)
r = self.sh(['bash'], code, **dict(dict(MU300_DATA_EVENTS_LIB=self.event_transport),**env))
self.assertEqual(r.returncode, 99, r.stderr)
return (self.tmp / 'calls').read_text()
+3 -3
View File
@@ -35,9 +35,9 @@ class Refresh(unittest.TestCase):
rpc = (PKG / 'root/usr/libexec/rpcd/mu300dash').read_text()
self.assertIn('"rates": { }', rpc)
self.assertIn('"cells": { "slot": "String" }', rpc)
self.assertIn('"$cage" -ge "$TTL"', rpc)
self.assertIn('"$sage" -ge "$TTL_FAST"', rpc)
rates = (LIB / 'dashboard-rates').read_text()
self.assertIn('mu300status', rpc)
self.assertIn('mu300.modem signal', rpc)
rates = (PKG / 'root/usr/share/ucode/mu300/rates.uc').read_text()
self.assertNotIn('AT+', rates)
self.assertNotIn('dashboard-info', rates)
self.assertIn("'data_interface'", rates)
+28 -131
View File
@@ -156,147 +156,44 @@ esac
r=self.run_shell(shell,self.qos_code(),AT_REPLY=reply)
self.assertEqual(json.loads(r.stdout),expected,r.stderr)
def snapshot_fixture(self):
from native_dashboard_fixture import Snapshot
return Snapshot(self.root)
def test_wan_block_and_real_counter_files_follow_changed_apn_and_cid_port(self):
source=(LIB/'dashboard-info').read_text()
json_helpers=source[source.index('n_or_null() {'):source.index('# ------------------------------------------------------------- temperature')]
jval=source[source.index('jval() {'):source.index('# ----------------------------------------------------------------- WAN')]
wan=source[source.index('cfg() {'):source.index('# ------------------------------------------------------------------- system')]
counter=source[source.index('net_obj() {'):source.index('# ------------------------------------------------------------------- Wi-Fi')]
counter=counter.replace('/sys/class/net',str(self.root/'net'))
for device,rx in (('sipa_eth0',915819),('sipa_eth3',6717270)):
d=self.root/'net'/device;(d/'statistics').mkdir(parents=True)
(d/'statistics/rx_bytes').write_text(str(rx));(d/'statistics/tx_bytes').write_text('100');(d/'operstate').write_text('up' if device.endswith('3') else 'down')
emit=source[source.index('MOBILE_NET=$(net_obj'):source.index('printf \'"wifi":')]
emit='\nprintf \'{\'\n'+emit+'\nprintf \'"_end":true}\''
code=json_helpers+'\n'+jval+'\n'+wan+'\nrd() { cat "$1"; }\n'+counter+emit
for shell in self.shells:
first=self.run_shell(shell,code);self.assertEqual(first.returncode,0,first.stderr)
data=json.loads(first.stdout)
self.assertEqual(data['wan']['apn'],'CMIOT5G')
self.assertEqual((data['wan']['device'],data['wan']['up']),('sipa_eth3',1))
self.assertEqual(data['net']['mobile'],{'rx':6717270,'tx':100,'up':1})
(self.root/'net/sipa_eth3/statistics/rx_bytes').write_text('6746383')
second=json.loads(self.run_shell(shell,code).stdout)
self.assertEqual(second['net']['mobile']['rx']-data['net']['mobile']['rx'],29113)
(self.root/'net/sipa_eth3/statistics/rx_bytes').write_text('6717270')
compact={'up':True,'l3_device':'sipa_eth3','proto':'modemmanager','inactive':{'up':False,'l3_device':'sipa_eth0','proto':'old'}}
nested=json.loads(self.run_shell(shell,code,WAN=json.dumps(compact)).stdout)
self.assertEqual((nested['wan']['up'],nested['wan']['proto'],nested['wan']['device']),(1,'modemmanager','sipa_eth3'))
snap=self.snapshot_fixture()
first=snap.run();self.assertEqual(first['wan']['apn'],'CMIOT5G')
self.assertEqual((first['wan']['device'],first['wan']['up']),('sipa_eth3',1))
snap.write('sys/class/net/sipa_eth3/statistics/rx_bytes','29214')
second=snap.run();self.assertEqual(second['net']['mobile']['rx']-first['net']['mobile']['rx'],29113)
snap.responses['network.interface.wan.status']['inactive']={'up':False,'l3_device':'sipa_eth0','proto':'old'}
self.assertEqual(snap.run()['wan']['device'],'sipa_eth3')
def test_shared_helper_is_packaged_and_collectors_keep_existing_at_ownership(self):
make=(LIB.parents[3]/'Makefile').read_text()
self.assertIn('$(CP) ./root/. $(1)/',make)
for name in ('dashboard-info','cell'):
source=(LIB/name).read_text();self.assertIn('. "$DASH_NET_BIN/dashboard-network.sh"',source)
self.assertIn('. "$DASH_NET_BIN/dashboard-network.sh"',(LIB/'cell').read_text())
self.assertNotIn("at 'AT+CGEQOSRDP=1'",(LIB/'cell').read_text())
self.assertNotIn('AT+',(LIB/'dashboard-info').read_text())
if (TOP/'tools/build-openwrt-tf-magisk.sh').exists():
for name in ('build-openwrt-tf-magisk.sh','make-release.sh'):
self.assertIn('./usr/libexec/unisoc-modem/dashboard-network.sh ',(TOP/'tools'/name).read_text())
def snapshot_fixture(self):
"""Run the entire collector with private proc/sys files and fake RPCs."""
source=(LIB/'dashboard-info').read_text()
source=re.sub(r'/sys/|/proc/|/run/|/tmp/dhcp[.]leases|/etc/openwrt_release|/etc/mu300/vpn[.]conf',lambda m:str(self.root)+m[0],source)
# BusyBox standalone ash can prefer its ip/date applets over PATH.
# Absolute fixture paths keep all three shells fully isolated.
for command in ('t2 ip ', 'if ip ', '|| ip '):
source=source.replace(command,command[:-3]+shlex.quote(str(self.bin/'ip'))+' ')
source=source.replace('$(date ', '$('+shlex.quote(str(self.bin/'date'))+' ')
path=self.root/'dashboard-info';path.write_text(source)
shutil.copyfile(LIB/'dashboard-network.sh',self.bin/'dashboard-network.sh')
self.stub('boot-status','boot_status() { printf \'{"next":"android"}\'; }\n')
self.stub('hotspot', '''#!/bin/sh
printf '%s\n' available 1 enabled 1 pending 0 up 1 section default_radio0 radio radio0 device wlan0 ssid FixtureWiFi channel 36 band 5g htmode HE80 country CN enc psk2 hidden 0
''')
self.stub('ubus', '''#!/bin/sh
case "$*" in
*network.interface.wan6*) printf '%s\n' '{"up":true,"dns-server":["2001:4860:4860::8888"]}';;
*network.interface.wan*) printf '%s\n' "$LATEST_WAN";;
*'system board') printf '{\n"model": "Fixture board"\n}\n';;
*get_status) printf '%s\n' '{"status":"ENABLED"}';;
*) exit 1;;
esac
''')
self.stub('uci', '''#!/bin/sh
printf '%s\n' "$*" >> "$FIXTURE_ROOT/uci-calls"
case "$*" in
*'show wireless') cat <<'EOF'
wireless.default_radio0.mode='ap'
wireless.default_radio0.device='radio0'
wireless.default_radio0.ssid='FixtureWiFi'
wireless.default_radio0.encryption='psk2'
wireless.default_radio0.hidden='0'
wireless.radio0.channel='36'
wireless.radio0.band='5g'
wireless.radio0.htmode='HE80'
wireless.radio0.country='CN'
EOF
;;
*unisoc_modem.main.data_interface) echo wan;;
*unisoc_modem.main.data_device) echo sipa_eth0;;
*hostname) echo fixture-router;;
*) exit 1;;
esac
''')
self.stub('iw', '#!/bin/sh\nexit 0\n')
self.stub('ip', '''#!/bin/sh
case "$*" in
'-4 addr show br-lan') echo 'inet 192.168.1.1/24';;
'-6 addr show sipa_eth3') echo 'inet6 2001:db8::2/64';;
*) exit 1;;
esac
''')
self.stub('date','#!/bin/sh\necho 1000\n')
for name in ('mu300-at','t551m-at','at','ifup','ifdown'):
self.stub(name,'#!/bin/sh\necho forbidden >> "$FIXTURE_ROOT/forbidden"\nexit 99\n')
files={'proc/uptime':'123.45 5\n','proc/stat':'cpu 10 0 5 85 0 0 0 0\n',
'proc/cpuinfo':'processor : 0\nprocessor : 1\n','proc/meminfo':'MemTotal: 1024 kB\nMemAvailable: 512 kB\n',
'proc/sys/net/netfilter/nf_conntrack_count':'7\n','sys/module/sipc_wwan/parameters/card':'0\n',
'sys/class/power_supply/battery/capacity':'73\n','sys/class/power_supply/battery/present':'1\n',
'sys/class/power_supply/battery/status':'Charging\n','sys/class/power_supply/battery/voltage_now':'4100000\n',
'sys/class/power_supply/battery/current_now':'-200000\n','sys/class/power_supply/usb/online':'1\n',
'sys/class/thermal/thermal_zone0/type':'soc-thmzone\n','sys/class/thermal/thermal_zone0/temp':'42000\n',
'etc/openwrt_release':"DISTRIB_DESCRIPTION='Fixture OpenWrt'\n",'tmp/dhcp.leases':'2000 aa:bb:cc:dd:ee:ff 192.168.1.2 fixture-client *\n',
'run/unisoc-modem-traffic/view.json':'{"fixture":123}\n'}
for device in ('sipa_eth0','sipa_eth3','br-lan','wlan0','usb0'):
for name,value in (('rx_bytes','101'),('tx_bytes','202')):
files[f'sys/class/net/{device}/statistics/{name}']=value+'\n'
files[f'sys/class/net/{device}/operstate']='up\n'
for name,value in files.items():
f=self.root/name;f.parent.mkdir(parents=True,exist_ok=True);f.write_text(value)
return path
native=(LIB.parents[1]/'share/ucode/mu300/dash.uc').read_text()
self.assertIn('apn.status(',native);self.assertNotIn('AT+',native)
for name in ('build-openwrt-tf-magisk.sh','make-release.sh'):
self.assertIn('./usr/share/ucode/mu300/dash.uc ',(TOP/'tools'/name).read_text())
def test_full_snapshot_preserves_unrelated_fields_when_apn_fails(self):
path=self.snapshot_fixture()
for shell in self.shells:
snapshots=[]
for state in (self.state,{'ok':0,'error':'apn_identity'}):
r=self.run_shell(shell,'. '+shlex.quote(str(path)),FIXTURE_ROOT=self.root,MU300_DASH_BIN=self.bin,APN_STATE=json.dumps(state))
self.assertEqual(r.returncode,0,r.stderr)
snapshots.append(json.loads(r.stdout))
good,bad=snapshots
self.assertEqual(good['wan']['apn'],'CMIOT5G');self.assertIsNone(bad['wan']['apn'])
for field in ('cpu','mem','temps','power','wifi','lan','net','boot','traffic','vpn','conns'):
self.assertEqual(good[field],bad[field],field)
self.assertEqual(good['cpu']['total'],100);self.assertEqual(good['mem']['avail_kb'],512)
self.assertEqual(good['power']['capacity'],73);self.assertEqual(good['temps']['soc'],42)
self.assertEqual(good['wifi']['ssid'],'FixtureWiFi');self.assertEqual(good['wifi']['width'],'80 MHz')
self.assertEqual(good['lan']['ip'],'192.168.1.1');self.assertEqual(good['lan']['list'][0]['host'],'fixture-client')
self.assertEqual(good['traffic'],{'fixture':123});self.assertEqual(good['conns'],7)
self.assertEqual(good['wan']['ip6'],'2001:db8::2')
self.assertFalse((self.root/'forbidden').exists())
self.assertTrue(all(line.startswith('-q get ') or line=='-q show wireless' for line in (self.root/'uci-calls').read_text().splitlines()))
snap=self.snapshot_fixture();good=snap.run()
(snap.config/'network').write_text("config interface 'wan'\n option proto 'unsupported'\n")
bad=snap.run();self.assertEqual(good['wan']['apn'],'CMIOT5G');self.assertIsNone(bad['wan']['apn'])
for field in ('cpu','mem','temps','power','wifi','lan','net','boot','traffic','vpn','conns'):
self.assertEqual(good[field],bad[field],field)
self.assertEqual(good['cpu']['total'],100);self.assertEqual(good['mem']['avail_kb'],512)
def test_stuck_apn_is_bounded_and_does_not_destroy_snapshot(self):
path=self.snapshot_fixture()
self.stub('apn','#!/bin/sh\nexec sleep 30\n')
started=time.monotonic()
r=self.run_shell(['sh'],'. '+shlex.quote(str(path)),FIXTURE_ROOT=self.root,MU300_DASH_BIN=self.bin)
elapsed=time.monotonic()-started
self.assertEqual(r.returncode,0,r.stderr);data=json.loads(r.stdout)
self.assertIsNone(data['wan']['apn']);self.assertEqual(data['wifi']['ssid'],'FixtureWiFi')
self.assertLess(elapsed,8,'APN status exceeded the existing 3-second deadline')
# The native snapshot imports the read-only selection function. It must
# never execute an APN helper, even if that executable hangs forever.
self.stub('apn','#!/bin/sh\necho invoked > "$FIXTURE_ROOT/forbidden"\nexec sleep 30\n')
snap=self.snapshot_fixture();started=time.monotonic();data=snap.run()
self.assertEqual(data['wifi']['ssid'],'FixtureWiFi')
self.assertFalse((self.root/'forbidden').exists());self.assertLess(time.monotonic()-started,8)
if __name__=='__main__':unittest.main()
+47 -91
View File
@@ -1,105 +1,61 @@
"""Hot-path shell helpers must preserve the dashboard's JSON wire values."""
"""Native snapshot regressions retain the original dashboard wire contract."""
import json
import shlex
import shutil
import tempfile
import unittest
from pathlib import Path
from native_dashboard_fixture import Snapshot
from helpers import ShellTest, TOP
class DashboardInfo(unittest.TestCase):
def setUp(self):
self.tmp=tempfile.TemporaryDirectory();self.addCleanup(self.tmp.cleanup)
self.root=Path(self.tmp.name);self.snap=Snapshot(self.root)
INFO = TOP / 'openwrt' / 'luci-app-mu300' / 'root' / 'usr' / 'libexec' / 'unisoc-modem' / 'dashboard-info'
class DashboardInfo(ShellTest):
def test_dns_reuses_both_status_snapshots(self):
script = INFO.read_text()
self.assertIn('wan_dns=$(wan_dns_servers "$WANJSON" "$WAN6JSON")', script)
helper = script[script.index('wan_dns_servers() {'):script.index('\nwan_up=')]
self.assertIn('jsonfilter -s "$snapshot"', helper)
self.assertNotIn('ubus call', helper)
self.assertNotIn('jarr_dns', script)
@unittest.skipUnless(shutil.which('jsonfilter'), 'also run fixture in OpenWrt container/device')
def test_dns_with_real_jsonfilter(self):
for shell in self.each_shell():
result = self.script(shell, TOP/'tests/dashboard_dns_fixture.sh', INFO)
self.assertEqual(result.returncode, 0, result.stderr)
self.assertIn('PASS dashboard DNS', result.stdout)
def station_code(self):
script = INFO.read_text()
helpers = script[script.index('n_or_null() {'):script.index('# ------------------------------------------------------------- temperature')]
stations = script[script.index('station_rows() {'):script.index('LAN_LEASES=')]
leases = self.tmp / 'leases'
leases.write_text('9999999999 E6:7A:77:59:7E:47 192.168.77.105 Xiaomi-17-Pro *\n'
'9999999999 aa:bb:cc:dd:ee:ff 192.168.77.106 * *\n')
stations = stations.replace('/tmp/dhcp.leases', str(leases))
return helpers + '\nt3() { cat; return "${IW_RC:-0}"; }\n' + stations + '\nprintf \'{"count":%s,"clients":[%s]}\' "$W_CN" "$W_CLIST"'
data=self.snap.run()
self.assertEqual(data['wan']['dns'],'1.1.1.1, 2001:4860:4860::8888')
# inactive DNS must never override the active netifd answer.
self.snap.responses['network.interface.wan.status']['inactive']={'dns-server':['WRONG']}
self.assertNotIn('WRONG',self.snap.run()['wan']['dns'])
def test_mac_only_station_is_counted_without_fabricated_metrics(self):
for shell in self.each_shell():
result = self.sh(shell, self.station_code(),
stdin='Station e6:7a:77:59:7e:47 (on wlan0)\n\tcurrent time: 1791393862131 ms\n')
self.assertEqual(result.returncode, 0, result.stderr)
data = json.loads(result.stdout)
self.assertEqual(data['count'], 1)
self.assertEqual(data['clients'][0], dict(mac='e6:7a:77:59:7e:47', host='Xiaomi-17-Pro',
ip='192.168.77.105', signal=None, tx=None, rx=None, conn=None))
self.snap.stations=[{'mac':'e6:7a:77:59:7e:47'}]
data=self.snap.run()['wifi']
self.assertEqual(data['clients_n'],1)
self.assertEqual(data['clients'][0],dict(mac='e6:7a:77:59:7e:47',host='Xiaomi-17-Pro',ip='192.168.77.105',signal=None,tx=None,rx=None,conn=None))
def test_complete_station_blocks_and_deduplication(self):
dump = ('Station E6:7A:77:59:7E:47 (on wlan0)\n\tsignal: -42 [-42] dBm\n'
'\ttx bitrate: 866.7 MBit/s VHT-MCS 9\n\trx bitrate: 433.3 MBit/s\n'
'\tconnected time: 125 seconds\nStation aa:bb:cc:dd:ee:ff (on wlan0)\n'
'Station e6:7a:77:59:7e:47 (on wlan0)\nStation invalid (on wlan0)\n')
for shell in self.each_shell():
result = self.sh(shell, self.station_code(), stdin=dump)
self.assertEqual(result.returncode, 0, result.stderr)
data = json.loads(result.stdout)
self.assertEqual(data['count'], 2)
self.assertEqual(data['clients'][0]['signal'], -42)
self.assertEqual(data['clients'][0]['tx'], '866.7 Mbit/s')
self.assertEqual(data['clients'][0]['rx'], '433.3 Mbit/s')
self.assertEqual(data['clients'][0]['conn'], '2 min')
self.assertIsNone(data['clients'][1]['host'])
self.snap.stations=[{'mac':'E6:7A:77:59:7E:47','sta_info':{'signal':-42,'tx_bitrate':{'bitrate':8667},'rx_bitrate':{'bitrate':4333},'connected_time':125}},
{'mac':'aa:bb:cc:dd:ee:ff'},{'mac':'e6:7a:77:59:7e:47'},{'mac':'invalid'}]
data=self.snap.run()['wifi'];self.assertEqual(data['clients_n'],2)
self.assertEqual(data['clients'][0]['signal'],-42)
self.assertEqual(data['clients'][0]['tx'],'866.7 Mbit/s')
self.assertEqual(data['clients'][0]['rx'],'433.3 Mbit/s')
self.assertEqual(data['clients'][0]['conn'],'2 min')
self.assertIsNone(data['clients'][1]['host'])
def test_empty_station_table_and_query_failure_are_distinct(self):
for shell in self.each_shell():
for rc, device, expected in [('0', 'lo', 0), ('1', 'lo', None), ('1', 'mu300-missing-test', 0)]:
result = self.sh(shell, self.station_code(), stdin='', IW_RC=rc, WIFI_DEVICE=device)
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual(json.loads(result.stdout), dict(count=expected, clients=[]))
self.snap.responses['hostapd.wlan0.get_clients']=None
for stations,count in [([],0),(None,None)]:
self.snap.stations=stations
self.assertEqual(self.snap.run()['wifi']['clients_n'],count)
self.snap.responses['hostapd.wlan0.get_clients']={'clients':{'aa:bb:cc:dd:ee:ff':{}}}
self.assertEqual(self.snap.run()['wifi']['clients_n'],1)
def test_conntrack_prefers_scalar_and_falls_back_only_when_needed(self):
script = INFO.read_text()
helper = script[script.index('conntrack_count() {'):script.index('CONNS=$(conntrack_count)')]
counter, table = self.tmp / 'counter', self.tmp / 'table'
command = helper + '\nconntrack_count ' + shlex.quote(str(counter)) + ' ' + shlex.quote(str(table))
for shell in self.each_shell():
for scalar, rows, expected in [('163\n', None, '163'), ('0\n', 'x\ny\n', '0'),
(None, 'x\ny\n', '2'), ('bad\n', 'x\n', '1'),
(None, '', '0'), (None, None, 'null')]:
for path, content in [(counter, scalar), (table, rows)]:
if content is None:
path.unlink(missing_ok=True)
else:
path.write_text(content)
result = self.sh(shell, command)
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual(result.stdout.strip(), expected)
def test_conntrack_prefers_scalar_and_uses_existing_table_format_when_needed(self):
scalar=self.root/'proc/sys/net/netfilter/nf_conntrack_count'
table=self.root/'proc/net/nf_conntrack'
for counter,rows,expected in [('163',None,163),('0','x\ny\n',0),(None,'x\ny\n',2),('bad','x\n',1),(None,'',0),(None,None,None)]:
for path,value in [(scalar,counter),(table,rows)]:
if value is None:path.unlink(missing_ok=True)
else:path.parent.mkdir(parents=True,exist_ok=True);path.write_text(value)
self.assertEqual(self.snap.run()['conns'],expected)
def test_json_string_escaping_matches_original_contract(self):
script = INFO.read_text()
helpers = script[script.index("CR=$(printf '\\r')"):script.index('# ------------------------------------------------------------- temperature')]
values = ['', 'normal', 'A\\B"C', '中文热点 🛜', 'line1\nline2\rline3']
for shell in self.each_shell():
for value in values:
result = self.sh(shell, helpers + '\nqs "$CASE"', CASE=value)
self.assertEqual(result.returncode, 0, result.stderr)
expected = (json.dumps(value.replace('\n', '').replace('\r', ''), ensure_ascii=False)
if value else 'null')
self.assertEqual(result.stdout, expected)
def test_conntrack_table_is_counted_across_chunk_boundaries(self):
self.snap.write('proc/net/nf_conntrack','x'*4095+'\n'+'entry\n'*10000)
self.assertEqual(self.snap.run()['conns'],10001)
if __name__ == '__main__':
import unittest
unittest.main()
def test_json_strings_quotes_unicode_and_newlines(self):
for value in ['normal','A\\B"C','中文热点 🛜','line1\nline2\rline3']:
# Read-only system-file strings cannot corrupt the surrounding JSON.
self.snap.write('tmp/sysinfo/model',value)
self.assertEqual(self.snap.run()['model'],value.replace('\n','').replace('\r',''))
+157
View File
@@ -0,0 +1,157 @@
"""Event-driven wakeups must preserve local watchdog recovery decisions."""
import json
import os
import signal
import subprocess
import time
import unittest
from helpers import TOP, ShellTest, ucode
from test_modemd import Base, has_modules, wait_for, UBUS, UBUSD
import test_cellular_mobility as original
LIB=TOP/'rootfs/overlay/opt/mu300/lib/data-events.sh'
class DataEventFilter(ShellTest):
def test_only_unsolicited_channel_can_trigger_a_modem_refresh(self):
for shell in self.each_shell():
for slot in [0,1]:
for nr in range(8):
for line in ['+CGEV: NW PDN DEACT 1','+CEREG: 1,"123",7','NO CARRIER','+CMTI: "SM",2']:
event=json.dumps({'mu300.modem.urc':{'channel':f'stty_nr{nr}','line':line}},separators=(',',':'))
r=self.sh(shell,'. '+str(LIB)+'\nwatch_event_decode "$EVENT"; printf "%s" "$watch_event"',MU300_SIM_SLOT=slot,EVENT=event)
self.assertEqual(r.returncode,0,r.stderr)
self.assertEqual(r.stdout,'modem' if nr==slot*3 and not line.startswith('+CMTI') else '')
def test_only_selected_wan_but_sim_transaction_wakes_to_reresolve_slot(self):
for shell in self.each_shell():
for event,want in [({'network.interface':{'interface':'wan2'}},'network'),({'network.interface':{'interface':'wan'}},''),({'mu300.sim-state':{'slot':1}},'sim'),({'ubus.object.remove':{'path':'mu300.modem'}},'gone')]:
r=self.sh(shell,'. '+str(LIB)+'\nwatch_event_decode "$EVENT"; printf "%s" "$watch_event"',MU300_WAN='wan2',EVENT=json.dumps(event,separators=(',',':')))
self.assertEqual(r.returncode,0,r.stderr);self.assertEqual(r.stdout,want)
@unittest.skipUnless(ucode() and has_modules(ucode()) and os.access(UBUS,os.X_OK) and os.access(UBUSD,os.X_OK),'real ucode/ubus required')
class DataEventBus(Base):
def setUp(self):
super().setUp()
self.sock=self.tmp/'bus';self.busd=subprocess.Popen([UBUSD,'-s',str(self.sock)],stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
self.assertTrue(wait_for(self.sock.exists));self.ubus_sock=self.sock
self.modem=self.start();self.ready()
self.assertTrue(wait_for(lambda:self.bus_call('list','mu300.modem').returncode==0))
stubs=self.tmp/'stubs';stubs.mkdir()
stub=stubs/'ubus';stub.write_text('#!/bin/sh\nexec '+UBUS+' -s "$MU300_UBUS_SOCKET" "$@"\n');stub.chmod(0o755)
self.event_env=dict(self.env,PATH=str(stubs)+':'+os.environ['PATH'],MU300_UBUS_SOCKET=str(self.sock))
self.result=self.tmp/'result';self.started=self.tmp/'started'
def tearDown(self):
super().tearDown();self.busd.terminate();self.busd.wait(5)
def bus_call(self,*args):
return subprocess.run([UBUS,'-s',str(self.sock),*args],capture_output=True,text=True,timeout=5)
def receiver(self,interval=30,fails=0):
# Bash is required by mobile-data. OpenWrt's receiver helper is portable
# too, so this test uses its actual ash with the same errexit/nounset.
code='set -eu\n. '+str(LIB)+'''\ntrap watch_events_stop EXIT
trap 'exit 0' TERM INT
watch_events_start || exit 9
printf '%s' "$watch_event_pid" > "$STARTED"
watch_next
printf '%s|%s' "$watch_event" "$watch_events" > "$RESULT"
'''
env=dict(self.event_env,MU300_WATCH_INTERVAL=str(interval),fails=str(fails),STARTED=str(self.started),RESULT=str(self.result))
p=subprocess.Popen(['/bin/sh','-c',code],env=env,stdout=subprocess.PIPE,stderr=subprocess.PIPE,text=True);self.procs.append(p)
self.assertTrue(wait_for(self.started.exists));time.sleep(.1)
return p
def send(self,name,data):
r=self.bus_call('send',name,json.dumps(data));self.assertEqual(r.returncode,0,r.stderr)
def finish(self,p,want):
self.assertEqual(p.wait(5),0,p.stderr.read());self.assertEqual(self.result.read_text(),want)
def test_wan_and_modem_events_wake_without_waiting_for_safety_poll(self):
p=self.receiver();self.send('mu300.modem.urc',{'channel':'stty_nr0','line':'+CGEV: NW PDN DEACT 1'})
self.finish(p,'modem|1')
def test_other_slot_and_solicited_replies_do_not_trigger_refresh(self):
p=self.receiver()
for nr in [1,2,3,4,5,6,7]:self.send('mu300.modem.urc',{'channel':f'stty_nr{nr}','line':'+CEREG: 1'})
self.send('network.interface',{'interface':'other'})
time.sleep(.2);self.assertIsNone(p.poll())
self.send('network.interface',{'interface':'wan'});self.finish(p,'network|1')
def test_unrelated_event_stream_does_not_extend_original_safety_deadline(self):
start=time.monotonic();p=self.receiver(interval=2)
for _ in range(6):self.send('network.interface',{'interface':'other'});time.sleep(.2)
self.finish(p,'|1');self.assertLess(time.monotonic()-start,3.2)
def test_detach_confirmation_interval_is_not_shortened_by_burst(self):
start=time.monotonic();p=self.receiver(interval=2,fails=1)
self.send('mu300.modem.urc',{'channel':'stty_nr0','line':'NO CARRIER'})
time.sleep(.2);self.assertIsNone(p.poll())
self.finish(p,'modem|1');self.assertGreater(time.monotonic()-start,.7)
def test_listener_death_stops_with_an_error(self):
p=self.receiver();pid=int(self.started.read_text());os.kill(pid,signal.SIGTERM)
self.assertNotEqual(p.wait(5),0,p.stderr.read())
def test_native_daemon_removal_stops_with_an_error(self):
p=self.receiver();self.modem.terminate();self.modem.wait(5);self.assertNotEqual(p.wait(5),0,p.stderr.read())
def whole_watchdog(self,down=False):
root=self.tmp/'watch-run';(root/'mu300').mkdir(parents=True)
if down:(root/'mu300-mobile-data-down').touch()
source=original.MOBILE
functions=source[source.index('watch_context_state() {'):source.index('\n# Radio quality')]
functions=functions.replace('/run/',str(root)+'/').replace('watch_events_start || return 1;','watch_events_start || return 1; printf "%s" "$watch_event_pid" > "$STARTED";')
script='set -euo pipefail\n'+functions+'''
CID=1; DEV=/dev/null; IFACE=sipa_eth0; DEVICE=f50; MU300_NETIFD=1; MU300_SIM_SLOT=0
modem_stack() { return 0; }
tty_setup() { :; }
at_owner_alive() { return 1; }
mu300_sim_env() { MU300_SIM_SLOT=1; MU300_SIM_DEVICE=sipa_eth8; }
led_up() { :; }
radio_on() { echo forbidden-radio >> "$CALLS"; }
at() {
printf 'slot=%s %s\n' "$MU300_SIM_SLOT" "$1" >> "$CALLS"
case "$1" in *CGACT*) echo '+CGACT: 1,1';; *CGPADDR*) echo '+CGPADDR: 1,10.0.0.2';; esac
}
watch
'''
stubs=self.tmp/'stubs'
for name,body in [('ip',"echo '1: sipa_eth8 inet 10.0.0.1/8 scope global sipa_eth8'"),('jsonfilter','echo false')]:
p=stubs/name;p.write_text('#!/bin/sh\n'+body+'\n');p.chmod(0o755)
# Keep the real ubus transport. Add only a harmless fake netifd method
# response so the complete watchdog can exercise in-place renew.
bus=stubs/'ubus';bus.write_text('#!/bin/sh\ncase "$*" in\n "call network.interface.wan status") echo "{}";;\n "call network.interface.wan renew") echo renew >> "$CALLS";;\n *) exec '+UBUS+' -s "$MU300_UBUS_SOCKET" "$@";;\nesac\n');bus.chmod(0o755)
calls=self.tmp/'calls';calls.touch()
env=dict(self.event_env,MU300_DATA_EVENTS_LIB=str(LIB),MU300_WATCH_INTERVAL='1',STARTED=str(self.started),CALLS=str(calls))
p=subprocess.Popen(['/bin/bash','-c',script],env=env,stdout=subprocess.PIPE,stderr=subprocess.PIPE,text=True);self.procs.append(p)
self.assertTrue(wait_for(self.started.exists));time.sleep(.15)
return p,calls
@unittest.skipUnless(os.path.exists('/bin/bash'),'mobile-data requires bash')
def test_whole_watchdog_reresolves_active_sim_and_renews_without_redial(self):
p,calls=self.whole_watchdog()
self.send('network.interface',{'interface':'wan'})
self.assertTrue(wait_for(lambda:'renew' in calls.read_text(),timeout=3),calls.read_text())
self.assertIn('slot=1 AT+CGACT?',calls.read_text())
self.assertNotIn('slot=0',calls.read_text());self.assertNotIn('forbidden-radio',calls.read_text())
pid=int(self.started.read_text());p.terminate();self.assertEqual(p.wait(5),143)
self.assertFalse(os.path.exists('/proc/'+str(pid)))
@unittest.skipUnless(os.path.exists('/bin/bash'),'mobile-data requires bash')
def test_whole_watchdog_respects_explicit_user_data_off(self):
p,calls=self.whole_watchdog(down=True)
self.send('network.interface',{'interface':'wan'})
time.sleep(1.2)
status=p.poll()
self.assertIsNone(status,p.stderr.read() if status is not None else '')
self.assertEqual(calls.read_text(),'')
@unittest.skipUnless(os.path.exists('/bin/bash'),'mobile-data requires bash')
def test_cleanup_does_not_remove_a_replaced_lock(self):
p,calls=self.whole_watchdog(down=True)
pidfile=self.tmp/'watch-run/mu300-mobile-data-watch.lock/pid'
pidfile.write_text('999999\n')
p.terminate();self.assertEqual(p.wait(5),143)
self.assertEqual(pidfile.read_text(),'999999\n')
Loaded 100 of 153 files, more files were not shown because too many files have changed in this diff. Show more