Skip to content

Instantly share code, notes, and snippets.

@j6s
Created March 24, 2016 17:58
Show Gist options
  • Save j6s/b26bba268b0a818d29db to your computer and use it in GitHub Desktop.
Save j6s/b26bba268b0a818d29db to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
#
# Send a notification using gnomes notification system
#
def notify(title, text)
`notify-send "#{title}" "#{text}"`
end
#
# Returns the integer value of a file
#
def getFileInt(file)
if File.exist?(file)
return File.read(file).to_i
else
return nil
end
end
#
# Gets the current battery level
#
def getBatteryPercentage()
return getFileInt("/sys/class/power_supply/BAT0/capacity")
end
#
# Notifies the user about the current battery level
#
def notifyBatteryLevel(level = nil)
if level == nil
level = getBatteryPercentage();
end
notify("Battery Level", level.to_s + "%")
end
#
# Sends out a notification, if the
#
def notifyIfDifference(difference = 10, tmpFile = "/tmp/battery_level")
puts "Checking for difference of more than " + difference.to_s;
level = getBatteryPercentage();
oldLevel = getFileInt(tmpFile);
if oldLevel == nil || level - 10 > oldLevel || level + 10 < oldLevel
notifyBatteryLevel(level);
File.open(tmpFile, "w") do |file|
file.puts(level)
end
end
end
#
# Prints the current usage to the user
#
def info()
msg = "Usage: ./battery_notify.rb ACTION
ACTIONS:
- notify: Sends a notification with the current battery load
- check: Only sends a notification on full steps";
puts msg;
notify("battery_notify", msg);
end
#
# Main logic block
#
if ARGV.length > 0
if ARGV[0] == "notify"
notifyBatteryLevel();
elsif ARGV[0] == "check"
if ARGV.length > 1
level = ARGV[1];
else
level = 10;
end
notifyIfDifference(level);
else
info();
end
else
info();
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment