No low battery popup notification in 16.04

13,042

Solution 1

Attempt reinstalling indicator-power with this command:

sudo apt-get install --reinstall indicator-power

If that doesn't solve the issue, consider using the battery monitoring script as provided by one of my previous answers : https://askubuntu.com/a/603322/295286

Below is python script that can notify you when battery charge gets past certain percentage, and suspend system once it is bellow 10 %. Usage is simple:

python battery_monitor.py INT

Where INT is integer value of your desired battery percentage at which you should receive notification, for example 30.

You can also add the above command to Startup Applications to start this script on every login into Unity session

Source code

As per OP requests in chat and comments , the script now takes two arguments, first for discharge notification and second os for charge notification.

Also available as Github Gitst

#!/usr/bin/env python
from gi.repository import Notify
import subprocess
from time import sleep, time
from sys import argv
import dbus


def send_notification(title, text):
    try:
        if Notify.init(argv[0]):
            n = Notify.Notification.new("Notify")
            n.update(title, text)
            n.set_urgency(2)
            if not n.show():
                raise SyntaxError("sending notification failed!")
        else:
            raise SyntaxError("can't initialize notification!")
    except SyntaxError as error:
        print(error)
        if error == "sending notification failed!":
            Notify.uninit()
    else:
        Notify.uninit()


def run_cmd(cmdlist):
    try:
        stdout = subprocess.check_output(cmdlist)
    except subprocess.CalledProcessError:
        pass
    else:
        if stdout:
            return stdout


def run_dbus_method(bus_type, obj, path, interface, method, arg):
    if bus_type == "session":
        bus = dbus.SessionBus()
    if bus_type == "system":
        bus = dbus.SystemBus()
    proxy = bus.get_object(obj, path)
    method = proxy.get_dbus_method(method, interface)
    if arg:
        return method(arg)
    else:
        return method()


def suspend_system():
    run_dbus_method('session',
                    'com.canonical.Unity',
                    '/com/canonical/Unity/Session',
                    'com.canonical.Unity.Session',
                    'Suspend', 'None')


def get_battery_percentage():
    output = run_cmd(['upower', '--dump']).decode().split('\n')
    found_battery = False
    for line in output:
        if 'BAT' in line:
            found_battery = True
        if found_battery and 'percentage' in line:
            return line.split()[1].split('%')[0]


def main():
    end = time()
    battery_path = ""
    for line in run_cmd(['upower', '-e']).decode().split('\n'):
        if 'battery_BAT' in line:
            battery_path = line
            break
    while True:
        notified = False
        while subprocess.call(['on_ac_power']) == 0:

            sleep(0.25)
            run_dbus_method('system', 'org.freedesktop.UPower',
                            battery_path, 'org.freedesktop.UPower.Device',
                            'Refresh', 'None')
            battery_percentage = int(get_battery_percentage())
            if battery_percentage == int(argv[2]) and not notified:
               subprocess.call( ['zenity', '--info','--text', 'Battery reached' + argv[2] + '%'  ]  ) 
               notified = True
        while subprocess.call(['on_ac_power']) == 1:

            sleep(0.25)
            run_dbus_method('system', 'org.freedesktop.UPower',
                            battery_path, 'org.freedesktop.UPower.Device',
                            'Refresh', 'None')
            battery_percentage = int(get_battery_percentage())

            if battery_percentage <= int(argv[1]):
                if battery_percentage <= 10:
                    send_notification('Low Battery',
                                      'Will suspend in 60 seconds')
                    sleep(60)
                    suspend_system()
                    continue
                if end < time():
                    end = time() + 600
                    send_notification('Low Battery', 'Plug in your charger')

if __name__ == '__main__':
    main()

Solution 2

This is not normal i have a 16.04 running and get popups but i'm using a gnome shell tho.

You can make a script that gives you a message.

battery_level=`acpi -b | grep -P -o '[0-9]+(?=%)'`
if [ $battery_level -le 10 ]
then
    notify-send "Battery low" "Battery level is ${battery_level}%!"
fi

Then make a cron job and run it every few minutes.

Solution 3

Yes, This is normal. I have written a simple bash script for setting up battery notifications.

#!/usr/bin/env bash
# check if acpi is installed.
if [ `dpkg -l | grep acpi | grep -v acpi-support | grep -v acpid | grep -c acpi` -ne 1 ]; then
    echo "run 'sudo apt install acpi' then run '$0' again."
    exit
fi

if [ $# -eq 1 ] && [ "$1" == "--install" ]; then
    echo "installing battery notifier..."

    if [ ! -e "$HOME/bin" ]; then
        mkdir $HOME/bin
    fi  

    cp $0 $HOME/bin/bn.sh
    (crontab -l 2>/dev/null; echo "*/2 * * * * $HOME/bin/bn.sh") | crontab -

else
    # check if power adapter is plugged in, if not, check battery status.
    if [ -z "`acpi -a | grep on-line`" ]; then
        batlvl=`acpi -b | grep -P -o '[0-9]+(?=%)'`

        if [ $batlvl -le 15 ] && [ $batlvl -ge 11 ]; then
            notify-send "Battery is at $batlvl%. Please plug your computer in."
        elif [ $batlvl -le 10 ] && [ $batlvl -ge 6 ]; then
            notify-send "Battery is at $batlvl%. Computer will shutdown at 5%."
        elif [ $batlvl -le 5 ]; then
            notify-send "BATTERY CRITICALLY LOW, SHUTTING DOWN IN 3 SECONDS!"
            sleep 3
            shutdown -h now
        fi
    fi  
fi

I also Have this and instructions on my github account. I hope this helps and makes it easier for you.

Share:
13,042

Related videos on Youtube

user227495
Author by

user227495

Updated on September 18, 2022

Comments

  • user227495
    user227495 almost 2 years

    I use Unity in 16.04. For some reason, I am not getting popup notifications for low battery. I have to rely on battery icon in top panel to see if battery is on the " low battery " side. Is the default behaviour in 16.04 ? Or I am not getting pop ups for low battery ?

    • Sergiy Kolodyazhnyy
      Sergiy Kolodyazhnyy almost 8 years
      You might try reinstallingindicator-power package。 If you want, i could also provide a script that can give you notification
    • user227495
      user227495 almost 8 years
      Thanks @Serg , kindly give me the commands to do the same.
    • Sergiy Kolodyazhnyy
      Sergiy Kolodyazhnyy almost 8 years
      ok, i will post an answer in a few minutes.
    • Sergiy Kolodyazhnyy
      Sergiy Kolodyazhnyy almost 8 years
      comments under my post have been moved to chat. We can continue troubleshooting there.
    • simgineer
      simgineer over 5 years
      @SergiyKolodyazhnyy Is this a low laptop battery or the motherboard battery. Does the solution discussed also refer to the motherboard's cmos battery normally used for keeping the clock alive?
    • Sergiy Kolodyazhnyy
      Sergiy Kolodyazhnyy over 5 years
      @simgineer This involves laptop battery, which typically has required sensors to provide necessary information. I'm not aware what method, if any, exist to check CMOS battery voltage.
    • VeganEye
      VeganEye about 4 years
      same problem on 18.04, I saw a tiny red dot on top left inside battery icon and found out power was disconnected! good I wasn't too long away from it...
  • user227495
    user227495 almost 8 years
    Thanks @Arne N. I do not know how to run corn jobs though. Also, any way to fi the core files so that we can skip the script ?
  • Cyber_Star
    Cyber_Star almost 8 years
    To make a cron job open up the terminal type in crontab -e choose the nano editor (only if you never made a cron job) by pressing 2 and enter, after that a file wil open scroll down to the bottom and add a new line. /2 * * * * my-script.sh Press ctrl + x and then type yand enter. That should work. No idea about the core files sorry.
  • user227495
    user227495 almost 8 years
    Will do. I am still trying it one by one. Was hoping to fix it through core files.
  • terdon
    terdon almost 8 years
    Comments are not for extended discussion. This conversation has been moved to chat.
  • VeganEye
    VeganEye about 4 years
    thx! I put this command at startupapps bash -c 'while true;do n="$(acpi -b |egrep "[[:digit:]]*%" -o |tr -d "%")";declare -p n;if((n<30));then notify-send "Low battery warning!" "$n%";fi;sleep $((5*60));done'