banner image

Off-peak latop charging

You can tell (some) laptops to stop charging when the battery is less than 100% full.

It's as simple as writing a value to /sys/class/power_supply/BAT0/charge_control_end_threshold, although this doesn't persist between reboots.

It would be interesting to:

Here's a script which does that:

root@havnor:~# cat /usr/local/bin/battery-charge-h2g2bob
#!/bin/bash

RUN_EVERY_SECONDS="$(( 15 * 60 ))"

# Avoid charging the battery to 100%, to prolong battery life
VALUE_ON_EXIT="90"

# Avoid charging the battery during times of peak demand
# hour:         00       03       06       09       12       15       18       21    23
VALUE_AT_TIME=( 90 90 90 90 90 90 90 90 70 70 80 90 90 90 90 90 80 50 30 50 70 80 90 90 )

set_value() {
    value="$1"
    echo "Setting battery max charge to $value"
    echo "$value" > /sys/class/power_supply/BAT0/charge_control_end_threshold;
}

on_exit() {
    set_value "$VALUE_ON_EXIT";
    exit 0;
}

trap on_exit SIGTERM

while true; do
    hour="$(date +"%H")";
    # hack to change "09" -> "9", eg: by doing 709-700 = 9
    index=$(("7$hour" - 700))
    set_value "${VALUE_AT_TIME[index]}";
    sleep "$RUN_EVERY_SECONDS";
done

Here's the systemd config:

root@havnor:~# cat /etc/systemd/system/battery-charge-h2g2bob.service
[Unit]
Description=Control battery charge

[Service]
Type=simple
ExecStart=/usr/local/bin/battery-charge-h2g2bob

[Install]
WantedBy=multi-user.target

Ideally this would run from the battery only during peak times and not take any AC at all. But actually it only turns off charging the battery and continues to run the laptop from AC

ie: if the battery is charged, it stays at the same percentage instead of discharging until it reaches the charge_control_end_threshold.

Why would I do this?

Image credit: Tabler