Ubuntu

當我的筆記型電腦達到某個低電池門檻值時,如何讓它進入睡眠狀態?

  • January 10, 2022

我使用的是 Ubuntu,但我將 i3 作為我的視窗管理器而不是桌面環境。

當我的電池電量達到 0% 時,電腦將突然關閉,沒有任何警告或任何東西。

有沒有我可以設置的簡單腳本或配置,讓它在電池電量為 4% 時進入睡眠狀態?

這是一個小腳本,用於檢查電池電量並呼叫自定義命令,pm-hibernate以防電池電量低於某個門檻值。

#!/bin/sh

###########################################################################
#
# 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
#
if [ -r ~/.dbus/Xdbus ]; then
 source ~/.dbus/Xdbus
fi

low_threshold=10
critical_threshold=4
timeout=59
shutdown_cmd='/usr/sbin/pm-hibernate'

level=$(cat /sys/devices/platform/smapi/BAT0/remaining_percent)
state=$(cat /sys/devices/platform/smapi/BAT0/state)

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
   $shutdown_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 shut down in 1 minute.'

 DISPLAY=:0 zenity --question --ok-label 'OK' --cancel-label 'Cancel' \
   --text "Battery level is low: $level%.\n\n The system is going to shut down in 1 minute." &
 zenity_pid=$!

 do_shutdown &
 shutdown_pid=$!

 trap 'kill $shutdown_pid' 1

 if ! wait $zenity_pid; then
   kill $shutdown_pid 2>/dev/null
 fi

fi

exit 0

這是一個非常簡單的腳本,但我認為您明白了這個想法,並且可以輕鬆地根據您的需要調整它。您的系統上電池電量的路徑可能不同。更便攜一點可能是使用類似acpi | cut -f2 -d,的東西來獲取電池電量。該腳本可以由 cron 安排為每分鐘執行一次。編輯您的 crontabcrontab -e並添加腳本:

*/1 * * * * /home/me/usr/bin/low-battery-shutdown

另一種解決方案是安裝像 Gnome 或 Xfce 這樣的桌面環境(並將視窗管理器更改為 i3)。兩個提到的 destop 環境都具有電源管理守護程序,負責關閉電腦電源。但我假設您故意不使用它們並且正在尋求更簡約的解決方案。

引用自:https://unix.stackexchange.com/questions/84437