AirPods battery level with `ioreg`

I can query the battery level of my bluetooth devices with ioreg with

ioreg -r -l -n devicename | grep  '"BatteryPercent"\ =' 

with the following devices

  • Keyboards: IOAppleBluetoothHIDDriver, AppleBluetoothHIDKeyboard
  • Mice: BNBMouseDevice, AppleHSBluetoothDevice
  • Trackpad: BNBTrackpadDevice

Any idea which is the object name for Apple AirPods?


Solution 1:

You can query /Library/Preferences/com.apple.Bluetooth.plist with the defaults command line utility to get airpod battery levels. It doesn't use ioreg but is fairly extensible.

Some examples:

# Parse as XML and store in environment variables
battery_left=$(defaults export /Library/Preferences/com.apple.Bluetooth   - | xpath '//dict/key[text()="BatteryPercentLeft"]/following-sibling::integer[1]/text()' 2>/dev/null )
battery_right=$(defaults export /Library/Preferences/com.apple.Bluetooth   - | xpath '//dict/key[text()="BatteryPercentRight"]/following-sibling::integer[1]/text()' 2>/dev/null )
battery_case=$(defaults export /Library/Preferences/com.apple.Bluetooth   - | xpath '//dict/key[text()="BatteryPercentCase"]/following-sibling::integer[1]/text()' 2>/dev/null )
echo left: $battery_left
echo right: $battery_right
echo case: $battery_case

# Just show values from defaults plist text output
# Left
defaults read /Library/Preferences/com.apple.Bluetooth    | grep BatteryPercentLeft | tr -d \; | awk '{print $3}'

# Right
defaults read /Library/Preferences/com.apple.Bluetooth    | grep BatteryPercentRight | tr -d \; | awk '{print $3}'

# Case
defaults read /Library/Preferences/com.apple.Bluetooth    | grep BatteryPercentCase | tr -d \; | awk '{print $3}'

My case seems to always report as 0 unless the airpods are in it. If you have more than one connected set of airpods (or if other devices return similar information) you'll have to do something more complicated to differentiate between multiple devices.

This blog post has more info: https://blog.duklabs.com/airpods-power-in-touchbar/