Last active
October 8, 2024 03:06
-
-
Save miyagawa/ed22215692e1937ab4bc to your computer and use it in GitHub Desktop.
Get OS X Bluetooth device's battery from the command line
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
➜ ~ ./battery.rb AppleBluetoothHIDKeyboard | |
{"BatteryPercent"=>49, "Product"=>"Tatsuhiko Miyagawa’s Keyboard"} | |
➜ ~ ./battery.rb BNBTrackpadDevice | |
{"BatteryPercent"=>39, "Product"=>"Tatsuhiko Miyagawa’s Trackpad"} |
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...
Can you get the "Product" name under the macOS 15?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
neat!
I looked
man ioreg
and found out the way to filter subtrees with "BatteryPercent" keyword.