Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions Readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,10 @@ Tauri relies on the VC runtime library and WebView runtime. The latest version o

# History

## 0.1.4

English Translation.

## 0.1.3

Add a historical record function for laptop battery usage to track changes in battery health, charge/discharge status, charge/discharge power, and battery wear; while also updating the monitoring page.
Expand Down
38 changes: 19 additions & 19 deletions crates/battery/src/battery_status.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,11 +51,11 @@ impl std::fmt::Display for State {
}
#[derive(Clone, Serialize, Deserialize, Debug, PartialEq)]
struct Identifier {
//供应商
// vendor
pub vendor: Option<String>,
//模式
// model
pub model: Option<String>,
//序列号
// serial number
pub serial_number: Option<String>,
}
impl Default for Identifier {
Expand All @@ -69,37 +69,37 @@ impl Default for Identifier {
}
#[derive(Clone, Serialize, Deserialize, Debug, PartialEq)]
pub struct Status {
// 基于上次更新,电池信息是否已经更改
// Whether battery info changed since last update
pub state_changed: bool,
//额外的标识信息
// additional identifier info
identifier: Identifier,
//序号
// index
index: u16,
//时间戳
// timestamp
pub timestamp: i64,
//状态
// state
pub state: State,
//温度
// temperature
pub temperature: Option<f32>,
//循环次数
// cycle count
pub cycle_count: Option<u32>,
//电量百分比
// percentage
pub percentage: f32,
//充放电瓦数
// energy rate (charge/discharge watts)
pub energy_rate: f32,
//电池电压
// voltage
pub voltage: f32,
//电池健康状态
// state of health
pub state_of_health: f32,
//设计容量
// design capacity
pub design_capacity: f32,
//满充容量
// full charge capacity
pub full_capacity: f32,
//当前容量
// current capacity
pub capacity: f32,
//预估放电时长
// estimated seconds to empty
pub time_to_empty_secs: u64,
//预估充满电时长
// estimated seconds to full
pub time_to_full_secs: u64,
}
impl<'a> Default for Status {
Expand Down
6 changes: 3 additions & 3 deletions crates/persis/.vscode/launch.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
// 使用 IntelliSense 了解相关属性。
// 悬停以查看现有属性的描述。
// 欲了解更多信息,请访问: https://go.microsoft.com/fwlink/?linkid=830387
// Use IntelliSense to learn about related properties.
// Hover to view descriptions of existing properties.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
Expand Down
2 changes: 1 addition & 1 deletion crates/persis/migration/src/m20250311_150000_init.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ impl MigrationTrait for Migration {
.if_not_exists()
.col(big_integer(BatteryStateHistory::Timestamp).primary_key())
.col(string(BatteryStateHistory::State))
.col(ColumnDef::new(BatteryStateHistory::Prev).string().null())//这么写才能定义null
.col(ColumnDef::new(BatteryStateHistory::Prev).string().null())// Use .null() to define a nullable column
.col(ColumnDef::new(BatteryStateHistory::EndAt).big_integer().null())
.col(float(BatteryStateHistory::Capacity))
.col(float(BatteryStateHistory::FullCapacity))
Expand Down
4 changes: 2 additions & 2 deletions crates/persis/src/down_sample.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ impl Default for DownSampleParams {
fn default() -> Self {
let end_time = Utc::now().timestamp();
Self {
time_formater: "%Y-%m-%dT%H:%M:%SZ".to_string(), //ISO 8601格式
time_formater: "%Y-%m-%dT%H:%M:%SZ".to_string(), // ISO 8601 format
table_name: "memory_battery_status".to_string(),
time_field: "timestamp".to_string(),
order_field: "id".to_string(),
Expand Down Expand Up @@ -54,7 +54,7 @@ UniqueBatteryStatus AS (
SELECT
{time_field},
state,
ROW_NUMBER() OVER (PARTITION BY {time_field} ORDER BY {order_field} DESC) AS rn --排序字段用于在分组内的数据排序
ROW_NUMBER() OVER (PARTITION BY {time_field} ORDER BY {order_field} DESC) AS rn -- Ordering field used to sort data within groups
FROM
{table_name}
WHERE {time_field}>{start_time} and {time_field}<={end_time}
Expand Down
2 changes: 1 addition & 1 deletion crates/persis/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ mod tests {
battery.last();
let system = system::Status::build().unwrap();
let res = store.insert(&battery, &system, |_| async {}).await;
//在系统进入休眠或睡眠瞬间,insert会Err,需要处理
// During system suspend/sleep, insert may Err; handle this case
match res {
Ok((_vec,inner)) => {
inner.map(|x| {
Expand Down
2 changes: 1 addition & 1 deletion crates/persis/src/store.rs
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ impl BatteryStore {
.to_string()
.contains("no such table: memory_battery_status")
{
//时间长了会出现这个错误,不理解为什么,故丢弃数据,重置这个数据库连接
// This error can occur after a long uptime; unclear why. Discard the data and reset the in-memory DB connection
self.mem_db = Database::connect(String::from("sqlite::memory:")).await?;
Migrator::up(&self.mem_db, None).await?;
model = status.insert(&self.mem_db).await;
Expand Down
22 changes: 11 additions & 11 deletions crates/store/src/battery.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,25 +52,25 @@ impl<'de> Deserialize<'de> for SerializableState {
#[derive(Clone, Serialize, Deserialize, Debug)]
pub struct BatteryInfo {
pub state_changed: bool,
//时间戳
// timestamp
pub timestamp: i64,
//状态
// state
pub state: SerializableState,
//电量百分比
// percentage
pub percentage: f32,
//充放电瓦数
// energy rate (W)
pub energy_rate: f32,
//电池电压
// voltage
pub voltage: f32,
//电池健康状态
// state of health
pub state_of_health: f32,
//设计容量
// design capacity
pub design_capacity: f32,
//满充容量
// full capacity
pub full_capacity: f32,
//当前容量
// current capacity
pub capacity: f32,
//cpu使用率
// CPU usage
pub cpu_load: f32,

pub serial_number: String,
Expand Down Expand Up @@ -182,7 +182,7 @@ impl Battery {
.to_string();
let mut record = BatteryInfo::default();

//查询电池数量
// query number of batteries
let batteries = bms.batteries().unwrap();
for battery in batteries {
let battery = battery.unwrap();
Expand Down
10 changes: 5 additions & 5 deletions crates/store/src/processor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -129,11 +129,11 @@ impl DataProcessor {
.clone()
.lazy()
.with_columns(vec![
// 创建一列标识当前行的状态变化
col("state").shift(lit(1)).alias("prev_state"), // 获取上一行的状态
])
.filter(
// 在每个时间窗口内,检查状态是否变化
// Create a column to identify state changes in the current row
col("state").shift(lit(1)).alias("prev_state"), // get the previous row's state
]),
.filter(
// Within each time window, check if state has changed
col("state")
.neq(col("prev_state"))
.or(col("prev_state").is_null()),
Expand Down
14 changes: 7 additions & 7 deletions crates/system/src/system_status.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,19 +23,19 @@ impl Default for Identifier {

#[derive(Clone, Serialize, Deserialize, Debug, PartialEq)]
pub struct Status {
//额外的标识信息
// additional identifier info
identifier: Identifier,
//时间戳
// timestamp
pub timestamp: i64,
//是否支持cpu功耗限制
// whether CPU power limiting is supported
pub support_power_set: bool,
//cpu占用
// CPU load
pub cpuload: f32,
//空闲内存
// free memory
pub memfree: u32,
//屏幕亮度
// screen brightness
//pub screen_brightness: f32,
//屏幕标识
// screen instance identifier
//pub screen_instance: String,
}

Expand Down
2 changes: 1 addition & 1 deletion src-tauri/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion src-tauri/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "BatteryMaster"
version = "0.1.3"
version = "0.1.4"
description = "BatteryMaster"
authors = ["topabomb"]
edition = "2021"
Expand Down
Binary file added src-tauri/WinRing0x64.dll
Binary file not shown.
Binary file added src-tauri/WinRing0x64.sys
Binary file not shown.
7 changes: 7 additions & 0 deletions src-tauri/config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"auto_start": false,
"start_minimize": false,
"ui_update": 2,
"service_update": 1,
"record_battery_history": true
}
Empty file added src-tauri/history.db
Empty file.
Binary file added src-tauri/inpoutx64.dll
Binary file not shown.
Binary file added src-tauri/libryzenadj.dll
Binary file not shown.
47 changes: 34 additions & 13 deletions src-tauri/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,14 @@ fn check_if_dev() -> bool {
false
}

// 定义配置结构体
// Define configuration struct
#[derive(Serialize, Deserialize, Clone, Copy)]
pub struct Config {
pub auto_start: bool, // 系统启动时自动启动
pub start_minimize: bool, //启动时最小化
pub ui_update: u8, // UI标更新时间
pub service_update: u8, // 监控服务更新时间
pub record_battery_history: bool, // 是否记录电池活动历史
pub auto_start: bool, // Start with the system
pub start_minimize: bool, // Start minimized
pub ui_update: u8, // UI update interval
pub service_update: u8, // Monitoring service update interval
pub record_battery_history: bool, // Whether to record battery activity history
}

impl Default for Config {
Expand All @@ -38,7 +38,7 @@ impl Default for Config {
}
}

// 获取当前执行目录
// Get current executable directory
pub fn get_exe_directory() -> PathBuf {
env::current_exe()
.expect("Failed to get current executable path")
Expand All @@ -47,22 +47,22 @@ pub fn get_exe_directory() -> PathBuf {
.to_path_buf()
}

// 获取配置文件路径(基于执行文件目录)
// Get config file path (based on executable directory)
pub fn get_config_file_path() -> PathBuf {
get_exe_directory().join("config.json")
}

// 读取配置文件并返回配置
// Read configuration file and return Config
pub fn load_config() -> Result<Config, Box<dyn std::error::Error>> {
let config_path = get_config_file_path();

if Path::new(&config_path).exists() {
// 文件存在,读取并解析配置
// File exists: read and parse configuration
let mut file = File::open(config_path)?;
let mut contents = String::new();
file.read_to_string(&mut contents)?;

// 解析 JSON 配置
// Parse JSON configuration
let config: Config = serde_json::from_str(&contents)?;
Ok(config)
} else {
Expand All @@ -72,18 +72,39 @@ pub fn load_config() -> Result<Config, Box<dyn std::error::Error>> {
}
}

// 保存配置到文件
// Save configuration to file
pub fn save_config(config: &Config) -> Result<(), Box<dyn std::error::Error>> {
let config_path = get_config_file_path();
let mut file = File::create(config_path)?;

// 将配置序列化为 JSON
// Serialize configuration to JSON
let config_json = serde_json::to_string_pretty(config)?;
file.write_all(config_json.as_bytes())?;

Ok(())
}

// Ensure runtime files exist: history DB and logs file.
pub fn ensure_runtime_files() -> Result<(), Box<dyn std::error::Error>> {
let exe_dir = get_exe_directory();
// Ensure directory exists (should normally exist)
if !exe_dir.exists() {
std::fs::create_dir_all(&exe_dir)?;
}

let history_path = exe_dir.join("history.db");
if !history_path.exists() {
let _ = File::create(&history_path)?;
}

let logs_path = exe_dir.join("logs.log");
if !logs_path.exists() {
let _ = File::create(&logs_path)?;
}

Ok(())
}

pub fn set_autostart(app_handle: &tauri::AppHandle, val: bool) {
let autostart_manager = app_handle.autolaunch();
if !check_if_dev() {
Expand Down
Loading