Files
ags/widget/menus/BatteryMenu/helpers.ts
T
2025-03-20 11:32:46 +07:00

72 lines
2.1 KiB
TypeScript

import { GLib } from "astal";
const cycles_count = (): string => {
try {
const [success, cycles] = GLib.file_get_contents(
"/sys/class/power_supply/BAT0/cycle_count",
);
if (!success || !cycles) {
throw new Error(
"Failed to read /sys/class/ or the file content is null.",
);
}
const cyclesinfo = new TextDecoder("utf-8").decode(cycles);
return cyclesinfo.replace(/\n$/, "");
} catch (error) {
console.error("Error get battery cycles_count");
return "";
}
};
const health = (): string => {
try {
const [success, charge_full] = GLib.file_get_contents(
"/sys/class/power_supply/BAT0/charge_full",
);
if (!success || !charge_full) {
throw new Error(
"Failed to read /sys/class/ or the file content is null.",
);
}
const [success_chagre_full_design, charge_full_design] =
GLib.file_get_contents("/sys/class/power_supply/BAT0/charge_full_design");
if (!success_chagre_full_design || !charge_full_design) {
throw new Error(
"Failed to read /sys/class/ or the file content is null.",
);
}
const chargefullnow = parseInt(
new TextDecoder("utf-8").decode(charge_full),
);
const chargefulldesign = parseInt(
new TextDecoder("utf-8").decode(charge_full_design),
);
const percents = Math.round((chargefullnow * 100) / chargefulldesign);
return percents.toString() + " %";
} catch (error) {
console.error("error get battery health");
return "";
}
};
const voltage = (): string => {
try {
const [success, voltage] = GLib.file_get_contents(
"/sys/class/power_supply/BAT0/voltage_now",
);
if (!success || !voltage) {
throw new Error(
"Failed to read /sys/class/ or the file content is null.",
);
}
const voltage_now = parseInt(new TextDecoder("utf-8").decode(voltage));
const voltage_string = (voltage_now / 1000).toString() + " V";
return voltage_string;
} catch (error) {
console.error("error get battery voltage");
return "";
}
};
export { cycles_count, health, voltage };