3
#! /bin/bash

# Read battery percentage value
OUT=`upower -i /org/freedesktop/UPower/devices/battery_BAT1 | grep percentage`

# Select only the int value
IFS=':' read -ra P <<< "$OUT"
PERCENTAGE="%"
BATTERY_VALUE=${P[1]%$PERCENTAGE}

# Send a notification if battery level is under 15% and not on AC power
if ! on_ac_power; then
  if (($BATTERY_VALUE  < "15")); then
      eval "export $(egrep -z DBUS_SESSION_BUS_ADDRESS /proc/$(pgrep -u $LOGNAME gnome-session)/environ)";
      notify-send -u critical -i "battery-caution" "Battery low! You should plug in your laptop!"
      /usr/bin/aplay /usr/share/sounds/desktop-logout.oga
  fi
fi

# Send a notification if battery level is equal to or over 90% and is on AC power
if on_ac_power; then
  if (($BATTERY_VALUE  >= "90")); then
      eval "export $(egrep -z DBUS_SESSION_BUS_ADDRESS /proc/$(pgrep -u $LOGNAME gnome-session)/environ)";
      notify-send -u critical -i "battery-full-charging" "Battery charged! You should unplug your laptop!"
      /usr/bin/aplay /usr/share/sounds/desktop-logout.oga
  fi
fi

Sound and script working fine if I execute the script manually. I get a notification from notify-send but it doesn't play sound from crontab. Cron log is saying:

Connection failure: Connection refused
pa_context_connect() failed: Connection refused. 

I've tried the command paplay and pointing to the absolute path of paplay in /usr/bin/paplay to no avail.

Pablo Bianchi
  • 15,657

1 Answers1

5

I find out that when I should send a sound with pulseaudio in the command line to another user, you should indicate the environment variable:

XDG_RUNTIME_DIR="/run/user/usr_id"

Replacing "usr_id`" with an id (a number) corresponding the user (here how to get it outside crontab).

Example cronjob:

* * * * * XDG_RUNTIME_DIR=/run/user/$(id -u) /path/to/script

it will automatically use current user ID.

The problem appears to be that the environment of the crontab is very limited.

Source: ArchLinux Wiki: PulseAudio

16851556
  • 561
VHMG
  • 71