为Linux笔电配置低电量关机

为Linux笔电配置低电量关机

低电量关机

文中使用的脚本为电池量低于40%进行关机,处于充电状态取消关机

部署脚本如下

1
2
3
4
5
nano /opt/batterydown.sh
nano /usr/lib/systemd/system/batterydown.service
systemctl daemon-reload
systemctl enable --now batterydown.service
systemctl status batterydown.service

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
#!/bin/bash

PATH=/sbin:/bin:/usr/sbin:/usr/bin
_shut=false
sleep 20

while :
do
    # 获取电池电量
    capacity=$(cat /sys/class/power_supply/BAT0/capacity)

    # 获取电池状态
    status=$(cat /sys/class/power_supply/BAT0/status)
    echo "Battery Status: $status"
    echo "Battery Capacity: $capacity%"

    if [[ $capacity -lt 40 ]]; then
        if [[ $status != "Full" && $status != "Charging" ]]; then
            echo "Battery capacity is below 40%. Going down!"
            if [ "$_shut" == "false" ]; then
                echo "Going Down!!!!"
                shutdown -h +10
            fi
            _shut=true
        else
            if $_shut; then
                echo "Battery is Charging. Canceling shutdown!"
                shutdown -c
                _shut=false
            fi
        fi
    else
        if $_shut; then
            echo "Battery capacity is above 40%. Canceling shutdown!"
            shutdown -c
            _shut=false
        fi
    fi

    sleep 20
done

service文件:

1
2
3
4
5
6
7
8
9
[Unit]
Description=batterydown Service

[Service]
User=root
ExecStart=/bin/bash /opt/batterydown.sh

[Install]
WantedBy=default.target

电池保护

先装一下相关的软件包

1
apt install tlp
1
2
3
4
nano /etc/tlp.conf
#找到下面两行进行取消注释和修改
START_CHARGE_THRESH_BAT0=50
STOP_CHARGE_THRESH_BAT0=80
1
systemctl restart tlp

状态查看

1
tlb-stat -b
Licensed under CC BY-NC-SA 4.0
使用 Hugo 构建
主题 StackJimmy 设计