Code. Battery notifier.
Kir Axanov

Kir Axanov @axkira

About: 👋 Hi, I’m @axkira I have some background in frontend and systems architecture & analysis (class diagrams, API specs etc). Also a little bit of Django and Docker stuff ;)

Location:
KG, UTC+6
Joined:
May 6, 2022

Code. Battery notifier.

Publish Date: Dec 12 '24
0 0

Out of frustration from some-battery-monitor-util sometimes missing the moment to notify me about low charge, this simple script was put together.

It checks the current status and level of the BAT0 device and does one of the following:

  • notify about low battery level (15%)
  • notify about critical battery level (5%)
  • notify about near-zero battery level (3%), wait a couple of seconds and hibernate if battery status haven't changed to Charging

Requisites:

  • some notification daemon (I like dunst)
  • systemd for hibernation
  • something, that calls that script periodically (I call it with polybar every 60 seconds)

The script itself (battery-notifier.sh):

#!/usr/bin/env bash

LOW_LEVEL=15
CRITICAL_LEVEL=5
HIBERNATE_LEVEL=3

LEVEL=$(cat /sys/class/power_supply/BAT0/capacity)
STATUS=$(cat /sys/class/power_supply/BAT0/status)

hibernate() {
  notify-send -a "Battery" "Hibernating!" -u critical

  # Give some time to plug the power in
  sleep 5

  # Hibernate if still discharging
  STATUS=$(cat /sys/class/power_supply/BAT0/status)
  if [[ "$STATUS" = "Discharging" ]]; then
    systemctl hibernate
  else
    notify-send -a "Battery" "Power was plugged in. Hibernation is cancelled!"
  fi
}

notify_critical() {
  notify-send -a "Battery" "Battery is critically low!" -u critical
}

notify_low() {
  notify-send -a "Battery" "Battery is low!"
}


if [[ "$STATUS" = "Discharging" ]]; then
  if [[ "$LEVEL" -le "$HIBERNATE_LEVEL" ]]; then
    hibernate
  elif [[ "$LEVEL" -le "$CRITICAL_LEVEL" ]]; then
    notify_critical
  elif [[ "$LEVEL" -le "$LOW_LEVEL" ]]; then
    notify_low
  fi
fi
Enter fullscreen mode Exit fullscreen mode

The polybar module config:

[module/battery_notifier]
type = custom/script
exec = ~/.config/polybar/battery-notifier.sh
interval = 60
Enter fullscreen mode Exit fullscreen mode

* Notice, that script is put to ~/.config/polybar/.

Comments 0 total

    Add comment