summaryrefslogtreecommitdiff
path: root/suspend-below-battery-capacity
diff options
context:
space:
mode:
Diffstat (limited to 'suspend-below-battery-capacity')
-rwxr-xr-xsuspend-below-battery-capacity51
1 files changed, 51 insertions, 0 deletions
diff --git a/suspend-below-battery-capacity b/suspend-below-battery-capacity
new file mode 100755
index 0000000..114cf9b
--- /dev/null
+++ b/suspend-below-battery-capacity
@@ -0,0 +1,51 @@
1#!/bin/bash
2default_capacity_threshold=50
3
4if [ -e /usr/lib/bash/sleep ]
5then
6 enable -f /usr/lib/bash/sleep sleep
7else
8 echo 'Warning: not found: /usr/lib/bash/sleep (try: "sudo apt install bash-builtins")' >&2
9fi
10
11main()
12{
13 capacity_threshold=${1:-$default_capacity_threshold}
14 while true
15 do
16 check_batteries /sys/class/power_supply/BAT*
17 sleep 1
18 done
19}
20
21check_batteries()
22{
23 for dir in "$@"
24 do
25 [ -d "$dir" ] || continue
26 check_battery "$dir"
27 done
28}
29
30check_battery()
31{
32 battery_dir=$1
33
34 read status < "$battery_dir"/status || return
35 [ "$status" = Discharging ] || return 0
36
37 read capacity < "$battery_dir"/capacity || return
38 case "$capacity" in
39 '' | *[^0-9]*)
40 echo "Error: unexpected value for battery capacity: $capacity" >&2
41 return 1
42 ;;
43 esac
44
45 if [ "$capacity" -lt "$capacity_threshold" ]
46 then
47 systemctl suspend
48 fi
49}
50
51main "$@"