如何监控电池状况和弹出通知?

lan*_*oni 5 battery notification command-line monitoring

从本质上讲,我希望将此评论变成一个有效的答案。

我知道如何从如何使用终端检查电池状态中提取电池百分比

upower -i $(upower -e | grep BAT) | grep --color=never -E percentage|xargs|cut -d' ' -f2|sed s/%//
Run Code Online (Sandbox Code Playgroud)

以及如何弹出基本通知:

notify-send "battery low"
Run Code Online (Sandbox Code Playgroud)

但是我如何设置一个(bash?)脚本来永久监控输出并按照这个伪代码发送通知:

如果battery_status < 10%然后notify-send "battery low"将我的系统置于挂起状态sudo pm-suspend

Ser*_*nyy 6

第一步:让所有用户都可以访问 pm-suspend,无需密码

sudo visudo并在文件末尾添加这一行:yourusername ALL=NOPASSWD: /usr/sbin/pm-suspend

来源:如何在没有密码的情况下运行特定的 sudo 命令?

第二步:创建batwatch.desktop文件:

这是将自动启动监控脚本的文件。该文件必须存储在$HOME/.config/autostart/文件夹中。

[Desktop Entry]
Type=Application
Exec=/home/serg/bin/batwatch.sh
Hidden=false
NoDisplay=false
Name=Battery Monitor Script
Run Code Online (Sandbox Code Playgroud)

请注意,脚本在我的/home/serg/bin文件夹中。您可以使用任何您喜欢的文件夹,但出于标准的考虑, /usr/bin 或 /home/username/bin 会更受欢迎。

来源:如何在启动时运行脚本

第三步:创建实际脚本,保存在与Exec=行相同的位置

这是实际的脚本。请注意,我在那里使用 bash,但它也应该与 korn shell 一起使用。我添加了一些注释,因此请阅读这些注释以了解脚本的确切作用

#!/bin/bash

# Check if the battery is connected
if [ -e /sys/class/power_supply/BAT1 ]; then

    # this line is for debugging mostly. Could be removed
    #notify-send --icon=info "STARTED MONITORING BATERY"
    zenity --warning --text "STARTED MONITORING BATERY"

    while true;do   
            # Get the capacity
            CAPACITY=$( cat /sys/class/power_supply/BAT1/uevent | grep -i capacity | cut -d'=' -f2 )

            case $CAPACITY in
            # do stuff when we hit 11 % mark
            [0-9]|11)
                # send warning and suspend only if battery is discharging
                # i.e., no charger connected
                STATUS=$(  cat /sys/class/power_supply/BAT1/uevent | grep -i status | cut -d'=' -f2 )
                 if [ $(echo $STATUS) == "Discharging" ]; then

                    #notify-send --urgency=critical --icon=dialog-warning "LOW BATTERY! SUSPENDING IN 30 sec"
                    zenity --warning --text "LOW BATTERY! SUSPENDING IN 30 sec"
                    sleep 30
                    gnome-screensaver-command -l && sudo pm-suspend
                    break
                 fi
                ;;
            *)
            sleep 1
                continue
                ;;
            esac
    done
fi
Run Code Online (Sandbox Code Playgroud)

第四步:重启并测试脚本是否有效

为此,您可以将数字调整为 [0-9]|11)您喜欢的任何值,例如65)暂停在 65%。只有当您没有连接到电源(即不充电)时,您才会挂起。

如果您喜欢这个,请告诉我,如果它有效,请务必投票并单击我的答案左侧的灰色复选标记!

干杯!