Skip to content

Instantly share code, notes, and snippets.

@ttscoff
Created July 8, 2019 16:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ttscoff/d39d732015113aa482ca495fcbaa9d07 to your computer and use it in GitHub Desktop.
Save ttscoff/d39d732015113aa482ca495fcbaa9d07 to your computer and use it in GitHub Desktop.
Ruby wrapper for brightness CLI (https://github.com/nriley/brightness)
#!/usr/bin/env ruby
# Brett Terpstra 2019
# This script adds the ability to increment/decrement display brightness
# levels to the nriley/brightness CLI (Copyright (c) 2014-2019, Nicholas Riley)
# Requires CLI installation: `brew install brightness`
# See https://github.com/nriley/brightness
CMD = "/usr/local/bin/brightness"
# Display usage and exit
def usage(code)
puts "Usage: #{File.basename(__FILE__)} [+-=]X"
puts " [+-]X increment/decrement by integer 0-100"
puts " =X set brightness 0-100"
Process.exit code
end
# Returns current brightness of the first display as a percentage
# (0-100). All displays will end up set to the same level, so we're only
# checking for the first display.
def get_brightness
details = %x{#{CMD} -l}
return (details.match(/display 0: brightness (\d\.\d+)/)[1].to_f.round(2) * 100).to_i
end
# Set brightness of all displays to a percentage (0-100)
def set_brightness(level)
target = level * 0.01
return system %Q{"#{CMD}" #{target} &> /dev/null}
end
def main(arg)
# if the argument starts with =, set brightness
if arg =~ /^=(\d{1,3})/
target = $1.to_i
if target < 0 || target > 100
puts "Error: #{target} is out of range"
usage(1)
end
# if argument is a positive or negative integer, increment or decrement
# brightness
else
inc = arg.to_i
current = get_brightness
target = (current + inc)
# ensure the adjusted level is in range. Don't throw an error, allow
# overruns and just compensate
if target > 100
target = 100
elsif target < 0
target = 0
end
end
# Execute CLI
res = set_brightness(target)
if res
$stdout.print get_brightness
else
$stdout.puts "Error setting brightness"
Process.exit 1
end
end
# Ensure brightness CLI is installed
unless File.executable?(CMD)
puts "Error: brightness executable missing"
puts "Requires brightness CLI (brew install brightness)"
Process.exit 1
end
# Ensure the argument is valid
if ARGV.length != 1 || ARGV[0] !~ /^[+-=]?\d{1,3}$/
usage(1)
else
main(ARGV[0])
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment