DEV Community

Kir Axanov
Kir Axanov

Posted on

Code. Battery notifier.

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/.

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

šŸ‘‹ Kindness is contagious

Please leave a ā¤ļø or a friendly comment on this post if you found it helpful!

Okay