├── .github └── workflows │ └── rust.yml ├── .gitignore ├── Cargo.lock ├── Cargo.toml ├── LICENSE ├── README.md ├── Real_Battery ├── META-INF │ └── com │ │ └── google │ │ └── android │ │ ├── update-binary │ │ └── updater-script ├── customize.sh ├── module.prop └── post-fs-data.sh ├── build.sh ├── pack_module.sh └── src ├── core.rs ├── lib.rs ├── main.rs └── mount.rs /.github/workflows/rust.yml: -------------------------------------------------------------------------------- 1 | name: Rust 2 | 3 | on: 4 | push: 5 | branches: [ "main" ] 6 | pull_request: 7 | branches: [ "main" ] 8 | 9 | env: 10 | CARGO_TERM_COLOR: always 11 | 12 | jobs: 13 | build: 14 | 15 | runs-on: ubuntu-latest 16 | 17 | steps: 18 | - uses: actions/checkout@v3 19 | - name: Build 20 | run: cargo build --verbose 21 | - name: Run tests 22 | run: cargo test --verbose 23 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | real_batt 3 | .vscode 4 | Real_Battery.zip -------------------------------------------------------------------------------- /Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | version = 3 4 | 5 | [[package]] 6 | name = "libc" 7 | version = "0.2.144" 8 | source = "registry+https://github.com/rust-lang/crates.io-index" 9 | checksum = "2b00cc1c228a6782d0f076e7b232802e0c5689d41bb5df366f2a6b6621cfdfe1" 10 | 11 | [[package]] 12 | name = "real_battery" 13 | version = "0.1.0" 14 | dependencies = [ 15 | "libc", 16 | ] 17 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "real_battery" 3 | version = "0.1.0" 4 | edition = "2021" 5 | 6 | [package.metadata] 7 | magisk_module_dir = "./Real_Battery/" 8 | 9 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 10 | 11 | [profile.release] 12 | lto = "fat" 13 | codegen-units = 1 14 | opt-level = 'z' 15 | strip = true 16 | 17 | [dependencies] 18 | libc = "0.2.144" 19 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## 编译 2 | ### 安装rust 3 | ``` 4 | # wsl/linux 5 | curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh 6 | # termux(not in proot) 7 | apt install rust 8 | # or 9 | pkg add rust 10 | ``` 11 | ### 下载源代码 12 | * #### 使用git 13 | ``` 14 | git clone https://github.com/shadow3aaa/real_battery.git --depth=1 15 | ``` 16 | * #### 或者,从该项目[release](https://github.com/shadow3aaa/real_battery/releases)下载最新source_code.zip 17 | ### 编译二进制程序 18 | ``` 19 | # 进入项目文件夹 20 | cd real_battery 21 | # 编译 22 | ./build.sh 23 | ``` 24 | #### 打包 25 | ``` 26 | ./pack_module.sh 27 | ``` 28 | * 然后,项目根目录会出现Real_Battery.zip 29 | * 用magisk刷入即可安装 30 | ___ 31 | ## 安装 32 | * 下载最新[release](https://github.com/shadow3aaa/real_battery/releases) 33 | * 在magisk内安装 34 | -------------------------------------------------------------------------------- /Real_Battery/META-INF/com/google/android/update-binary: -------------------------------------------------------------------------------- 1 | #!/sbin/sh 2 | 3 | #################################################### 4 | # 5 | # Magisk 模块安装脚本模板 6 | # by topjohnwu 7 | # 20.3+版本适配汉化: Pinkdoge 8 | # 9 | ##################################################### 10 | 11 | umask 022 12 | 13 | # 全局变量 14 | TMPDIR=/dev/tmp 15 | PERSISTDIR=/sbin/.magisk/mirror/persist 16 | 17 | rm -rf $TMPDIR 2>/dev/null 18 | mkdir -p $TMPDIR 19 | 20 | # 在加载 util_functions 前 echo 21 | ui_print() { echo "$1"; } 22 | 23 | require_new_magisk() { 24 | ui_print "*******************************" 25 | ui_print " 请安装 Magisk v20.3+! " 26 | ui_print "*******************************" 27 | exit 1 28 | } 29 | 30 | is_legacy_script() { 31 | unzip -l "$ZIPFILE" install.sh | grep -q install.sh 32 | return $? 33 | } 34 | 35 | print_modname() { 36 | local len 37 | len=`echo -n $MODNAME | wc -c` 38 | len=$((len + 2)) 39 | local pounds=`printf "%${len}s" | tr ' ' '*'` 40 | ui_print "$pounds" 41 | ui_print " $MODNAME " 42 | ui_print "$pounds" 43 | } 44 | 45 | ############## 46 | # 环境设置 47 | ############## 48 | 49 | OUTFD=$2 50 | ZIPFILE=$3 51 | 52 | mount /data 2>/dev/null 53 | 54 | # 加载公用函数 55 | [ -f /data/adb/magisk/util_functions.sh ] || require_new_magisk 56 | . /data/adb/magisk/util_functions.sh 57 | [ $MAGISK_VER_CODE -gt 18100 ] || require_new_magisk 58 | 59 | # 准备卡刷 zip 包 60 | setup_flashable 61 | 62 | # 挂载分区 63 | mount_partitions 64 | 65 | # 检测版本和架构 66 | api_level_arch_detect 67 | 68 | # 安装 busybox 和二进制文件 69 | $BOOTMODE && boot_actions || recovery_actions 70 | 71 | ############## 72 | # 准备 73 | ############## 74 | 75 | # 提取公共文件 76 | unzip -o "$ZIPFILE" module.prop -d $TMPDIR >&2 77 | [ ! -f $TMPDIR/module.prop ] && abort "! 从 zip 中提取文件失败!" 78 | 79 | $BOOTMODE && MODDIRNAME=modules_update || MODDIRNAME=modules 80 | MODULEROOT=$NVBASE/$MODDIRNAME 81 | MODID=`grep_prop id $TMPDIR/module.prop` 82 | MODPATH=$MODULEROOT/$MODID 83 | MODNAME=`grep_prop name $TMPDIR/module.prop` 84 | 85 | # 创建模块路径 86 | rm -rf $MODPATH 2>/dev/null 87 | mkdir -p $MODPATH 88 | 89 | ########## 90 | # 安装 91 | ########## 92 | 93 | if is_legacy_script; then 94 | unzip -oj "$ZIPFILE" module.prop install.sh uninstall.sh 'common/*' -d $TMPDIR >&2 95 | 96 | # 加载安装脚本 97 | . $TMPDIR/install.sh 98 | 99 | # 打印模块名称 100 | print_modname 101 | on_install 102 | 103 | # 加载自定义卸载脚本 104 | [ -f $TMPDIR/uninstall.sh ] && cp -af $TMPDIR/uninstall.sh $MODPATH/uninstall.sh 105 | 106 | # 取消挂载 107 | $SKIPMOUNT && touch $MODPATH/skip_mount 108 | 109 | # prop 文件 110 | $PROPFILE && cp -af $TMPDIR/system.prop $MODPATH/system.prop 111 | 112 | # 模块信息 113 | cp -af $TMPDIR/module.prop $MODPATH/module.prop 114 | 115 | # post-fs-data 模式脚本 116 | $POSTFSDATA && cp -af $TMPDIR/post-fs-data.sh $MODPATH/post-fs-data.sh 117 | 118 | # service 模式脚本 119 | $LATESTARTSERVICE && cp -af $TMPDIR/service.sh $MODPATH/service.sh 120 | 121 | ui_print "- 正在设置权限" 122 | set_permissions 123 | else 124 | print_modname 125 | 126 | unzip -o "$ZIPFILE" customize.sh -d $MODPATH >&2 127 | 128 | if ! grep -q '^SKIPUNZIP=1$' $MODPATH/customize.sh 2>/dev/null; then 129 | ui_print "- 正在提取模块文件" 130 | unzip -o "$ZIPFILE" -x 'META-INF/*' -d $MODPATH >&2 131 | 132 | # 默认权限 133 | set_perm_recursive $MODPATH 0 0 0755 0644 134 | fi 135 | 136 | # 加载 customization 脚本 137 | [ -f $MODPATH/customize.sh ] && . $MODPATH/customize.sh 138 | fi 139 | 140 | # 处理 replace 文件夹 141 | for TARGET in $REPLACE; do 142 | ui_print "- 正在删除目标文件: $TARGET" 143 | mktouch $MODPATH$TARGET/.replace 144 | done 145 | 146 | if $BOOTMODE; then 147 | # Update info for Magisk Manager 148 | mktouch $NVBASE/modules/$MODID/update 149 | cp -af $MODPATH/module.prop $NVBASE/modules/$MODID/module.prop 150 | fi 151 | 152 | # 安装自定义 sepolicy 补丁 153 | if [ -f $MODPATH/sepolicy.rule -a -e $PERSISTDIR ]; then 154 | ui_print "- 安装自定义 sepolicy 补丁" 155 | PERSISTMOD=$PERSISTDIR/magisk/$MODID 156 | mkdir -p $PERSISTMOD 157 | cp -af $MODPATH/sepolicy.rule $PERSISTMOD/sepolicy.rule 158 | fi 159 | 160 | # 删除 placeholder 文件 161 | rm -rf \ 162 | $MODPATH/system/placeholder $MODPATH/customize.sh \ 163 | $MODPATH/README.md $MODPATH/.git* 2>/dev/null 164 | 165 | ############## 166 | # 结束 167 | ############## 168 | 169 | cd / 170 | $BOOTMODE || recovery_cleanup 171 | rm -rf $TMPDIR 172 | 173 | ui_print "- 完成" 174 | exit 0 -------------------------------------------------------------------------------- /Real_Battery/META-INF/com/google/android/updater-script: -------------------------------------------------------------------------------- 1 | #MAGISK 2 | -------------------------------------------------------------------------------- /Real_Battery/customize.sh: -------------------------------------------------------------------------------- 1 | ui_print "让部分支持的设备显示更符合实际状态的电量百分比" 2 | pkill -9 real_batt 3 | chmod a+x "$MODPATH/real_batt" 4 | nohup "$MODPATH/real_batt" >/dev/null 2>&1 & 5 | if [[ ! -d /sys/class/power_supply/bms ]]; then 6 | ui_print "由于采用方法不同的原因" 7 | ui_print "你的机型需要安装完重启才可能生效" 8 | else 9 | ui_print "你的机型似乎能马上生效" 10 | if [ "$(pidof real_batt)" = "" ]; then 11 | ui_print "运行失败" 12 | abort 13 | fi 14 | fi 15 | -------------------------------------------------------------------------------- /Real_Battery/module.prop: -------------------------------------------------------------------------------- 1 | id=real_bat_cap 2 | name=真实电量 3 | version=v0.1 4 | versionCode=1 5 | author=shadow3 6 | description=让部分支持的设备显示更符合实际状态的电量百分比 -------------------------------------------------------------------------------- /Real_Battery/post-fs-data.sh: -------------------------------------------------------------------------------- 1 | MODDIR=${0%/*} 2 | pkill -9 real_batt 3 | chmod a+x "$MODDIR/real_batt" 4 | { 5 | while [ ! -f /sys/class/power_supply/battery/capacity ]; do 6 | sleep 1 7 | done 8 | nohup $MODDIR/real_batt >/dev/null 2>&1 9 | } & -------------------------------------------------------------------------------- /build.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/bash 2 | TAGS="--release -Z unstable-options --out-dir=${0%/*}/target/build" 3 | function pred() { 4 | local error_message=$1 5 | echo -e "\033[31m$error_message\033[0m" >&2 6 | } 7 | 8 | function pgreen() { 9 | local error_message=$1 10 | echo -e "\033[32m$error_message\033[0m" >&2 11 | } 12 | 13 | # try taregt aarch64-linux-android 14 | rustup target add aarch64-linux-android 2>&1 >/dev/null 15 | cargo build $TAGS --target=aarch64-linux-android 16 | if [[ ! $? -eq 0 ]]; then 17 | pred "编译到target: aarch64-linux-android失败!" 18 | pred "检查是否缺少相关库" 19 | pgreen "尝试编译到target: aarch64-unknown-linux-musl,在安卓上运行效率较aarch64-linux-android低,但是内存占用小" 20 | # try target aarch64-unknown-linux-musl 21 | rustup target add aarch64-unknown-linux-musl 2>&1 >/dev/null 22 | cargo build $TAGS --target=aarch64-unknown-linux-musl 23 | if [[ ! $? -eq 0 ]]; then 24 | pred "编译到target: aarch64-unknown-linux-musl 失败!" 25 | pgreen "尝试编译到target: aarch64-unknown-linux-gnu,该target二进制文件大小较大" 26 | # try target aarch64-unknown-linux-gnu 27 | export RUSTFLAGS="-C target-feature=+crt-static" 28 | rustup target add aarch64-unknown-linux-gnu 2>&1 >/dev/null 29 | cargo build $TAGS --target=aarch64-unknown-linux-gnu 30 | fi 31 | fi 32 | [[ ! $? -eq 0 ]] && 33 | \pred "编译失败" && 34 | \exit -1 35 | 36 | # 优化体积 37 | sstrip ${0%/*}/target/build/real_battery 38 | 39 | pgreen "编译成功,复制到模块" 40 | cp -f ${0%/*}/target/build/real_battery ${0%/*}/Real_Battery/real_batt 41 | -------------------------------------------------------------------------------- /pack_module.sh: -------------------------------------------------------------------------------- 1 | function pred() { 2 | local error_message=$1 3 | echo -e "\033[31m$error_message\033[0m" >&2 4 | } 5 | 6 | function pgreen() { 7 | local error_message=$1 8 | echo -e "\033[32m$error_message\033[0m" >&2 9 | } 10 | 11 | if [[ ! -d ${0%/*}/Real_Battery || ! -f ${0%/*}/Real_Battery/real_batt ]]; then 12 | pred "打包失败,也许还没有编译?" 13 | exit -1 14 | fi 15 | 16 | cd ${0%/*}/Real_Battery 17 | zip -r -X9 -FS ${0%/*}/../Real_Battery.zip ./ 18 | 19 | if [ $? -eq 0 ]; then 20 | pgreen "打包magisk模块成功" 21 | else 22 | pred "打包为magisk模块失败" 23 | fi 24 | -------------------------------------------------------------------------------- /src/core.rs: -------------------------------------------------------------------------------- 1 | use crate::mount::mount_bind; 2 | use crate::{create_file, exec_cmd, is_writable, set_security_context, test_path, write_file}; 3 | use std::{error::Error, fs::read_to_string, thread::sleep, time::Duration}; 4 | 5 | pub const BMS_CAPACITY: &str = "/sys/class/power_supply/bms/capacity"; 6 | pub const BAT_CAPACITY: &str = "/sys/class/power_supply/battery/capacity"; 7 | pub const MOUNT_CAPACITY: &str = "/cache/real_battery_cap"; 8 | 9 | pub fn run(real_list: T) 10 | where 11 | T: IntoIterator)>, 12 | F: Fn(u32) -> u32, 13 | { 14 | for (path, do_with) in real_list { 15 | if !test_path(path) { 16 | continue; 17 | } 18 | loop { 19 | let real: u32 = read_to_string(path).unwrap().trim().parse().unwrap(); 20 | let real = match &do_with { 21 | Some(f) => f(real), 22 | None => real, 23 | }; 24 | set_cap(real); 25 | sleep(Duration::from_secs(5)); 26 | } 27 | } 28 | } 29 | 30 | fn set_cap(cap: u32) { 31 | match is_writable(BMS_CAPACITY) { 32 | true => set_cap_by_write(cap), 33 | false => set_cap_by_mount(cap), 34 | } 35 | } 36 | 37 | fn set_cap_by_write(cap: u32) { 38 | write_file(&cap.to_string(), BMS_CAPACITY); 39 | } 40 | 41 | fn mount_init() -> Result<(), Box> { 42 | set_enforce(false); 43 | create_file(MOUNT_CAPACITY)?; 44 | let cur_cap = read_to_string(BAT_CAPACITY).unwrap_or("50".to_string()); 45 | write_file(&cur_cap, MOUNT_CAPACITY); 46 | mount_bind(MOUNT_CAPACITY, BAT_CAPACITY)?; 47 | set_security_context(BAT_CAPACITY, "u:object_r:vendor_sysfs_battery_supply:s0"); 48 | set_enforce(true); 49 | Ok(()) 50 | } 51 | 52 | pub fn init_mount_until_success() { 53 | if !test_path(BMS_CAPACITY) && mount_init().is_err() { 54 | init_mount_until_success(); 55 | } 56 | } 57 | 58 | fn set_cap_by_mount(cap: u32) { 59 | if !test_path(MOUNT_CAPACITY) { 60 | eprintln!("mount path: {} not found!", MOUNT_CAPACITY) 61 | } 62 | write_file(&cap.to_string(), MOUNT_CAPACITY); 63 | } 64 | 65 | fn set_enforce(status: bool) { 66 | match status { 67 | true => { 68 | let _ = exec_cmd("setenforce", &["1"]); 69 | } 70 | false => { 71 | let _ = exec_cmd("setenforce", &["0"]); 72 | } 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | pub mod core; 2 | pub mod mount; 3 | 4 | pub fn set_self_sched() { 5 | let self_pid = &std::process::id().to_string(); 6 | write_file(self_pid, "/dev/cpuset/background/tasks"); 7 | } 8 | 9 | pub fn write_file(content: &str, path: &str) { 10 | use std::{ 11 | fs::{set_permissions, OpenOptions}, 12 | io::Write, 13 | os::unix::fs::PermissionsExt, 14 | }; 15 | 16 | // debug 17 | // println!("path: {}, value: {}", path, content); 18 | 19 | match set_permissions(path, PermissionsExt::from_mode(0o644)) { 20 | Ok(()) => { 21 | match OpenOptions::new() 22 | .write(true) 23 | .truncate(true) 24 | .create(true) 25 | .open(path) 26 | { 27 | Ok(mut file) => match file.write_all(content.as_bytes()) { 28 | Ok(()) => {} 29 | Err(e) => eprintln!("Write failed: {}", e), 30 | }, 31 | Err(e) => eprintln!("Open failed: {}", e), 32 | } 33 | } 34 | Err(e) => eprintln!("Set permissions failed: {}", e), 35 | } 36 | } 37 | 38 | pub fn is_writable(path: &str) -> bool { 39 | use std::fs; 40 | if let Ok(metadata) = fs::metadata(path) { 41 | return !metadata.permissions().readonly(); 42 | } 43 | false 44 | } 45 | 46 | pub fn test_path(path: &str) -> bool { 47 | std::path::Path::new(path).exists() 48 | } 49 | 50 | pub fn set_security_context(path: &str, context: &str) { 51 | let _ = exec_cmd("chcon", &[context, path]); 52 | } 53 | 54 | pub fn exec_cmd(command: &str, args: &[&str]) -> Result { 55 | use std::process::Command; 56 | let output = Command::new(command).args(args).output(); 57 | 58 | match output { 59 | Ok(o) => Ok(String::from_utf8_lossy(&o.stdout).into_owned()), 60 | Err(e) => { 61 | eprintln!("{}", e); 62 | Err(-1) 63 | } 64 | } 65 | } 66 | 67 | use std::fs::File; 68 | fn create_file(path: &str) -> std::io::Result<()> { 69 | let _file = File::create(path)?; 70 | Ok(()) 71 | } 72 | -------------------------------------------------------------------------------- /src/main.rs: -------------------------------------------------------------------------------- 1 | use real_battery::{core::*, set_self_sched, test_path}; 2 | 3 | fn main() { 4 | let list = [ 5 | ("/sys/class/qcom-battery/fg1_rsoc", None), 6 | ("/sys/class/power_supply/bms/rsoc", None), 7 | ( 8 | "/sys/class/power_supply/bms/capacity_raw", 9 | Some(|r: u32| r / 100), 10 | ), 11 | ]; 12 | 13 | if !test_support(list) { 14 | eprintln!("Unsupported device"); 15 | std::process::exit(-1); 16 | } 17 | 18 | init_mount_until_success(); 19 | set_self_sched(); 20 | run(list); 21 | std::process::exit(-1); 22 | } 23 | 24 | fn test_support(list: T) -> bool 25 | where 26 | T: IntoIterator)>, 27 | F: Fn(u32) -> u32, 28 | { 29 | list.into_iter().any(|(path, _)| test_path(path)) 30 | } 31 | -------------------------------------------------------------------------------- /src/mount.rs: -------------------------------------------------------------------------------- 1 | use libc::{mount, umount, umount2, EINVAL, MS_BIND, MS_REC}; 2 | use std::ffi::CString; 3 | use std::os::raw::c_char; 4 | 5 | pub fn mount_bind(src_path: &str, dest_path: &str) -> Result<(), String> { 6 | let src_path = CString::new(src_path).expect("CString::new failed"); 7 | let dest_path = CString::new(dest_path).expect("CString::new failed"); 8 | 9 | // 检查目录是否已经被挂载,如果是的,先卸载 10 | let _ = unsafe { umount2(dest_path.as_ptr(), libc::MNT_DETACH) }; 11 | 12 | // 挂载文件系统 13 | let result = unsafe { 14 | mount( 15 | src_path.as_ptr() as *const c_char, 16 | dest_path.as_ptr() as *const c_char, 17 | std::ptr::null(), 18 | MS_BIND | MS_REC, 19 | std::ptr::null(), 20 | ) 21 | }; 22 | 23 | if result != 0 { 24 | if result == -EINVAL { 25 | return Err(String::from("Invalid arguments provided.")); 26 | } else { 27 | return Err(String::from("Failed to mount filesystem.")); 28 | } 29 | } 30 | 31 | Ok(()) 32 | } 33 | 34 | pub fn unmount(file_system: &str) { 35 | let path = CString::new(file_system).unwrap(); 36 | let _result = unsafe { umount(path.as_ptr()) }; 37 | } 38 | --------------------------------------------------------------------------------