Skip to content

Instantly share code, notes, and snippets.

@miyagawa miyagawa/battery.rb
Last active Jun 28, 2018

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

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

This comment has been minimized.

Copy link
Owner Author

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

This comment has been minimized.

Copy link

commented Dec 4, 2014

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.