Reputation: 1
#!/bin/sh
percent=`upower -i /org/freedesktop/UPower/devices/battery_BAT0 | grep percentage:
notify-send "battery life" "$percent"
It works as intended, and pops up with this notification when called.
I wrote the script because my window manager, i3 lacks a notification system for battery status, so I found myself running out of battery on my laptop even though I was right next to an outlet at home.
Of course; having a script like this is pointlesss unless it's automated to pop up by itself, so after some fiddling, I set up a Cron-job that runs the script every 10 minutes.
This is what the cron-tab looks like:
*/10 * * * * export DISPLAY=:0 ; export DBUS_SESSION_BUS_ADDRESS=a; batterystatus.sh
It works, except that without the little snippet about the DBUS_SESSION_BUS_ADDRESS stuff, for some reason notify-status
doesn't work.
So, everything was cool until I rebooted and found that this value used in the cron-tab: unix:abstract=/tmp/dbus-FOSTebXqX5,guid=a7ad198d91d224b8c056efc6615a3610
changes upon boot.
That means that I would have to change the cron-job everytime I boot up my computer so that the script would work.
Is there any way around this?
Upvotes: 0
Views: 227
Reputation: 8014
Rather than use crontab
, it might be better to use systemd
. You can have a systemd user service and timer so that D-Bus has access to the session D-Bus information for session notifications.
I've tested this out using the Python dbus library pydbus as an example bus I'm sure you could use your shell script also.
Python script for getting battery power and posting notifications:
#!/usr/bin/python3
import pydbus
sys_bus = pydbus.SystemBus()
ses_bus = pydbus.SessionBus()
power = sys_bus.get('.UPower', '/org/freedesktop/UPower/devices/battery_BAT0')
notifications = ses_bus.get('.Notifications')
print(power.Percentage)
notifications.Notify('test', 0, 'dialog-information', "Battery Notification!",
f"Percentage: {power.Percentage}%", [], {}, 5000)
Created a user service in /etc/systemd/user/battery.service
:
[Unit]
Description=Check for battery percentage
[Service]
Type=dbus
BusName=org.freedesktop.Notifications
ExecStart=/home/thinkabit1/stack_overflow/battery_monitor.py
You can test this works with:
$ systemctl --user start battery.service
To see the status of the service do:
$ systemctl --user status battery.service
To have a timer run this every 10 minutes create /etc/systemd/user/battery.timer
[Unit]
Description=Run battery monitor every 10 minutes
[Timer]
OnBootSec=10min
OnUnitActiveSec=10min
[Install]
WantedBy=timers.target
This can be started with:
$ systemctl --user start battery.timer
To see the status:
$ systemctl --user list-timers
To have it start automatically after reboot use:
systemctl --user enable battery.timer
Upvotes: 0