Skip to content

Instantly share code, notes, and snippets.

@miyagawa
Last active April 13, 2024 10:13
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save miyagawa/ed22215692e1937ab4bc to your computer and use it in GitHub Desktop.
Save miyagawa/ed22215692e1937ab4bc to your computer and use it in GitHub Desktop.
Get OS X Bluetooth device's battery from the command line
#!/usr/bin/env ruby
require 'plist'
def visit(thing, want, &block)
case thing
when Hash
thing.keys.each do |key|
if want.include?(key)
yield key, thing[key]
else
visit thing[key], want, &block
end
end
when Array
thing.each do |value|
visit value, want, &block
end
end
end
plist = Plist::parse_xml(`ioreg -c #{ARGV[0]} -a`)
props = {}
visit plist, ["BatteryPercent", "Product"] do |key, value|
props[key] ||= value
end
p props
➜ ~ ./battery.rb AppleBluetoothHIDKeyboard
{"BatteryPercent"=>49, "Product"=>"Tatsuhiko Miyagawa’s Keyboard"}
➜ ~ ./battery.rb BNBTrackpadDevice
{"BatteryPercent"=>39, "Product"=>"Tatsuhiko Miyagawa’s Trackpad"}
@sekimura
Copy link

sekimura commented Dec 3, 2014

neat!

I looked man ioreg and found out the way to filter subtrees with "BatteryPercent" keyword.

    $ ioreg -r -d 1 -k BatteryPercent | egrep '("BatteryPercent"|"Product") '
          "Product" = "Masayoshi Sekimura�s Trackpad"
          "BatteryPercent" = 42

@miyagawa
Copy link
Author

miyagawa commented Dec 4, 2014

Cool, I incorporated that into https://github.com/miyagawa/btbattery

The plist thing is a bit weird since it's an ordered key-value so you have to track state...

@sekimura
Copy link

sekimura commented Dec 4, 2014

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment