diff --git a/.github/workflows/build-android.yml b/.github/workflows/build-android.yml index d2fe24c..67857fd 100644 --- a/.github/workflows/build-android.yml +++ b/.github/workflows/build-android.yml @@ -31,36 +31,25 @@ jobs: - name: Build WebUI run: pnpm build - # ── 2. lumipro 二进制 ──────────────────────────────────────────────── - - name: Install Rust toolchain - uses: dtolnay/rust-toolchain@stable + # ── 2. luminpro 二进制 (Go) ───────────────────────────────────────── + - name: Setup Go + uses: actions/setup-go@v5 with: - targets: aarch64-linux-android + go-version-file: go/go.mod + cache-dependency-path: go/go.sum - - name: Setup Android NDK - uses: nttld/setup-ndk@v1 - id: ndk - with: - ndk-version: r27c - - - name: Cache Rust dependencies - uses: Swatinem/rust-cache@v2 - with: - workspaces: rust - - - name: Install cargo-ndk - run: cargo install cargo-ndk --locked - - - name: Build lumipro (aarch64-linux-android) - working-directory: rust - env: - ANDROID_NDK_HOME: ${{ steps.ndk.outputs.ndk-path }} - run: cargo ndk -t arm64-v8a --platform 26 build --release - - - name: Copy binary to bin/ + - name: Test Go packages + working-directory: go run: | - cp rust/target/aarch64-linux-android/release/lumipro bin/lumipro - chmod +x bin/lumipro + go vet ./... + go test ./... + + - name: Build luminpro (android/arm64) + working-directory: go + run: | + mkdir -p ../bin + CGO_ENABLED=0 GOOS=android GOARCH=arm64 go build -trimpath -ldflags="-s -w" -o ../bin/luminpro ./cmd/luminpro + chmod +x ../bin/luminpro # ── 3. 打包模块 ────────────────────────────────────────────────────── - name: Package module diff --git a/.gitignore b/.gitignore index 939cd52..5360f7f 100644 --- a/.gitignore +++ b/.gitignore @@ -9,8 +9,8 @@ dist/ webroot/* !webroot/.gitkeep -# rust -rust/target/ +# Go 编译产物(CI/本地构建生成) +bin/luminpro # 本地脚本 deploy.js diff --git a/DEVELOPMENT.md b/DEVELOPMENT.md index afb791c..6a00937 100644 --- a/DEVELOPMENT.md +++ b/DEVELOPMENT.md @@ -3,18 +3,18 @@ 欢迎回到 LuminPro 的开发!本指南旨在帮助开发者快速找回开发节奏,了解项目结构、构建流程以及如何进行本地调试。 > [!IMPORTANT] -> **无需本地环境全套配置**:本项目已配置完善的 GitHub Actions,每次推送代码到 `main` 分支或发布标签 (`v*`),云端会自动完成前端编译、Rust 交叉编译及模块打包,并生成可直接刷入的 ZIP 包。 +> **无需本地环境全套配置**:本项目已配置完善的 GitHub Actions,每次推送代码到 `main` 分支或发布标签 (`v*`),云端会自动完成前端编译、Go 交叉编译、单元测试及模块打包,并生成可直接刷入的 ZIP 包。 --- ## 1. 项目架构概览 -LuminPro 是一个基于 KernelSU WebUI 的 Android 亮度增强模块,结合了 Rust 底层监听与 Vue.js 前端控制。 +LuminPro 是一个基于 KernelSU WebUI 的 Android 亮度增强模块,底层为 Go 常驻守护进程,前端为 Vue 3。 +- `go/`: Go 源码。`cmd/luminpro` 是入口,`internal/` 下按职责分包(见第 5 节)。 - `webui/`: 基于 Vite + Vue 3 的前端源码。 -- `rust/`: 负责底层文件监听的二进制程序 (`lumipro`) 源码。 -- `bin/`: 存放预编译的二进制文件(如 `jq`, `lumipro`)。 -- `script/`: 核心逻辑 shell 脚本(守护进程、逻辑触发等)。 +- `bin/`: 编译产物 `luminpro`(CI 生成,不进版本库)。 +- `script/`: 仅保留 `restart.sh` 等转发脚本。 - `webroot/`: WebUI 编译产物存放地,模块刷入后 KernelSU 会读取此处。 - `module.prop`: 模块基础信息。 - `build-module.js`: 模块自动化打包脚本。 @@ -23,15 +23,16 @@ LuminPro 是一个基于 KernelSU WebUI 的 Android 亮度增强模块,结合 ## 2. 环境搭建 (本地) -如果你仅进行 WebUI 界面调整或脚本逻辑修改,只需安装 Node.js: +- **Node.js**: 推荐 v18+ (项目中使用 pnpm/npm),用于 WebUI 与打包。 +- **Go**: 1.26+,用于守护进程开发与测试(交叉编译到 Android 无需 NDK)。 -- **Node.js**: 推荐 v18+ (项目中使用 pnpm/npm) +```bash +cd go +go vet ./... && go test ./... # 全部逻辑均可在 host 上测试 +CGO_ENABLED=0 GOOS=android GOARCH=arm64 go build -trimpath -ldflags="-s -w" -o ../bin/luminpro ./cmd/luminpro +``` -如果你需要**在本地编译 Rust 程序**(通常不需要,建议交给云端),才需要安装以下工具: - -- **Rust**: 需要安装 Android Target: `rustup target add aarch64-linux-android` -- **Android NDK**: 交叉编译所需 (推荐 r27c+)。 -- **cargo-ndk**: 安装命令: `cargo install cargo-ndk` +守护进程支持 `LUMINPRO_MODDIR` 环境变量覆盖模块目录,配合自定义 `now_bri_file` 即可在电脑上直接跑通全流程(详见第 8 节)。 --- @@ -75,27 +76,39 @@ npm run build --- -## 5. Rust 底层开发 (可选) +## 5. Go 守护进程开发 -`lumipro` 源码位于 `rust/`。通常修改逻辑后直接推送即可,若需本地测试编译: +`go/` 下按职责分包,判定逻辑与 IO 分离,便于在电脑上测试: + +| 包 | 职责 | +| --- | --- | +| `cmd/luminpro` | 子命令入口:`daemon` / `boost` / `restart` / `config` | +| `internal/inotify` | 原始 inotify 封装(事件字母与 toybox 兼容,含防抖与事件排空) | +| `internal/policy` | 纯判定逻辑:休眠时段、阈值、黑名单、HDR 迟滞状态机 | +| `internal/brightness` | 亮度节点读写与渐变序列计算 | +| `internal/system` | `dumpsys` / `settings` 调用,接口化以便注入假实现 | +| `internal/config` | config.json 读写、补默认值、旧配置迁移(安装脚本用它替代 jq) | +| `internal/logging` | service.log 写入(格式与 WebUI 过滤兼容) | +| `internal/daemon` | 主循环、操作锁、boost / restart 实现 | ```bash -cd rust -cargo ndk -t arm64-v8a --platform 26 build --release -cp target/aarch64-linux-android/release/lumipro ../bin/lumipro +cd go +go test ./... # 全部单测(含真 inotify 集成测试) +go test ./internal/policy/ -v # 只跑判定逻辑 ``` --- ## 6. 模块打包脚本 -`build-module.js` 负责版本同步、生成校验和并打包。即便不在本地编译 Rust,你也可以用它临时打包当前目录文件: +`build-module.js` 负责版本同步、生成校验和并打包。打包前需要先有 `bin/luminpro`: ```bash -# 自动执行:前端编译 + 模块打包 +# 自动执行:前端编译 + 模块打包(不含 Go 编译) npm run build -# 仅打包(不重编前端): +# 完整本地构建: +cd go && CGO_ENABLED=0 GOOS=android GOARCH=arm64 go build -trimpath -ldflags="-s -w" -o ../bin/luminpro ./cmd/luminpro && cd .. node build-module.js ``` @@ -103,32 +116,44 @@ node build-module.js ## 7. 核心逻辑说明 -- **service.sh**: 模块启动入口,负责拉起守护进程。 -- **script/daemon.sh**: 持续监控 `lumipro` 进程,并处理亮度提升逻辑。 -- **script/up.sh**: 亮度提升核心逻辑(阈值判断、黑名单、HDR、渐变写入)。 -- **script/restart.sh**: 重启守护进程与监听。 -- **boost.sh**: 一键提升至峰值亮度 / 恢复原亮度。 -- **customize.sh**: 刷入时的安装逻辑,处理初次校准与文件权限。 -- **action.sh**: 快捷操作逻辑(音量键或管理器按钮触发)。 +- **service.sh**: 开机入口,等待系统就绪后拉起 `luminpro daemon`。 +- **luminpro daemon**: 常驻进程,负责监听、判定、渐变写入、状态文件维护。 +- **luminpro boost** / **boost.sh**: 一键提升至峰值亮度 / 恢复原亮度。 +- **luminpro restart** / **script/restart.sh**: 通知守护进程重建监听;未运行时按需拉起。 +- **customize.sh**: 刷入时的安装逻辑(校准向导、旧配置迁移),配置读写全部调用 + `luminpro config ...`,模块内不再需要 jq。 +- **action.sh**: 快捷启停(管理器操作按钮),仅切换 `pid/stop.flag`。 ### 操作锁 (oplock) -`pid/oplock` 是脚本与 WebUI 之间的约定文件:任何会写亮度节点或重建监听的操作 -(`up.sh` 渐变期间、`boost.sh` 全程、`restart.sh` 全程)都会把自己的 PID 写入该文件, -结束时删除。WebUI 轮询此文件,发现持锁时暂停状态刷新并禁用写操作入口(配置保存、 -黑名单保存、亮度滑条、重启模块),顶部显示提示横幅。 +`pid/oplock` 是守护进程与 WebUI 之间的约定文件:任何会写亮度节点或重建监听的操作 +(渐变期间、`boost` 全程、`restart` 全程)都会把自己的 PID 写入该文件,结束时删除。 +WebUI 轮询此文件,发现持锁时暂停状态刷新并禁用写操作入口(配置保存、黑名单保存、 +亮度滑条、重启模块),顶部显示提示横幅。 - 查询约定:文件存在且其中的 PID 在 `/proc` 中存活 → 锁定中;否则视为遗留锁,由查询方 - 就地清理(避免脚本被 SIGKILL 后 WebUI 永久卡在锁定态)。 + 就地清理(避免进程被 SIGKILL 后 WebUI 永久卡在锁定态)。 - `service.sh` 开机时清理该文件;WebUI 侧的实现见 `webui/src/composables/useOplock.js`。 --- ## 8. 调试技巧 -- **查看日志**: 在 WebUI 界面、日志页,或执行 `tail -f /data/adb/modules/luminpro/luminpro.log`。 -- **手动触发逻辑**: 执行 `/data/adb/modules/luminpro/boost.sh`。 -- **配置文件**: `/data/adb/modules/luminpro/config/config.json`。 +- **查看日志**: WebUI 日志页,或 `tail -f /data/adb/modules/LuminPro/service.log`。 +- **手动触发**: `/data/adb/modules/LuminPro/boost.sh`。 +- **配置文件**: `/data/adb/modules/LuminPro/config/config.json`。 +- **在电脑上跑守护进程**(无需真机): + +```bash +mkdir -p /tmp/lp/{config,pid} && printf 1200 > /tmp/lp/brightness +cp bin/luminpro /tmp/lp/ # 或用 go build 出的 host 版二进制 +LUMINPRO_MODDIR=/tmp/lp ./luminpro config init +LUMINPRO_MODDIR=/tmp/lp ./luminpro config set now_bri_file=/tmp/lp/brightness ui_max_bri=1000 max_bri=3000 +LUMINPRO_MODDIR=/tmp/lp ./luminpro daemon & +printf 1500 > /tmp/lp/brightness # 模拟用户调高亮度,观察日志与节点变化 +``` + +`dumpsys` / `settings` 在电脑上不存在时按「无数据」降级,不影响验证监听与渐变主流程。 --- diff --git a/README.md b/README.md index c21f63d..2e181d8 100755 --- a/README.md +++ b/README.md @@ -5,21 +5,21 @@ **中文简体** 丨 [English](https://github.com/YuleBest/LuminPro/blob/main/README_en.md) 让你的 Android 设备随时可以突破前台亮度上限,将屏幕提升至硬件峰值 -_基于 KernelSU WebUI + Rust 事件驱动架构_ +_基于 KernelSU WebUI + Go 事件驱动架构_ ## 模块介绍 -无论当前屏幕亮度如何,只要触发亮度超过设定阈值,LuminPro 便会自动且平滑地将屏幕提升至硬件支持的峰值亮度,确保你在强光户外也能获得清晰的显示效果。模块采用 Rust 编写的 `lumipro` 二进制程序进行底层文件事件监听,零轮询、零空转,配合 KernelSU WebUI 提供完整的可视化配置与状态监控。 +无论当前屏幕亮度如何,只要触发亮度超过设定阈值,LuminPro 便会自动且平滑地将屏幕提升至硬件支持的峰值亮度,确保你在强光户外也能获得清晰的显示效果。模块采用 Go 编写的常驻守护进程进行底层文件事件监听,零轮询、零空转,配合 KernelSU WebUI 提供完整的可视化配置与状态监控。 > [!TIP] > 如果你是开发者,请参阅 [开发文档 (DEVELOPMENT.md)](./DEVELOPMENT.md) 了解构建与调试流程。 ## V2.3+ 核心特性 -- **零耗电底层监听 (lumipro)** - 彻底告别死循环与轮询。使用 Rust 编写的 `lumipro` 二进制程序替代 `inotifyd`,内置防抖动与调试模式,仅在亮度节点文件发生变更的瞬间响应,守护进程 (`daemon.sh`) 负责持续监视 lumipro 进程稳定性,并具备**失效自动修复(Stale Lock 回收)**机制。 +- **零耗电底层监听 (luminpro)** + 彻底告别死循环与轮询。Go 编写的常驻守护进程 (`luminpro`) 直接使用 inotify 监听亮度节点,仅在文件发生变更的瞬间响应,内置 300ms 防抖与事件排空;判定逻辑、渐变写入、状态维护全部在同一进程内完成,无脚本拼接与进程拉起开销,并具备**失效自动修复**机制(监听失效自动重建、遗留锁自动回收)。 - **兼容模式 (轮询驱动)** 针对部分无法触发 inotify 事件的特殊机型,新增兼容模式。开启后模块切换为 2 秒一次的低频轮询,确保在任何环境下都能正常工作。 @@ -32,7 +32,7 @@ _基于 KernelSU WebUI + Rust 事件驱动架构_ - `休眠时段` — 指定不触发提升的时间范围(如 `2200-0700`) - `日志等级` — 控制日志输出量(关闭 / 仅错误 / 警告+ / 全部) - `亮度/最大亮度节点路径` — 支持自定义设备 sysfs 路径 - - `inotify 监测事件` — 自定义 lumipro 触发事件类型 + - `inotify 监测事件` — 自定义监听的事件类型 - **平滑亮度过渡** 毫秒级 50 步步进算法,避免亮度瞬间跃升带来的视觉不适。步数可在 WebUI 中自由调整。 @@ -51,7 +51,7 @@ _基于 KernelSU WebUI + Rust 事件驱动架构_ 通过管理器的「操作」按钮或 `action.sh` 快捷开关,可即时将亮度拉至峰值;再次触发则恢复原始亮度。 - **实时状态监控与日志** - WebUI 状态页实时显示当前亮度值、lumipro 运行 PID 及服务状态。日志页支持按 `INFO` / `WARN` / `ERROR` 等级过滤,并可一键复制或导出到 `/sdcard`。 + WebUI 状态页实时显示当前亮度值、守护进程 PID 及服务状态。日志页支持按 `INFO` / `WARN` / `ERROR` 等级过滤,并可一键复制或导出到 `/sdcard`。 ## 配置项说明 @@ -71,7 +71,7 @@ _基于 KernelSU WebUI + Rust 事件驱动架构_ | `now_bri_file` | 当前亮度节点路径 | 标准 panel0 路径 | | `max_bri_file` | 最大亮度节点路径 | 标准 panel0 路径 | | `blacklist_apps` | 黑名单包名/Activity 列表 | `[]` | -| `inotify_events` | lumipro 监测事件 | `c` | +| `inotify_events` | 监听事件 | `c` | ## 安装方法 diff --git a/README_en.md b/README_en.md index 7d2add2..08b3bdd 100644 --- a/README_en.md +++ b/README_en.md @@ -5,18 +5,18 @@ [中文简体](https://github.com/YuleBest/LuminPro/blob/main/README.md) 丨 **English** Break past the Android foreground brightness cap and push your screen to its hardware peak — anytime -_Powered by KernelSU WebUI + Rust Event-Driven Architecture_ +_Powered by KernelSU WebUI + Go Event-Driven Architecture_ ## Overview -LuminPro monitors the system brightness sysfs node via a Rust-native `lumipro` binary. Whenever the current brightness exceeds a configured threshold, it smoothly ramps the display up to the hardware maximum — ideal for outdoor readability. A resident daemon (`daemon.sh`) keeps the listener alive, and the full KernelSU WebUI lets you tune every parameter without a reboot. +LuminPro monitors the system brightness sysfs node via a Go-native resident daemon (`luminpro`). Whenever the current brightness exceeds a configured threshold, it smoothly ramps the display up to the hardware maximum — ideal for outdoor readability. The daemon owns listening, decision-making, ramping and state files in a single process, and the full KernelSU WebUI lets you tune every parameter without a reboot. ## V2.3 Core Features -- **Zero-Overhead Event Listener (lumipro)** - No polling loops, no background spin. LuminPro now uses a Rust-native `lumipro` binary with built-in debouncing and debug mode, replacing the old `inotifyd` approach. A companion daemon process continuously watches the listener and restarts it if it ever dies, guaranteeing an unbroken monitoring chain. +- **Zero-Overhead Event Listener (luminpro)** + No polling loops, no background spin. The Go daemon (`luminpro`) watches the brightness node with raw inotify, responds only when the file actually changes, and includes a 300ms debounce plus event draining. It self-heals: a lost watch is rebuilt automatically and stale locks are reclaimed. - **KernelSU WebUI Configuration** Adjust all settings visually inside the module's settings page. Changes take effect **immediately** — no reboot required: @@ -26,7 +26,7 @@ LuminPro monitors the system brightness sysfs node via a Rust-native `lumipro` b - `Sleep Hours` — time range to suppress boosts (e.g. `2200-0700`) - `Log Level` — control log verbosity (off / error / warn / info) - `Brightness / Max-Brightness node paths` — custom sysfs paths for non-standard devices - - `inotify Event Types` — which events `lumipro` should watch + - `inotify Event Types` — which events the daemon should watch - **Smooth Step Transition** Millisecond-level 50-step interpolation prevents jarring brightness jumps. The step count is configurable. @@ -45,7 +45,7 @@ LuminPro monitors the system brightness sysfs node via a Rust-native `lumipro` b Trigger a one-shot peak brightness via the manager's Action button or `action.sh`. A second tap restores the original brightness. - **Live Status & Log Dashboard** - The WebUI status page shows real-time brightness, the active `lumipro` PID, and service state. The log page supports level filtering (`INFO` / `WARN` / `ERROR`) and lets you copy or export logs to `/sdcard` with one tap. + The WebUI status page shows real-time brightness, the daemon PID, and service state. The log page supports level filtering (`INFO` / `WARN` / `ERROR`) and lets you copy or export logs to `/sdcard` with one tap. ## Configuration Reference @@ -62,7 +62,7 @@ LuminPro monitors the system brightness sysfs node via a Rust-native `lumipro` b | `now_bri_file` | Current brightness sysfs node path | standard panel0 path | | `max_bri_file` | Max brightness sysfs node path | standard panel0 path | | `blacklist_apps` | Blacklisted packages / activities | `[]` | -| `inotify_events` | lumipro event mask | `c` | +| `inotify_events` | inotify event mask | `c` | ## Installation diff --git a/SHA256SUMS b/SHA256SUMS index f44ed93..7d08a08 100644 --- a/SHA256SUMS +++ b/SHA256SUMS @@ -1,8 +1,6 @@ b1ac7dab449904d761b64b59192b217387ca5ab8b9a36a581c257078c36d8032 action.sh -6bc62f25981328edd3cfcfe6fe51b073f2d7e7710d7ef7fcdac28d4e384fc3d4 bin/jq -0c2d380d5171449802d1dc62ffa312c0ff9a41c73216c1159324a85705d02f0e boost.sh -8b3080197fa7ac3511717d901f509327e9a3e7db1de61d660f83f9ebf55913fd customize.sh -a05c860694e46891c91baac4d54805524d5234ff06bc5fcb4ff46bac542ed3c1 script/daemon.sh -8d3c20a7404e6b5aeb423ff0a40dd3eb725b9882aa998bd0b8d5ef24dd766396 script/restart.sh -59d0ab6f9e1d0b3a67d9c867e8ff2c7bc3bb6c051cc0642f6bf076758841be88 script/up.sh -6631d85232e54f0066639f8ca4610c8b992e6130173563d9568ed8f9f79ab83a service.sh +02d71e872c7b76a437f17e2e2c94bbe589d668449326873b536a8122d5a71258 bin/luminpro +c8ebe774473772ad08791716546e602533ac1198c0d9abf0e750ff386a1980eb boost.sh +51947b69e81d21b8199b11fd259e0418566c5e646e39d6e46b97b272cbe9b25b customize.sh +da8d6380e9a66cb059a005a1e999ee15cb54dfe74feb9d7cae45e751a2abc58a script/restart.sh +96caeb9deb80a29824e06adc1ca712c4cf10c785c109e02f510c27d612f7cd3a service.sh diff --git a/bin/jq b/bin/jq deleted file mode 100644 index 04b0365..0000000 Binary files a/bin/jq and /dev/null differ diff --git a/boost.sh b/boost.sh index bbfc1f6..4cf3128 100644 --- a/boost.sh +++ b/boost.sh @@ -1,51 +1,7 @@ #!/system/bin/sh #shellcheck shell=ash -# LuminPro 手动提升/恢复亮度触发脚本 +# LuminPro 手动提升/恢复亮度(转发到 Go 实现) MODDIR="$(dirname "$(readlink -f "$0")")" -CONFIG_FILE="$MODDIR/config/config.json" -JQ="$MODDIR/bin/jq" -PID_DIR="$MODDIR/pid" -BOOST_FLAG="$PID_DIR/boost.flag" -OPLOCK_FILE="$PID_DIR/oplock" - -DEFAULT_NOW_BRI_FILE="/sys/class/backlight/panel0-backlight/brightness" - -get_cfg() { - local key="$1" default="$2" - local val - if val=$("$JQ" -re ".${key}" "$CONFIG_FILE" 2>/dev/null); then - echo "$val" - else - echo "$default" - fi -} - -now_bri_file="$(get_cfg now_bri_file "$DEFAULT_NOW_BRI_FILE")" - -if [ ! -f "$now_bri_file" ]; then - exit 1 -fi - -mkdir -p "$PID_DIR" -# 持操作锁:WebUI 据此暂停刷新并禁用写操作 -echo $$ >"$OPLOCK_FILE" -# shellcheck disable=SC2064 -trap "rm -f '$OPLOCK_FILE'" EXIT HUP INT TERM - -if [ -f "$BOOST_FLAG" ]; then - restore_bri="$(cat "$BOOST_FLAG" 2>/dev/null | tr -d ' \n')" - [ -n "$restore_bri" ] && echo -n "$restore_bri" >"$now_bri_file" 2>/dev/null - rm -f "$BOOST_FLAG" -else - max_bri="$(get_cfg max_bri '')" - if [ -z "$max_bri" ] || [ "$max_bri" = "0" ]; then - exit 1 - fi - now_bri="$(cat "$now_bri_file" 2>/dev/null | tr -d ' \n')" - echo -n "$now_bri" >"$BOOST_FLAG" - echo -n "$max_bri" >"$now_bri_file" 2>/dev/null -fi - -exit 0 +exec "$MODDIR/bin/luminpro" boost diff --git a/build-module.js b/build-module.js index 66231c0..5797471 100644 --- a/build-module.js +++ b/build-module.js @@ -47,7 +47,9 @@ const excludes = [ 'build.ps1', 'build-module.js', 'webui', // webui 目录已经构建到 webroot - 'rust', // Rust 源码,编译产物已复制到 bin/ + 'go', // Go 源码,编译产物已复制到 bin/ + 'dist', // 本地下载的构建产物 + '.zcode', // 编辑器/会话临时文件 zipName, ] diff --git a/customize.sh b/customize.sh index 0aefb8e..5250512 100755 --- a/customize.sh +++ b/customize.sh @@ -20,12 +20,12 @@ DEFAULT_MAX_BRI_FILE="/sys/class/backlight/panel0-backlight/max_brightness" mod_config="$MODPATH/config" old_config="/data/adb/modules/LuminPro/config" -# jq 二进制(已随模块提取) -JQ="$MODPATH/bin/jq" +# Go 二进制(已随模块提取),负责全部 JSON 配置读写 +BIN="$MODPATH/bin/luminpro" CONFIG_FILE="$mod_config/config.json" mkdir -p "$mod_config" -chmod 755 "$JQ" 2>/dev/null +chmod 755 "$BIN" 2>/dev/null # 亮度节点校验结果: 1 = 默认节点不可用 (安装继续, 但功能不启用) NODE_MISSING=0 @@ -34,65 +34,35 @@ NODE_MISSING=0 # 工具函数 # ========================== -# 从当前 config.json 读取字段值 +# 读取配置字段,缺失或为空时返回默认值 cfg_get() { - local key="$1" default="$2" - local val - if val=$("$JQ" -re ".${key}" "$CONFIG_FILE" 2>/dev/null); then + local key="$1" default="$2" val + val="$("$BIN" config get "$key" 2>/dev/null)" + if [ -n "$val" ]; then echo "$val" else echo "$default" fi } -# 从旧 txt 文件读取值(迁移用) -read_old_txt() { - local file="$old_config/$1" - local default="$2" - if [ -f "$file" ]; then - local val - val="$(cat "$file" 2>/dev/null | tr -d ' \n')" - [ -n "$val" ] && echo "$val" || echo "$default" - else - echo "$default" - fi +# 取正值字段(0 视为未配置,输出空) +cfg_pos() { + local v + v="$(cfg_get "$1" 0)" + case "$v" in + '' | 0) echo "" ;; + *) echo "$v" ;; + esac } -# 用 cfg_* 变量写入 config.json -write_config_json() { - "$JQ" -n \ - --arg ui_max_bri "${cfg_ui_max_bri:-0}" \ - --arg max_bri "${cfg_max_bri:-0}" \ - --arg steps_num "${cfg_steps_num:-50}" \ - --arg log_max_size "${cfg_log_max_size:-512}" \ - --arg auto_bri_sleep "${cfg_auto_bri_sleep:-1}" \ - --arg display_hdr_sleep "${cfg_display_hdr_sleep:-0}" \ - --arg hdr_enter_ratio "${cfg_hdr_enter_ratio:-1.15}" \ - --arg hdr_exit_ratio "${cfg_hdr_exit_ratio:-1.05}" \ - --arg compatibility_mode "${cfg_compatibility_mode:-0}" \ - --arg sleep_time "${cfg_sleep_time:-}" \ - --arg inotify_events "${cfg_inotify_events:-c}" \ - --arg now_bri_file "${cfg_now_bri_file:-$DEFAULT_NOW_BRI_FILE}" \ - --arg max_bri_file "${cfg_max_bri_file:-$DEFAULT_MAX_BRI_FILE}" \ - --arg log_level "${cfg_log_level:-info}" \ - --argjson blacklist_apps "${cfg_blacklist_apps:-[]}" \ - '{ - ui_max_bri: ($ui_max_bri | tonumber), - max_bri: ($max_bri | tonumber), - steps_num: ($steps_num | tonumber), - log_max_size: ($log_max_size | tonumber), - auto_bri_sleep: ($auto_bri_sleep | tonumber), - display_hdr_sleep: ($display_hdr_sleep | tonumber), - hdr_enter_ratio: ($hdr_enter_ratio | tonumber), - hdr_exit_ratio: ($hdr_exit_ratio | tonumber), - compatibility_mode:($compatibility_mode | tonumber), - sleep_time: $sleep_time, - inotify_events: $inotify_events, - now_bri_file: $now_bri_file, - max_bri_file: $max_bri_file, - log_level: $log_level, - blacklist_apps: $blacklist_apps - }' >"$CONFIG_FILE" +# 从 key=value 输出中提取字段(供 config inspect / summary 使用) +field() { + sed -n "s/^$1=//p" | head -n 1 +} + +# 0/1 转中文 +onoff() { + [ "$1" = "1" ] && echo "开启" || echo "关闭" } # ========================== @@ -188,9 +158,7 @@ TEST_UI_MAX_BRI() { echo " ✦ 峰值最大亮度由节点文件获得: [ $measured_max ]" echo " ✦ 若不符合预期,请稍后到 Web UI 更改" - # 写入 JSON - "$JQ" ".ui_max_bri = ($measured_ui | tonumber) | .max_bri = ($measured_max | tonumber)" \ - "$CONFIG_FILE" >"$CONFIG_FILE.tmp" && mv "$CONFIG_FILE.tmp" "$CONFIG_FILE" + "$BIN" config set "ui_max_bri=$measured_ui" "max_bri=$measured_max" >/dev/null 2>&1 echo "" echo " ✦ 测试完成" @@ -200,92 +168,59 @@ TEST_UI_MAX_BRI() { # 导入旧配置(支持 JSON 格式和旧 txt 格式) IMPORT_OLD_CONFIG() { + local out format v + + # 让 Go 侧判断是否存在可用旧配置并输出字段 + out="$("$BIN" config inspect "$old_config" 2>/dev/null)" || return 1 + format="$(echo "$out" | field format)" + # 1. 已有 JSON 格式 - if [ -f "$old_config/config.json" ]; then - local old_ui - old_ui=$("$JQ" -re '.ui_max_bri' "$old_config/config.json" 2>/dev/null || echo "0") - if [ "${old_ui:-0}" -gt 0 ] 2>/dev/null; then - echo "" - sleep 1 - echo " ✦ 检测到已有 JSON 配置:" - echo " - 前台最大亮度: $old_ui" - echo " - 峰值最大亮度: $("$JQ" -re '.max_bri' "$old_config/config.json" 2>/dev/null)" - local old_st - old_st=$("$JQ" -re '.sleep_time // empty' "$old_config/config.json" 2>/dev/null) - [ -n "$old_st" ] && echo " - 休眠时间: $old_st" - echo "" - echo " ❆ 按音量 + 沿用旧配置, 按音量 - 重新测试" - if [ "$(btn)" = "0" ]; then - cp -f "$old_config/config.json" "$CONFIG_FILE" - # 若旧 JSON 缺少 blacklist_apps 字段,尝试从 blacklist_apps.txt 补入 - if ! "$JQ" -e '.blacklist_apps' "$CONFIG_FILE" >/dev/null 2>&1; then - local bl_arr - if [ -s "$old_config/blacklist_apps.txt" ]; then - bl_arr=$("$JQ" -Rs 'split("\n") | map(select(length > 0))' \ - "$old_config/blacklist_apps.txt" 2>/dev/null || echo '[]') - else - bl_arr='[]' - fi - local tmp_cfg="$CONFIG_FILE.tmp" - "$JQ" --argjson bl "$bl_arr" '. + {blacklist_apps: $bl}' \ - "$CONFIG_FILE" >"$tmp_cfg" && mv -f "$tmp_cfg" "$CONFIG_FILE" - fi - echo " ✦ 已导入 JSON 配置" - return 0 - else - echo " ❆ 将重新测试" - return 1 - fi + if [ "$format" = "json" ]; then + echo "" + sleep 1 + echo " ✦ 检测到已有 JSON 配置:" + echo " - 前台最大亮度: $(echo "$out" | field ui_max_bri)" + echo " - 峰值最大亮度: $(echo "$out" | field max_bri)" + v="$(echo "$out" | field sleep_time)" + [ -n "$v" ] && echo " - 休眠时间: $v" + echo "" + echo " ❆ 按音量 + 沿用旧配置, 按音量 - 重新测试" + if [ "$(btn)" = "0" ]; then + "$BIN" config migrate "$old_config" >/dev/null 2>&1 + echo " ✦ 已导入 JSON 配置" + return 0 fi + echo " ❆ 将重新测试" return 1 fi # 2. 旧 txt 格式迁移 - if [ -d "$old_config" ] && [ -s "$old_config/ui_max_bri.txt" ] && [ -s "$old_config/max_bri.txt" ]; then + if [ "$format" = "txt" ]; then echo "" sleep 1 echo " ✦ 检测到旧格式配置,将迁移至 JSON:" - echo " - 前台最大亮度: $(cat "$old_config/ui_max_bri.txt")" - echo " - 峰值最大亮度: $(cat "$old_config/max_bri.txt")" - [ -s "$old_config/sleep_time.txt" ] && echo " - 休眠时间: $(cat "$old_config/sleep_time.txt")" - [ -s "$old_config/auto_bri_sleep.txt" ] && echo " - 自动亮度时休眠: $(cat "$old_config/auto_bri_sleep.txt" | sed 's/1/开启/;s/0/关闭/')" - [ -s "$old_config/steps_num.txt" ] && echo " - 亮度步数: $(cat "$old_config/steps_num.txt")" - [ -s "$old_config/log_max_size.txt" ] && echo " - 日志限制: $(cat "$old_config/log_max_size.txt") KB" - [ -s "$old_config/blacklist_apps.txt" ] && echo " - 黑名单: $(wc -l <"$old_config/blacklist_apps.txt" | tr -d ' ') 个" + echo " - 前台最大亮度: $(echo "$out" | field ui_max_bri)" + echo " - 峰值最大亮度: $(echo "$out" | field max_bri)" + v="$(echo "$out" | field sleep_time)" + [ -n "$v" ] && echo " - 休眠时间: $v" + v="$(echo "$out" | field auto_bri_sleep)" + [ -n "$v" ] && echo " - 自动亮度时休眠: $(onoff "$v")" + v="$(echo "$out" | field steps_num)" + [ -n "$v" ] && echo " - 亮度步数: $v" + v="$(echo "$out" | field log_max_size)" + [ -n "$v" ] && echo " - 日志限制: $v KB" + v="$(echo "$out" | field blacklist_count)" + [ "$v" != "0" ] && [ -n "$v" ] && echo " - 黑名单: $v 个" echo "" echo " ❆ 按音量 + 沿用旧配置, 按音量 - 重新测试" if [ "$(btn)" = "0" ]; then - cfg_ui_max_bri="$(read_old_txt ui_max_bri.txt '0')" - cfg_max_bri="$(read_old_txt max_bri.txt '0')" - cfg_steps_num="$(read_old_txt steps_num.txt '50')" - cfg_log_max_size="$(read_old_txt log_max_size.txt '512')" - cfg_auto_bri_sleep="$(read_old_txt auto_bri_sleep.txt '1')" - cfg_display_hdr_sleep="$(read_old_txt display_hdr_sleep.txt '0')" - cfg_compatibility_mode="$(read_old_txt compatibility_mode.txt '0')" - cfg_sleep_time="$(read_old_txt sleep_time.txt '')" - cfg_inotify_events="$(read_old_txt inotify_events.txt 'c')" - cfg_now_bri_file="$(read_old_txt path/now_bri_file.txt "$DEFAULT_NOW_BRI_FILE")" - cfg_max_bri_file="$(read_old_txt path/max_bri_file.txt "$DEFAULT_MAX_BRI_FILE")" - - # 黑名单转 JSON 数组 - if [ -s "$old_config/blacklist_apps.txt" ]; then - cfg_blacklist_apps=$("$JQ" -Rs 'split("\n") | map(select(length > 0))' \ - "$old_config/blacklist_apps.txt" 2>/dev/null || echo '[]') - else - cfg_blacklist_apps='[]' - fi - - write_config_json - - # 删除旧 txt 配置文件 - rm -f "$old_config/"*.txt 2>/dev/null - rm -rf "$old_config/path" 2>/dev/null + "$BIN" config migrate "$old_config" >/dev/null 2>&1 + "$BIN" config remove-old-txt "$old_config" >/dev/null 2>&1 echo " ✦ 配置已迁移至 JSON, 旧文件已清理" return 0 - else - echo " ❆ 将重新测试" - return 1 fi + echo " ❆ 将重新测试" + return 1 fi return 1 @@ -294,41 +229,12 @@ IMPORT_OLD_CONFIG() { # 初始化默认配置 INIT_CONFIG() { mkdir -p "$mod_config" - if [ ! -f "$CONFIG_FILE" ]; then - cfg_ui_max_bri=0 - cfg_max_bri=0 - cfg_steps_num=50 - cfg_log_max_size=512 - cfg_auto_bri_sleep=1 - cfg_display_hdr_sleep=0 - cfg_hdr_enter_ratio=1.15 - cfg_hdr_exit_ratio=1.05 - cfg_compatibility_mode=0 - cfg_sleep_time="" - cfg_inotify_events="c" - cfg_now_bri_file="$DEFAULT_NOW_BRI_FILE" - cfg_max_bri_file="$DEFAULT_MAX_BRI_FILE" - cfg_blacklist_apps="[]" - cfg_log_level="info" - write_config_json - fi + "$BIN" config init 2>/dev/null } # 补全缺失字段 ENSURE_DEFAULTS() { - "$JQ" ' - .steps_num = (.steps_num // 50) | - .log_max_size = (.log_max_size // 512) | - .auto_bri_sleep = (.auto_bri_sleep // 1) | - .display_hdr_sleep = (.display_hdr_sleep // 0) | - .hdr_enter_ratio = (.hdr_enter_ratio // 1.15) | - .hdr_exit_ratio = (.hdr_exit_ratio // 1.05) | - .compatibility_mode= (.compatibility_mode // 0) | - .sleep_time = (.sleep_time // "") | - .inotify_events = (.inotify_events // "c") | - .log_level = (.log_level // "info") | - .blacklist_apps = (.blacklist_apps // []) - ' "$CONFIG_FILE" >"$CONFIG_FILE.tmp" && mv "$CONFIG_FILE.tmp" "$CONFIG_FILE" + "$BIN" config ensure 2>/dev/null } # 机型兼容性校验 @@ -342,7 +248,7 @@ CHECK_DEVICE_COMPATIBILITY() { echo " ✿ 您可能是 Xiaomi 17 Ultra 用户,建议使用 '0' 事件作为监测对象" echo " ✿ 是否将 inotifyd 监测事件修改为 '0'? (音量 + 确认,音量 - 跳过)" if [ "$(btn)" = "0" ]; then - "$JQ" '.inotify_events = "0"' "$CONFIG_FILE" >"$CONFIG_FILE.tmp" && mv "$CONFIG_FILE.tmp" "$CONFIG_FILE" + "$BIN" config set inotify_events=0 >/dev/null 2>&1 echo " ✦ 已设置为 0 事件监测" else echo " ✦ 已跳过" @@ -361,13 +267,16 @@ END() { echo "" sleep 1 + local summary + summary="$("$BIN" config summary 2>/dev/null)" + # 确保 now_bri_file / max_bri_file 已设置(import 路径可能未调用 CHECK_FILES) : "${now_bri_file:=$(cfg_get now_bri_file "$DEFAULT_NOW_BRI_FILE")}" : "${max_bri_file:=$(cfg_get max_bri_file "$DEFAULT_MAX_BRI_FILE")}" local final_ui final_max - final_ui=$("$JQ" -re 'if .ui_max_bri > 0 then .ui_max_bri else empty end' "$CONFIG_FILE" 2>/dev/null) - final_max=$("$JQ" -re 'if .max_bri > 0 then .max_bri else empty end' "$CONFIG_FILE" 2>/dev/null) + final_ui="$(cfg_pos ui_max_bri)" + final_max="$(cfg_pos max_bri)" if [ -z "$final_max" ] || [ -z "$final_ui" ]; then if [ "$NODE_MISSING" = "1" ]; then @@ -386,45 +295,33 @@ END() { echo " ❆ 或按音量 + 现在进行测试, 按音量 - 跳过" if [ "$(btn)" = "0" ]; then TEST_UI_MAX_BRI - final_ui=$("$JQ" -re 'if .ui_max_bri > 0 then .ui_max_bri else empty end' "$CONFIG_FILE" 2>/dev/null) - final_max=$("$JQ" -re 'if .max_bri > 0 then .max_bri else empty end' "$CONFIG_FILE" 2>/dev/null) + final_ui="$(cfg_pos ui_max_bri)" + final_max="$(cfg_pos max_bri)" + summary="$("$BIN" config summary 2>/dev/null)" fi fi fi + local steps log_size auto_bri disp_hdr st inotify bl_count now_path max_path + steps="$(echo "$summary" | field steps_num)" + log_size="$(echo "$summary" | field log_max_size)" + auto_bri="$(echo "$summary" | field auto_bri_sleep)" + disp_hdr="$(echo "$summary" | field display_hdr_sleep)" + st="$(echo "$summary" | field sleep_time)" + inotify="$(echo "$summary" | field inotify_events)" + now_path="$(echo "$summary" | field now_bri_file)" + max_path="$(echo "$summary" | field max_bri_file)" + bl_count="$(echo "$summary" | field blacklist_count)" + echo "" echo "======== 将要应用的配置 ========" echo " - 前台最大亮度: $final_ui" echo " - 峰值最大亮度: $final_max" - - local steps log_size auto_bri disp_hdr st inotify bl_count now_path max_path - steps=$("$JQ" -re '.steps_num' "$CONFIG_FILE" 2>/dev/null || echo "50") - log_size=$("$JQ" -re '.log_max_size' "$CONFIG_FILE" 2>/dev/null || echo "512") - auto_bri=$("$JQ" -re '.auto_bri_sleep' "$CONFIG_FILE" 2>/dev/null || echo "1") - disp_hdr=$("$JQ" -re '.display_hdr_sleep' "$CONFIG_FILE" 2>/dev/null || echo "0") - st=$("$JQ" -re '.sleep_time // empty' "$CONFIG_FILE" 2>/dev/null) - inotify=$("$JQ" -re '.inotify_events' "$CONFIG_FILE" 2>/dev/null || echo "c") - now_path=$("$JQ" -re '.now_bri_file' "$CONFIG_FILE" 2>/dev/null || echo "$DEFAULT_NOW_BRI_FILE") - max_path=$("$JQ" -re '.max_bri_file' "$CONFIG_FILE" 2>/dev/null || echo "$DEFAULT_MAX_BRI_FILE") - bl_count=$("$JQ" -re '.blacklist_apps | length' "$CONFIG_FILE" 2>/dev/null || echo "0") - echo " - 亮度渐变步数: $steps" echo " - 日志大小上限: ${log_size} KB" - if [ "$auto_bri" = "1" ]; then - echo " - 自动亮度时跳过: 开启" - else - echo " - 自动亮度时跳过: 关闭" - fi - if [ "$disp_hdr" = "1" ]; then - echo " - HDR 内容时跳过: 开启" - else - echo " - HDR 内容时跳过: 关闭" - fi - if [ "$("$JQ" -re '.compatibility_mode' "$CONFIG_FILE" 2>/dev/null || echo "0")" = "1" ]; then - echo " - 兼容模式 (轮询): 开启" - else - echo " - 兼容模式 (轮询): 关闭" - fi + echo " - 自动亮度时跳过: $(onoff "$auto_bri")" + echo " - HDR 内容时跳过: $(onoff "$disp_hdr")" + echo " - 兼容模式 (轮询): $(onoff "$(echo "$summary" | field compatibility_mode)")" if [ -n "$st" ]; then echo " - 休眠时段: $st" else diff --git a/go/cmd/luminpro/main.go b/go/cmd/luminpro/main.go index 318baa9..8b815d9 100644 --- a/go/cmd/luminpro/main.go +++ b/go/cmd/luminpro/main.go @@ -109,6 +109,27 @@ func runConfig(paths daemon.Paths, args []string) error { return fmt.Errorf("set 需要至少一个 key=value") } return config.Set(paths.ConfigFile, args[1:]) + case "get": + if len(args) < 2 { + return fmt.Errorf("get 需要字段名") + } + cfg, err := config.Load(paths.ConfigFile) + if err != nil { + return err + } + value, ok := cfg.Get(args[1]) + if !ok { + return fmt.Errorf("未知字段: %s", args[1]) + } + fmt.Println(value) + return nil + case "summary": + cfg, err := config.Load(paths.ConfigFile) + if err != nil { + return err + } + printMap(cfg.Summary()) + return nil case "inspect": if len(args) < 2 { return fmt.Errorf("inspect 需要旧配置目录") @@ -146,12 +167,17 @@ func runConfig(paths daemon.Paths, args []string) error { // printOld 输出 key=value 行,供安装脚本读取展示。 func printOld(old config.OldConfig) { fmt.Printf("format=%s\n", old.Format) - keys := make([]string, 0, len(old.Values)) - for k := range old.Values { + printMap(old.Values) +} + +// printMap 按键排序输出 key=value 行。 +func printMap(values map[string]string) { + keys := make([]string, 0, len(values)) + for k := range values { keys = append(keys, k) } sort.Strings(keys) for _, k := range keys { - fmt.Printf("%s=%s\n", k, old.Values[k]) + fmt.Printf("%s=%s\n", k, values[k]) } } diff --git a/go/internal/config/config.go b/go/internal/config/config.go index 8eaa7f0..7c75005 100644 --- a/go/internal/config/config.go +++ b/go/internal/config/config.go @@ -303,3 +303,55 @@ func (c Config) toRawMap() map[string]json.RawMessage { func (c Config) Blacklist() []string { return append([]string(nil), c.BlacklistApps...) } + +// Get 返回字段的纯文本表示(供 shell 使用):字符串原样,数字/布尔去引号, +// 数组与对象返回 JSON。第二个返回值表示字段是否存在。 +func (c Config) Get(key string) (string, bool) { + raw, ok := c.toRawMap()[key] + if !ok { + return "", false + } + var v any + if err := json.Unmarshal(raw, &v); err != nil { + return "", false + } + switch value := v.(type) { + case string: + return value, true + case float64: + return strconv.FormatFloat(value, 'f', -1, 64), true + case bool: + return strconv.FormatBool(value), true + case nil: + return "", true + default: + b, err := json.Marshal(v) + if err != nil { + return "", false + } + return string(b), true + } +} + +// Summary 返回安装界面需要展示的字段(key=value 形式),供 shell 读取。 +func (c Config) Summary() map[string]string { + out := map[string]string{ + "ui_max_bri": strconv.Itoa(c.UIMaxBri), + "max_bri": strconv.Itoa(c.MaxBri), + "steps_num": strconv.Itoa(c.StepsNum), + "log_max_size": strconv.Itoa(c.LogMaxSize), + "auto_bri_sleep": strconv.Itoa(c.AutoBriSleep), + "display_hdr_sleep": strconv.Itoa(c.DisplayHdrSleep), + "hdr_enter_ratio": strconv.FormatFloat(c.HdrEnterRatio, 'f', -1, 64), + "hdr_exit_ratio": strconv.FormatFloat(c.HdrExitRatio, 'f', -1, 64), + "compatibility_mode": strconv.Itoa(c.CompatibilityMode), + "sleep_time": c.SleepTime, + "inotify_events": c.InotifyEvents, + "now_bri_file": c.NowBriFile, + "max_bri_file": c.MaxBriFile, + "log_level": c.LogLevel, + "debug_mode": strconv.Itoa(c.DebugMode), + "blacklist_count": strconv.Itoa(len(c.BlacklistApps)), + } + return out +} diff --git a/rust/.cargo/config.toml b/rust/.cargo/config.toml deleted file mode 100644 index 64b7820..0000000 --- a/rust/.cargo/config.toml +++ /dev/null @@ -1,3 +0,0 @@ -[target.x86_64-pc-windows-msvc] -linker = "rust-lld" -rustflags = ["-C", "linker-flavor=lld-link"] diff --git a/rust/Cargo.lock b/rust/Cargo.lock deleted file mode 100644 index 728baee..0000000 --- a/rust/Cargo.lock +++ /dev/null @@ -1,112 +0,0 @@ -# This file is automatically @generated by Cargo. -# It is not intended for manual editing. -version = 4 - -[[package]] -name = "bitflags" -version = "1.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" - -[[package]] -name = "futures-core" -version = "0.3.32" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7e3450815272ef58cec6d564423f6e755e25379b217b0bc688e295ba24df6b1d" - -[[package]] -name = "inotify" -version = "0.10.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fdd168d97690d0b8c412d6b6c10360277f4d7ee495c5d0d5d5fe0854923255cc" -dependencies = [ - "bitflags", - "futures-core", - "inotify-sys", - "libc", - "tokio", -] - -[[package]] -name = "inotify-sys" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e05c02b5e89bff3b946cedeca278abc628fe811e604f027c45a8aa3cf793d0eb" -dependencies = [ - "libc", -] - -[[package]] -name = "libc" -version = "0.2.184" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "48f5d2a454e16a5ea0f4ced81bd44e4cfc7bd3a507b61887c99fd3538b28e4af" - -[[package]] -name = "lumipro" -version = "0.1.0" -dependencies = [ - "inotify", - "libc", -] - -[[package]] -name = "mio" -version = "1.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "50b7e5b27aa02a74bac8c3f23f448f8d87ff11f92d3aac1a6ed369ee08cc56c1" -dependencies = [ - "libc", - "wasi", - "windows-sys", -] - -[[package]] -name = "pin-project-lite" -version = "0.2.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" - -[[package]] -name = "socket2" -version = "0.6.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3a766e1110788c36f4fa1c2b71b387a7815aa65f88ce0229841826633d93723e" -dependencies = [ - "libc", - "windows-sys", -] - -[[package]] -name = "tokio" -version = "1.51.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f66bf9585cda4b724d3e78ab34b73fb2bbaba9011b9bfdf69dc836382ea13b8c" -dependencies = [ - "libc", - "mio", - "pin-project-lite", - "socket2", - "windows-sys", -] - -[[package]] -name = "wasi" -version = "0.11.1+wasi-snapshot-preview1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" - -[[package]] -name = "windows-link" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" - -[[package]] -name = "windows-sys" -version = "0.61.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" -dependencies = [ - "windows-link", -] diff --git a/rust/Cargo.toml b/rust/Cargo.toml deleted file mode 100644 index 0938dcf..0000000 --- a/rust/Cargo.toml +++ /dev/null @@ -1,20 +0,0 @@ -[package] -name = "lumipro" -version = "0.1.0" -edition = "2021" - -[[bin]] -name = "lumipro" -path = "src/main.rs" - -# Linux/Android 专用依赖(本地 Windows 不编译,仅 GitHub Actions 使用) -[target.'cfg(any(target_os = "linux", target_os = "android"))'.dependencies] -inotify = "0.10" -libc = "0.2" - -[profile.release] -opt-level = "z" -lto = true -codegen-units = 1 -strip = true -panic = "abort" diff --git a/rust/src/main.rs b/rust/src/main.rs deleted file mode 100644 index b17f3a5..0000000 --- a/rust/src/main.rs +++ /dev/null @@ -1,237 +0,0 @@ -//! lumipro: 带防抖的 inotify 监听工具 -//! -//! 用法: lumipro [--debug] [--debounce ] [...] -//! -//! 事件字母与 Android toybox inotifyd 完全兼容: -//! a=ACCESS c=MODIFY e=ATTRIB w=CLOSE_WRITE -//! 0=CLOSE_NOWRITE r=OPEN n=CREATE d=DELETE -//! D=DELETE_SELF M=MOVE_SELF m=MOVED_TO y=MOVED_FROM -//! u=UNMOUNT o=OVERFLOW x=IGNORED *=ALL -//! -//! 防抖机制: 在指定窗口期内多次触发时,只执行最后一次;handler 执行期间 -//! 积压的事件(如亮度渐变写入)在 handler 返回后统一丢弃。 - -#[cfg(any(target_os = "linux", target_os = "android"))] -mod linux { - use std::collections::HashMap; - use std::os::unix::io::AsRawFd; - use std::path::PathBuf; - use std::process::Command; - use std::time::{Duration, Instant}; - - use inotify::{EventMask, Inotify, WatchDescriptor, WatchMask}; - - fn letters_to_mask(letters: &str) -> WatchMask { - let mut mask = WatchMask::empty(); - for c in letters.chars() { - mask |= match c { - 'a' => WatchMask::ACCESS, - 'c' => WatchMask::MODIFY, // toybox: modified - 'e' => WatchMask::ATTRIB, // toybox: metadata change - 'w' => WatchMask::CLOSE_WRITE, // toybox: closed (writable) - '0' => WatchMask::CLOSE_NOWRITE, // toybox: closed (unwritable) - 'r' => WatchMask::OPEN, // toybox: opened - 'n' => WatchMask::CREATE, - 'd' => WatchMask::DELETE, - 'D' => WatchMask::DELETE_SELF, - 'M' => WatchMask::MOVE_SELF, - 'm' => WatchMask::MOVED_TO, // toybox: moved in - 'y' => WatchMask::MOVED_FROM, // toybox: moved out - 'u' => WatchMask::empty(), // toybox: unmounted — 内核产生,不设置 watch mask - '*' => WatchMask::ALL_EVENTS, - // 'o'=overflow 'x'=ignored 为内核产生,不设置 watch mask - _ => WatchMask::empty(), - }; - } - mask - } - - fn mask_to_letters(mask: EventMask) -> String { - let mut s = String::new(); - if mask.contains(EventMask::ACCESS) { s.push('a'); } - if mask.contains(EventMask::MODIFY) { s.push('c'); } - if mask.contains(EventMask::ATTRIB) { s.push('e'); } - if mask.contains(EventMask::CLOSE_WRITE) { s.push('w'); } - if mask.contains(EventMask::CLOSE_NOWRITE) { s.push('0'); } - if mask.contains(EventMask::OPEN) { s.push('r'); } - if mask.contains(EventMask::MOVED_FROM) { s.push('y'); } - if mask.contains(EventMask::MOVED_TO) { s.push('m'); } - if mask.contains(EventMask::CREATE) { s.push('n'); } - if mask.contains(EventMask::DELETE) { s.push('d'); } - if mask.contains(EventMask::DELETE_SELF) { s.push('D'); } - if mask.contains(EventMask::MOVE_SELF) { s.push('M'); } - if mask.contains(EventMask::UNMOUNT) { s.push('u'); } - if mask.contains(EventMask::Q_OVERFLOW) { s.push('o'); } - if mask.contains(EventMask::IGNORED) { s.push('x'); } - if s.is_empty() { s.push('?'); } - s - } - - /// 对 inotify fd 执行 poll,返回是否有可读事件。 - /// timeout_ms = -1 为永久阻塞,0 为立即返回。 - fn poll_readable(fd: i32, timeout_ms: i32) -> bool { - let mut pfd = libc::pollfd { - fd, - events: libc::POLLIN, - revents: 0, - }; - // SAFETY: pfd 为合法的 pollfd,nfds=1,fd 由 Inotify 保证有效。 - unsafe { libc::poll(&mut pfd as *mut libc::pollfd, 1, timeout_ms) > 0 } - } - - struct Pending { - triggered_at: Instant, - event_letters: String, - path: PathBuf, - } - - pub fn run() { - let args: Vec = std::env::args().skip(1).collect(); - let mut idx = 0; - - let mut debounce_ms: u64 = 300; - let mut debug = false; - - loop { - match args.get(idx).map(String::as_str) { - Some("--debug") => { debug = true; idx += 1; } - Some("--debounce") => { - idx += 1; - debounce_ms = args.get(idx).and_then(|s| s.parse().ok()).unwrap_or(300); - idx += 1; - } - _ => break, - } - } - - let handler = match args.get(idx) { - Some(h) => h.clone(), - None => { - eprintln!("Usage: lumipro [--debounce ] ..."); - std::process::exit(1); - } - }; - idx += 1; - - if idx >= args.len() { - eprintln!("Error: no watch targets specified"); - std::process::exit(1); - } - - let mut inotify = Inotify::init().expect("inotify_init failed"); - - // 设置 O_NONBLOCK,使 read_events 在无数据时立即返回 WouldBlock, - // 避免 drain 循环阻塞。 - let inotify_fd = inotify.as_raw_fd(); - unsafe { - let flags = libc::fcntl(inotify_fd, libc::F_GETFL, 0); - libc::fcntl(inotify_fd, libc::F_SETFL, flags | libc::O_NONBLOCK); - } - - let mut watches: HashMap = HashMap::new(); - for spec in &args[idx..] { - let (path_str, letters) = match spec.find(':') { - Some(i) => (&spec[..i], &spec[i + 1..]), - None => (spec.as_str(), "c"), - }; - let path = PathBuf::from(path_str); - let mask = letters_to_mask(letters); - match inotify.watches().add(&path, mask) { - Ok(wd) => { - if debug { - eprintln!("[lumipro] watching: {} events: {}", path_str, letters); - } - watches.insert(wd, (path, letters.to_string())); - } - Err(e) => { - eprintln!("Failed to watch {path_str}: {e}"); - std::process::exit(1); - } - } - } - - if debug { - eprintln!("[lumipro] debounce={}ms handler={}", debounce_ms, handler); - } - - let debounce = Duration::from_millis(debounce_ms); - let mut pending: Option = None; - let mut buffer = [0u8; 4096]; - - loop { - // ── 1. 计算本次 poll 超时 ────────────────────────────────────────── - let timeout_ms: i32 = match &pending { - // 无待触发事件:永久阻塞直到新事件到来 - None => -1, - Some(p) => { - let elapsed = p.triggered_at.elapsed(); - if elapsed >= debounce { - 0 // 防抖窗口已过期,跳过 poll 直接触发 - } else { - (debounce - elapsed).as_millis().min(i32::MAX as u128) as i32 - } - } - }; - - // timeout_ms == 0 时跳过 poll(防抖已到期),直接进入触发分支 - let has_data = timeout_ms != 0 && poll_readable(inotify_fd, timeout_ms); - - if has_data { - // ── 2. 有新事件:读取并重置防抖计时器 ─────────────────────── - match inotify.read_events(&mut buffer) { - Ok(events) => { - for event in events { - if let Some((path, _)) = watches.get(&event.wd) { - let letters = mask_to_letters(event.mask); - if debug { - eprintln!("[lumipro] event: {} path: {}", letters, path.display()); - } - pending = Some(Pending { - triggered_at: Instant::now(), - event_letters: letters, - path: path.clone(), - }); - } - } - } - Err(ref e) if e.kind() == std::io::ErrorKind::WouldBlock => {} - Err(e) => eprintln!("read_events: {e}"), - } - } else if let Some(p) = pending.take() { - // ── 3. 防抖窗口结束:同步执行 handler ─────────────────────── - if debug { - eprintln!("[lumipro] debounce fired → handler: {} {}", p.event_letters, p.path.display()); - } - let _ = Command::new(&handler) - .arg(&p.event_letters) - .arg(&p.path) - .status(); - - // ── 4. 丢弃 handler 执行期间(亮度渐变写入)积压的全部事件 ─ - let mut drained = 0usize; - loop { - match inotify.read_events(&mut buffer) { - Ok(events) => { - for _ in events { drained += 1; } - } - Err(_) => break, // WouldBlock:积压已清空 - } - } - if debug && drained > 0 { - eprintln!("[lumipro] drain: discarded {} event(s)", drained); - } - } - } - } -} - -fn main() { - #[cfg(any(target_os = "linux", target_os = "android"))] - linux::run(); - - #[cfg(not(any(target_os = "linux", target_os = "android")))] - { - eprintln!("lumipro: only supported on Linux/Android"); - std::process::exit(1); - } -} diff --git a/script/daemon.sh b/script/daemon.sh deleted file mode 100644 index 259e8a3..0000000 --- a/script/daemon.sh +++ /dev/null @@ -1,140 +0,0 @@ -#!/system/bin/sh -#shellcheck shell=ash -# LuminPro 守护进程 - -REAL_PATH="$(readlink -f "$0")" -SCRIPT_DIR="$(dirname "$REAL_PATH")" -MODDIR="$(dirname "$SCRIPT_DIR")" - -PID_DIR="$MODDIR/pid" -CONFIG_FILE="$MODDIR/config/config.json" -JQ="$MODDIR/bin/jq" -pid_file="$PID_DIR/inotifyd.pid" -stop_file="$PID_DIR/stop.flag" -pause_file="$PID_DIR/daemon.pause" -log_file="$MODDIR/service.log" -config_cache_file="$PID_DIR/.config_cache" - -DEFAULT_NOW_BRI_FILE="/sys/class/backlight/panel0-backlight/brightness" - -get_cfg() { - local key="$1" default="$2" - local val - if val=$("$JQ" -re ".${key}" "$CONFIG_FILE" 2>/dev/null); then - echo "$val" - else - echo "$default" - fi -} - -get_config_hash() { - local now_file events - now_file="$(get_cfg now_bri_file "$DEFAULT_NOW_BRI_FILE")" - events="$(get_cfg inotify_events "c")" - echo "${now_file}|${events}" -} - -_log() { - local level="${2:-INFO}" - local ll - ll="$(get_cfg log_level "info")" - case "$ll" in - off) return ;; - error) case "$level" in ERROR) ;; *) return ;; esac ;; - warn) case "$level" in ERROR | WARN) ;; *) return ;; esac ;; - esac - printf '[%s] [%s] [%s] %s\n' "$(date '+%m-%d %H:%M:%S')" "daemon" "$level" "$1" >>"$log_file" -} - -mkdir -p "$PID_DIR" -_log "守护进程已启动" "INFO" - -while true; do - if [ -f "$stop_file" ]; then - [ -f "$pid_file" ] && kill -9 "$(cat "$pid_file")" 2>/dev/null - rm -f "$pid_file" - _log "检测到停止信号,守护进程挂起" "WARN" - sleep 5 - continue - fi - - if [ -f "$pause_file" ]; then - [ -f "$pid_file" ] && kill -9 "$(cat "$pid_file")" 2>/dev/null - rm -f "$pid_file" - sleep 1 - continue - fi - - current_config="$(get_config_hash)" - - if [ -f "$config_cache_file" ]; then - cached_config="$(cat "$config_cache_file")" - if [ "$current_config" != "$cached_config" ]; then - _log "检测到配置变更,重启监听进程" "INFO" - [ -f "$pid_file" ] && kill -9 "$(cat "$pid_file")" 2>/dev/null - rm -f "$pid_file" - echo "$current_config" >"$config_cache_file" - sleep 1 - continue - fi - else - echo "$current_config" >"$config_cache_file" - fi - - compatibility_mode="$(get_cfg compatibility_mode "0")" - now_bri_file="${current_config%|*}" - - # 亮度节点不存在时挂起监听 (功能未启用或路径配置错误),等待节点出现或配置变更 - if [ ! -f "$now_bri_file" ]; then - if [ -z "$node_wait_logged" ]; then - _log "亮度节点不存在: $now_bri_file,功能挂起,每 10 秒重试" "ERROR" - node_wait_logged=1 - fi - sleep 10 - continue - fi - if [ -n "$node_wait_logged" ]; then - _log "亮度节点已就绪: $now_bri_file" "INFO" - node_wait_logged="" - fi - - if [ "$compatibility_mode" = "1" ]; then - _log "兼容模式已开启 (轮询驱动)" "WARN" - # 写入一个特殊的 PID 标识轮询模式 - echo "polling" >"$pid_file" - while true; do - if [ -f "$stop_file" ] || [ -f "$pause_file" ]; then - break - fi - # 检查配置哈希是否变化 - new_config="$(get_config_hash)" - if [ "$new_config" != "$current_config" ]; then - break - fi - sh "$MODDIR/script/up.sh" & - sleep 2 - done - _log "轮询模式已退出" "INFO" - else - _log "正在启动 lumipro 监听" "INFO" - inotify_events="${current_config#*|}" - debug_mode="$(get_cfg debug_mode "0")" - - # 缓存当前监听路径(供参考) - echo -n "$now_bri_file" >"$MODDIR/config/.cached_path" - - if [ "$debug_mode" = "1" ]; then - "$MODDIR/bin/lumipro" --debug "$MODDIR/script/up.sh" "$now_bri_file:$inotify_events" >>"$log_file" 2>&1 & - else - "$MODDIR/bin/lumipro" "$MODDIR/script/up.sh" "$now_bri_file:$inotify_events" >>"$log_file" 2>&1 & - fi - inotify_pid=$! - echo "$inotify_pid" >"$pid_file" - _log "lumipro 已启动 (PID: $inotify_pid), 监听: $now_bri_file, 事件: $inotify_events" "SUCCESS" - - wait "$inotify_pid" - _log "lumipro 进程 (PID: $inotify_pid) 已退出,即将重启" "WARN" - fi - - sleep 0.5 -done diff --git a/script/restart.sh b/script/restart.sh index 6573c54..e02195e 100644 --- a/script/restart.sh +++ b/script/restart.sh @@ -1,82 +1,7 @@ #!/system/bin/sh -# LuminPro 服务重启脚本 +#shellcheck shell=ash + +# LuminPro 服务重启脚本(转发到 Go 实现) MODDIR="${0%/*/*}" -PID_DIR="$MODDIR/pid" -pid_file="$PID_DIR/inotifyd.pid" -flag_file="$PID_DIR/up.flag" -log_file="$MODDIR/service.log" -CONFIG_FILE="$MODDIR/config/config.json" -JQ="$MODDIR/bin/jq" - -DEFAULT_NOW_BRI_FILE="/sys/class/backlight/panel0-backlight/brightness" - -get_cfg() { - local key="$1" default="$2" - local val - if val=$("$JQ" -re ".${key}" "$CONFIG_FILE" 2>/dev/null); then - echo "$val" - else - echo "$default" - fi -} - -_log() { - printf '[%s] [restart] %s\n' "$(date '+%d %H:%M:%S.%3N')" "$1" >>"$log_file" -} - -_log "收到手动重启请求" - -pause_file="$PID_DIR/daemon.pause" -oplock_file="$PID_DIR/oplock" - -# 持操作锁:覆盖守护进程重建窗口,WebUI 据此暂停刷新并禁用写操作 -mkdir -p "$PID_DIR" -echo $$ >"$oplock_file" -# shellcheck disable=SC2064 -trap "rm -f '$oplock_file'" EXIT HUP INT TERM - -# 1. 通知守护进程挂起,终止 lumipro 实例 -_log "通知守护进程挂起,清理 lumipro 实例" -touch "$pause_file" -[ -f "$pid_file" ] && kill -9 "$(cat "$pid_file")" 2>/dev/null - -# 2. 清理遗留标记 -rm -f "$pid_file" -rm -f "$flag_file" -rm -f "$PID_DIR/up.lock" -_log "已清理锁文件" - -# 3. 恢复守护进程 (它会自动拉起新监听) -rm -f "$pause_file" - -# 4. 守护进程未运行时 (亮度节点不可用导致服务未启动),按需拉起 -if ! pgrep -f "script/daemon.sh" >/dev/null 2>&1; then - now_bri_file="$(get_cfg now_bri_file "$DEFAULT_NOW_BRI_FILE")" - if [ ! -f "$now_bri_file" ]; then - _log "亮度节点不存在 ($now_bri_file),拒绝启动服务" - echo "亮度节点不存在: $now_bri_file,无法启动服务,请先在配置页填写正确路径" >&2 - exit 1 - fi - _log "守护进程未运行,正在启动" - sh "$MODDIR/script/daemon.sh" & - _log "守护进程已启动 (PID: $!)" -else - _log "守护进程已恢复,等待自动拉起监听" -fi - -# 5. 等待新监听就绪,让操作锁覆盖守护进程重建窗口 -wait_i=0 -while [ "$wait_i" -lt 15 ]; do - if [ -f "$pid_file" ]; then - new_pid="$(cat "$pid_file" 2>/dev/null)" - if [ "$new_pid" = "polling" ] || { [ -n "$new_pid" ] && [ -d "/proc/$new_pid" ]; }; then - _log "新监听已就绪 (PID: $new_pid)" - break - fi - fi - sleep 0.2 - wait_i=$((wait_i + 1)) -done - -exit 0 +exec "$MODDIR/bin/luminpro" restart diff --git a/script/up.sh b/script/up.sh deleted file mode 100644 index 4615902..0000000 --- a/script/up.sh +++ /dev/null @@ -1,216 +0,0 @@ -#!/system/bin/sh -#shellcheck shell=ash -# 亮度提升脚本 - -MODDIR="${0%/*/*}" -CONFIG_FILE="$MODDIR/config/config.json" -JQ="$MODDIR/bin/jq" -PID_DIR="$MODDIR/pid" -stop_file="$PID_DIR/stop.flag" -log_file="$MODDIR/service.log" - -DEFAULT_NOW_BRI_FILE="/sys/class/backlight/panel0-backlight/brightness" - -get_cfg() { - local key="$1" default="$2" - local val - if val=$("$JQ" -re ".${key}" "$CONFIG_FILE" 2>/dev/null); then - echo "$val" - else - echo "$default" - fi -} - -now_bri_file="$(get_cfg now_bri_file "$DEFAULT_NOW_BRI_FILE")" -log_level="$(get_cfg log_level "info")" - -_log() { - local level="${2:-INFO}" - - case "$1" in - "日志超限"*) ;; - *) if [ -f "$stop_file" ]; then return; fi ;; - esac - - case "$log_level" in - off) return ;; - error) case "$level" in ERROR) ;; *) return ;; esac ;; - warn) case "$level" in ERROR | WARN) ;; *) return ;; esac ;; - esac - - local max_size - max_size="$(get_cfg log_max_size 500)" - if [ -f "$log_file" ]; then - local cur_size - cur_size=$(du -k "$log_file" | cut -f1) - if [ "$cur_size" -ge "$max_size" ]; then - printf '[%s] [%s] [%s] %s\n' "$(date '+%m-%d %H:%M:%S')" "up" "WARN" "日志超限 (${cur_size}KB / ${max_size}KB),已自动重置" >"$log_file" - fi - fi - printf '[%s] [%s] [%s] %s\n' "$(date '+%m-%d %H:%M:%S')" "up" "$level" "$1" >>"$log_file" -} - -if [ -f "$stop_file" ]; then - _log "服务已暂停,跳过本次处理" "WARN" - exit 0 -fi - -# 防止 up.sh 自身读写亮度节点时触发 inotify 事件导致递归调用 -lock_file="$PID_DIR/up.lock" -# 操作锁:仅在真正写亮度节点期间持有,供 WebUI 暂停刷新并禁用写操作 -oplock_file="$PID_DIR/oplock" -if [ -f "$lock_file" ]; then - old_pid=$(cat "$lock_file" 2>/dev/null) - if [ -n "$old_pid" ] && [ -d "/proc/$old_pid" ]; then - exit 0 - fi - # PID 不存在,说明是遗留的锁,清理之 - _log "检测到遗留的锁文件 (PID: $old_pid 不存在),已自动清除" "WARN" - rm -f "$lock_file" -fi -echo $$ >"$lock_file" -# shellcheck disable=SC2064 -trap "rm -f '$lock_file' '$oplock_file'" EXIT HUP INT TERM - -# 读取配置 -ui_max_bri="$(get_cfg ui_max_bri 0)" -max_bri="$(get_cfg max_bri 0)" -sleep_time="$(get_cfg sleep_time '')" -auto_bri_sleep="$(get_cfg auto_bri_sleep 1)" -display_hdr_sleep="$(get_cfg display_hdr_sleep 0)" -hdr_enter_ratio="$(get_cfg hdr_enter_ratio 1.15)" -hdr_exit_ratio="$(get_cfg hdr_exit_ratio 1.05)" -steps_num="$(get_cfg steps_num 50)" - -# 解析休眠时间 -sleep_start="${sleep_time%-*}" -sleep_end="${sleep_time#*-}" - -IS_SLEEP_TIME() { - local now - now="$(date '+%H%M')" - [ -z "$sleep_start" ] || [ -z "$sleep_end" ] && return 1 - [ "$sleep_start" = "$sleep_end" ] && return 1 - if [ "$sleep_start" -gt "$sleep_end" ]; then - [ "$now" -ge "$sleep_start" ] || [ "$now" -lt "$sleep_end" ] - else - [ "$now" -ge "$sleep_start" ] && [ "$now" -lt "$sleep_end" ] - fi -} - -target_bri="$max_bri" - -update_all() { - local step rc=0 - # 持操作锁:仅在写亮度节点期间,WebUI 据此暂停刷新并禁用写操作 - echo $$ >"$oplock_file" - - start_bri="$(cat "$now_bri_file")" - bri_diff="$((target_bri - start_bri))" - step_value="$((bri_diff / steps_num))" - - if [ "$step_value" -eq 0 ]; then - _log "差値过小,直接设定亮度: $target_bri" "INFO" - echo -n "$target_bri" >"$now_bri_file" || rc=1 - else - _log "开始渐变调整: $start_bri → $target_bri ($steps_num 步)" "INFO" - for step in $(seq 1 "$steps_num"); do - echo -n $((start_bri + step * step_value)) >"$now_bri_file" - sleep 0.02 - done - echo -n "$target_bri" >"$now_bri_file" || rc=1 - fi - - rm -f "$oplock_file" - return "$rc" -} - -CHECK_BRI() { - local cycle_num now_bri - # shellcheck disable=SC2034 - for cycle_num in $(seq 1 10); do - now_bri="$(cat "$now_bri_file")" - if [ "$now_bri" -ge "$ui_max_bri" ] && [ "$now_bri" -lt "$target_bri" ]; then - _log "触发提升: 当前亮度 $now_bri ≥ 阈値 $ui_max_bri,目标 $target_bri" "INFO" - if update_all; then - _log "亮度提升完成 ($target_bri)" "SUCCESS" - return 0 - else - _log "亮度提升失败: 无法写入亮度节点" "ERROR" - return 1 - fi - fi - sleep 0.3 - done - return 1 -} - -MAIN() { - if IS_SLEEP_TIME; then - _log "处于休眠时段 ($sleep_start-$sleep_end),跳过提升" "INFO" - return - fi - - if [ "$auto_bri_sleep" = "1" ]; then - local mode - mode="$(settings get system screen_brightness_mode 2>/dev/null)" - if [ "$mode" = "1" ]; then - _log "自动亮度已启用,跳过提升" "INFO" - return - fi - fi - - # 黑名单检测(从 JSON 数组读取) - local blacklist_len - blacklist_len=$("$JQ" -r '.blacklist_apps | length' "$CONFIG_FILE" 2>/dev/null || echo "0") - if [ "${blacklist_len:-0}" -gt 0 ]; then - local current_focus current_app - current_focus="$(dumpsys window | grep mCurrentFocus | sed 's/.*u[0-9][0-9]* //' | sed 's/}.*//')" - current_app="${current_focus%%/*}" - if [ -n "$current_focus" ] && - "$JQ" -re --arg f "$current_focus" --arg a "$current_app" \ - '.blacklist_apps | map(. == $f or . == $a) | any' \ - "$CONFIG_FILE" >/dev/null 2>&1; then - _log "当前前台 ($current_focus) 在黑名单中,跳过提升" "INFO" - return - fi - fi - - # 显示 HDR 内容时休眠 (迟滞: 比率达到进入阈值休眠, 降至退出阈值恢复) - if [ "$display_hdr_sleep" = "1" ]; then - local hdr_state_file="$PID_DIR/hdr.flag" - local hdr_cache_file="$PID_DIR/.hdr_ratio_cache" - local hdr_ratio - hdr_ratio="$(dumpsys display 2>/dev/null | sed -n 's/.*hdrSdrRatio \([0-9.]*\).*/\1/p' | head -n 1)" - if echo "$hdr_ratio" | grep -qE '^[0-9]+\.[0-9]+$'; then - echo -n "$hdr_ratio" >"$hdr_cache_file" - elif [ -f "$hdr_cache_file" ]; then - hdr_ratio="$(cat "$hdr_cache_file")" - _log "HDR 比率读取为空,使用缓存值: $hdr_ratio" "INFO" - fi - if echo "$hdr_ratio" | grep -qE '^[0-9]+\.[0-9]+$'; then - hdr_ratio="$(awk "BEGIN{printf \"%.2f\", $hdr_ratio}")" - if [ -f "$hdr_state_file" ]; then - if awk "BEGIN{exit !($hdr_ratio <= $hdr_exit_ratio)}" 2>/dev/null; then - rm -f "$hdr_state_file" - _log "HDR 休眠解除 (比率: $hdr_ratio ≤ 退出阈值 $hdr_exit_ratio)" "INFO" - else - _log "HDR 休眠中 (比率: $hdr_ratio),跳过提升" "INFO" - return - fi - elif awk "BEGIN{exit !($hdr_ratio >= $hdr_enter_ratio)}" 2>/dev/null; then - touch "$hdr_state_file" - _log "检测到 HDR 内容 (比率: $hdr_ratio ≥ 进入阈值 $hdr_enter_ratio),进入休眠" "INFO" - return - fi - elif [ -f "$hdr_state_file" ]; then - _log "HDR 比率不可读,保持休眠,跳过提升" "INFO" - return - fi - fi - - CHECK_BRI -} - -MAIN -exit 0 diff --git a/service.sh b/service.sh index e4bde6f..85c0930 100755 --- a/service.sh +++ b/service.sh @@ -1,28 +1,19 @@ #!/system/bin/sh #shellcheck shell=ash +# LuminPro 模块启动入口:等待系统就绪后拉起 Go 守护进程 + MODDIR="${0%/*}" -CONFIG_FILE="$MODDIR/config/config.json" -JQ="$MODDIR/bin/jq" +BIN="$MODDIR/bin/luminpro" log_file="$MODDIR/service.log" DEFAULT_NOW_BRI_FILE="/sys/class/backlight/panel0-backlight/brightness" -DEFAULT_MAX_BRI_FILE="/sys/class/backlight/panel0-backlight/max_brightness" - -get_cfg() { - local key="$1" default="$2" - local val - if val=$("$JQ" -re ".${key}" "$CONFIG_FILE" 2>/dev/null); then - echo "$val" - else - echo "$default" - fi -} _log() { local level="${2:-INFO}" local ll - ll="$(get_cfg log_level "info")" + ll="$("$BIN" config get log_level 2>/dev/null)" + [ -n "$ll" ] || ll="info" case "$ll" in off) return ;; error) case "$level" in ERROR) ;; *) return ;; esac ;; @@ -38,14 +29,10 @@ sleep 30 rm -f "$MODDIR/pid/"*.flag "$MODDIR/pid/"*.pause "$MODDIR/pid/"*.lock "$MODDIR/pid/oplock" "$MODDIR/pid/.hdr_ratio_cache" _log "LuminPro 服务启动" "INFO" -_log "前台最大亮度: $(get_cfg ui_max_bri 0)" "INFO" -_log "峰值最大亮度: $(get_cfg max_bri 0)" "INFO" -_log "休眠时段: $(get_cfg sleep_time '')" "INFO" -now_bri_file="$(get_cfg now_bri_file "$DEFAULT_NOW_BRI_FILE")" -max_bri_file="$(get_cfg max_bri_file "$DEFAULT_MAX_BRI_FILE")" +now_bri_file="$("$BIN" config get now_bri_file 2>/dev/null)" +[ -n "$now_bri_file" ] || now_bri_file="$DEFAULT_NOW_BRI_FILE" _log "当前亮度节点: $now_bri_file" "INFO" -_log "最大亮度节点: $max_bri_file" "INFO" # 亮度节点不存在时不启动守护进程 (节点不可用的设备允许安装但功能保持关闭) if [ ! -f "$now_bri_file" ]; then @@ -54,12 +41,8 @@ if [ ! -f "$now_bri_file" ]; then exit 0 fi -_log "正在启动守护进程" "INFO" -chmod 755 "$MODDIR/script/up.sh" -chmod 755 "$MODDIR/script/daemon.sh" -chmod 755 "$MODDIR/bin/lumipro" - -sh "$MODDIR/script/daemon.sh" & +chmod 755 "$BIN" +"$BIN" daemon >>"$log_file" 2>&1 & _log "守护进程已启动 (PID: $!)" "SUCCESS" exit 0 diff --git a/webui/src/composables/useConfig.js b/webui/src/composables/useConfig.js index 7d2abed..0757f79 100644 --- a/webui/src/composables/useConfig.js +++ b/webui/src/composables/useConfig.js @@ -6,7 +6,6 @@ import { updateConfig, BACKUP_CONFIG_FILE, PID_FILE, - FLAG_FILE, DEFAULT_NOW_BRI_FILE, DEFAULT_SYS_MAX_BRI_FILE, } from '../utils.js' @@ -147,7 +146,6 @@ export function useConfig() { compatibility_mode: compatibilityMode.value ? 1 : 0, sleep_time: getSleepTimeStr(), }) - await runCmd(`rm -f "${FLAG_FILE}"`) const pidRes = await runCmd(`cat "${PID_FILE}"`) toast( pidRes.errno === 0 && pidRes.stdout.trim() diff --git a/webui/src/utils.js b/webui/src/utils.js index 216da74..e7db1fd 100644 --- a/webui/src/utils.js +++ b/webui/src/utils.js @@ -5,7 +5,6 @@ export const CONFIG_DIR = `${MODULE_DIR}/config` export const CONFIG_FILE = `${MODULE_DIR}/config/config.json` export const BACKUP_CONFIG_FILE = `${MODULE_DIR}/config/.backup/config.json` export const PID_FILE = `${MODULE_DIR}/pid/inotifyd.pid` -export const FLAG_FILE = `${MODULE_DIR}/pid/up.flag` export const STOP_FLAG_FILE = `${MODULE_DIR}/pid/stop.flag` export const OPLOCK_FILE = `${MODULE_DIR}/pid/oplock` export const LOG_FILE = `${MODULE_DIR}/service.log` diff --git a/webui/src/views/ConfigView.vue b/webui/src/views/ConfigView.vue index d8412b3..8984aed 100644 --- a/webui/src/views/ConfigView.vue +++ b/webui/src/views/ConfigView.vue @@ -281,7 +281,7 @@ function handleSaveWebUI() {
- lumipro 监听事件 + 监听事件 默认 c,改后需重启模块