Skip to content

Instantly share code, notes, and snippets.

@glightfoot
Created September 7, 2022 17:08
Show Gist options
  • Save glightfoot/6a1befc22a59c0cf555ce449612009cb to your computer and use it in GitHub Desktop.
Save glightfoot/6a1befc22a59c0cf555ce449612009cb to your computer and use it in GitHub Desktop.
Airpods Battery
#!/bin/bash
#set -eux
AIRPODS_NAME='Greg’s AirPods Pro'
OUTPUT='🎧'
BLUETOOTH_DEFAULTS=$(defaults read /Library/Preferences/com.apple.Bluetooth)
SYSTEM_PROFILER=$(system_profiler SPBluetoothDataType 2>/dev/null)
MAC_ADDR=$(grep -b3 "Minor Type: Headphones"<<<"${SYSTEM_PROFILER}"|grep -a1 ${AIRPODS_NAME}|awk '/Address/{print $3}')
CONNECTED=$(grep -ia6 "${MAC_ADDR}"<<<"${SYSTEM_PROFILER}"|awk '/Connected: Yes/{print 1}')
BLUETOOTH_DATA=$(grep -ia6 '"'"${MAC_ADDR}"'"'<<<"${BLUETOOTH_DEFAULTS}")
BATTERY_LEVELS=("BatteryPercentCombined" "HeadsetBattery" "BatteryPercentSingle" "BatteryPercentCase" "BatteryPercentLeft" "BatteryPercentRight")
if [[ "${CONNECTED}" ]]; then
for I in "${BATTERY_LEVELS[@]}"; do
declare -x "${I}"="$(awk -v pat="${I}" '$0~pat{gsub (";",""); print $3 }'<<<"${BLUETOOTH_DATA}")"
[[ ! -z "${!I}" ]] && OUTPUT="${OUTPUT} $(awk '/BatteryPercent/{print substr($0,15,1)": "}'<<<"${I}")${!I}%"
done
printf "%s\n" "${OUTPUT}"
else printf "%s Not Connected\n" "${OUTPUT}"
fi
echo "Connect"
#OUTPUT='🎧'; BLUETOOTH_DEFAULTS=$(defaults read /Library/Preferences/com.apple.Bluetooth); SYSTEM_PROFILER=$(system_profiler SPBluetoothDataType 2>/dev/null); MAC_ADDR=$(grep -b2 "Minor Type: Headphones"<<<"${SYSTEM_PROFILER}"|awk '/Address/{print $3}'); CONNECTED=$(grep -ia6 "${MAC_ADDR}"<<<"${SYSTEM_PROFILER}"|awk '/Connected: Yes/{print 1}'); BLUETOOTH_DATA=$(grep -ia6 '"'"${MAC_ADDR}"'"'<<<"${BLUETOOTH_DEFAULTS}"); BATTERY_LEVELS=("BatteryPercentCombined" "HeadsetBattery" "BatteryPercentSingle" "BatteryPercentCase" "BatteryPercentLeft" "BatteryPercentRight"); if [[ "${CONNECTED}" ]]; then for I in "${BATTERY_LEVELS[@]}"; do declare -x "${I}"="$(awk -v pat="${I}" '$0~pat{gsub (";",""); print $3 }'<<<"${BLUETOOTH_DATA}")"; [[ ! -z "${!I}" ]] && OUTPUT="${OUTPUT} $(awk '/BatteryPercent/{print substr($0,15,1)": "}'<<<"${I}")${!I}%"; done; printf "%s\n" "${OUTPUT}"; else printf "%s Not Connected\n" "${OUTPUT}"; fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment