2

I have Ubuntu 16.04 LTS on Lenovo z5170. I want to have a program (no matter what programming language) that notifies me that i'm running low on battery by a beep. I assume that the program should be sleeping until the moment that i'm out of battery(10% energy) but all I can think of is a while loop which eats up the whole processor and keeps everything else from running.

1- How should I implement such program ?

2- Which are the ways to notify users on specific event ?

Shadow_m2
  • 165

1 Answers1

1

In addition to the suggested duplicate methods, what you can do is this:

Find your battery interface path via upower -enumerate:

bash-4.3$ upower --enumerate
/org/freedesktop/UPower/devices/line_power_ACAD
/org/freedesktop/UPower/devices/battery_BAT1
/org/freedesktop/UPower/devices/DisplayDevice

Then use upower --show-info and trip its output. In my example that would be like so:

bash-4.3$ upower --show-info /org/freedesktop/UPower/devices/DisplayDevice | awk '/percentage/{gsub(/\%/,""); print $2}'
100

All you have to do now, is use a simple script to compare if that output value is less than or equal to certain threshold

#!/bin/bash

get_percentage()
{
     # Note, | \ must have only new line after it, no space
     upower --show-info /org/freedesktop/UPower/devices/battery_BAT1 |\
     awk '/percentage/{gsub(/\%/,""); print $2}'
}

main()
{
    while true
    do
        pcent=$(get_percentage)
        [ $pcent -le 10  ] && notify-send "Battery Low" "Please plug in charger"
        sleep 60 # check every minute
    done
}
main

As for notifying via beep, you could use aplay command and any audio file instead of notify-send. If you don't have GUI, you can also use wall command like so wall <<< "Battery low" and it will print to screen a message. NOTE: because of recent updates in gnome-terminal this doesn't work in gnome-terminal, but in TTYs and other terminal emulators it still does

Sergiy Kolodyazhnyy
  • 105,154
  • 20
  • 279
  • 497
  • Do you have any suggestion on how to completely disable this notification (my battery is broken). https://askubuntu.com/questions/1040830/bionic-block-notification-laptop-battery-critically-low – Porcupine Jun 16 '18 at 16:42
  • @Nikhil Maybe this can help http://www.webupd8.org/2016/10/nonotifications-indicator-09-released.html?m=1 – Sergiy Kolodyazhnyy Jun 17 '18 at 01:06