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"} |
This comment has been minimized.
This comment has been minimized.
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... |
This comment has been minimized.
This comment has been minimized.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This comment has been minimized.
neat!
I looked
man ioreg
and found out the way to filter subtrees with "BatteryPercent" keyword.