]> git.corax.cc Git - toolbox/commitdiff
include/acpi: Add modules for querying battery and PSU state
authorMatthias Kruk <m@m10k.eu>
Mon, 22 Mar 2021 00:46:46 +0000 (09:46 +0900)
committerMatthias Kruk <m@m10k.eu>
Mon, 22 Mar 2021 00:46:46 +0000 (09:46 +0900)
This commit adds the acpi/battery and acpi/ac module which can be used
to query the state of batteries and power supply units in the system
through the kernel's sysfs ACPI interface.

include/acpi/ac.sh [new file with mode: 0644]
include/acpi/battery.sh [new file with mode: 0644]

diff --git a/include/acpi/ac.sh b/include/acpi/ac.sh
new file mode 100644 (file)
index 0000000..4ada7ba
--- /dev/null
@@ -0,0 +1,19 @@
+#!/bin/bash
+
+__init() {
+       declare -gr __acpi_ac_path="/sys/class/power_supply"
+
+       return 0
+}
+
+acpi_ac_get_state() {
+       local psu
+
+       psu="$1"
+
+       if ! cat "$__acpi_ac_path/$psu/online" 2>/dev/null; then
+               return 1
+       fi
+
+       return 0
+}
diff --git a/include/acpi/battery.sh b/include/acpi/battery.sh
new file mode 100644 (file)
index 0000000..9f0386f
--- /dev/null
@@ -0,0 +1,66 @@
+#!/bin/bash
+
+__init() {
+       declare -gr __acpi_battery_path="/sys/class/power_supply"
+
+       return 0
+}
+
+acpi_battery_get_charge_full() {
+       local battery
+
+       battery="$1"
+
+       if cat "$__acpi_battery_path/$battery/charge_full" 2>/dev/null; then
+               return 0
+       fi
+
+       if cat "$__acpi_battery_path/$battery/energy_full" 2>/dev/null; then
+               return 0
+       fi
+
+       return 1
+}
+
+acpi_battery_get_charge_now() {
+       local battery
+
+       battery="$1"
+
+       if cat "$__acpi_battery_path/$battery/charge_now" 2>/dev/null; then
+               return 0
+       fi
+
+       if cat "$__acpi_battery_path/$battery/energy_now" 2>/dev/null; then
+               return 0
+       fi
+
+       return 1
+}
+
+acpi_battery_get_level() {
+       local battery
+
+        local full
+       local now
+       local lvl
+
+       battery="$1"
+
+       if ! full=$(acpi_battery_get_charge_full "$battery"); then
+               return 1
+       fi
+
+       if ! now=$(acpi_battery_get_charge_now "$battery"); then
+               return 1
+       fi
+
+       if (( full == 0 )); then
+               return 1
+       fi
+
+       lvl=$((now * 100 / full))
+       echo "$lvl"
+
+       return 0
+}