-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathhibernate_when_battery_is_low.sh
83 lines (66 loc) · 2.16 KB
/
hibernate_when_battery_is_low.sh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
#!/bin/sh
set -x
# http://unix.stackexchange.com/questions/84437/how-do-i-make-my-laptop-sleep-when-it-reaches-some-low-battery-threshold
###########################################################################
#
# Usage: system-low-battery
#
# Checks if the battery level is low. If “low_threshold” is exceeded
# a system notification is displayed, if “critical_threshold” is exceeded
# a popup window is displayed as well. If “OK” is pressed, the system
# shuts down after “timeout” seconds. If “Cancel” is pressed the script
# does nothing.
#
# This script is supposed to be called from a cron job.
#
###########################################################################
# This is required because the script is invoked by cron. Dbus information
# is stored in a file by the following script when a user logs in. Connect
# it to your autostart mechanism of choice.
#
# #!/bin/sh
# touch $HOME/.dbus/Xdbus
# chmod 600 $HOME/.dbus/Xdbus
# env | grep DBUS_SESSION_BUS_ADDRESS > $HOME/.dbus/Xdbus
# echo 'export DBUS_SESSION_BUS_ADDRESS' >> $HOME/.dbus/Xdbus
# exit 0
#
# User should be able to run pm-suspend command without password. Add the
# following to sudoer file using visudo command.
# dilawar ALL=(ALL) NOPASSWD: ALL
# let crontab know whom to talk to
export DISPLAY=:0
if [ -r ~/.dbus/Xdbus ]; then
. ~/.dbus/Xdbus
fi
low_threshold=20
critical_threshold=15
timeout=15
suspend_cmd='/usr/sbin/pm-suspend'
level=$(cat /sys/class/power_supply/BAT0/capacity)
state=$(cat /sys/class/power_supply/BAT0/status)
if [ x"$state" != x'Discharging' ]; then
exit 0
fi
do_shutdown() {
sleep $timeout && kill $zenity_pid 2>/dev/null
if [ x"$state" != x'Discharging' ]; then
exit 0
else
sudo $suspend_cmd
fi
}
if [ "$level" -gt $critical_threshold ] && [ "$level" -lt $low_threshold ]; then
notify-send "Battery level is low: $level%"
fi
if [ "$level" -lt $critical_threshold ]; then
notify-send -u critical -t 20000 "Battery level is low: $level%" \
'The system is going to hibernate in 15 seconds.'
do_shutdown &
shutdown_pid=$!
trap 'kill $shutdown_pid' 1
if ! wait $zenity_pid; then
kill $shutdown_pid 2>/dev/null
fi
fi
exit 0