Created
July 19, 2024 21:52
-
-
Save zkarj735/ad70e786e85404deb686aedfd776444c to your computer and use it in GitHub Desktop.
SwiftBar plugin to show Apple "Magic" peripheral battery levels
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
#!/bin/zsh | |
tmp=$(ioreg -c 'AppleDeviceManagementHIDEventService' | grep 'BatteryPercent\|\"Magic' | sed -e 's/[ |]*//' -e 's/\"//g' -e 's/\Product = //' -e 's/BatteryPercent //' | paste -d\ - - | sed 's/Magic \(.\).* = /\1/') | |
arr=(${(f)tmp}) | |
count=1 | |
for d in "${arr[@]}"; do | |
# Extract type and percentage | |
type="${d[1,1]}" | |
pct="${d[2,3]}" | |
# Define base symbol based on type | |
if [ "$type" = "M" ]; then | |
symbol="magicmouse" | |
fi | |
if [ "$type" = "T" ]; then | |
symbol="rectangle" | |
fi | |
if [ "$type" = "K" ]; then | |
symbol="keyboard" | |
fi | |
# Define warning state based on percentage | |
state="OK" | |
if [[ $pct -lt 30 ]]; then | |
state="WARN" | |
fi | |
if [[ $pct -lt 10 ]]; then | |
state="DANGER" | |
fi | |
# Use filled symbol if WARN or DANGER | |
if [ "$state" != "OK" ]; then | |
symbol="${symbol}.fill" | |
fi | |
# Wrap the symbol for SwiftBar | |
symbol=":${symbol}:" | |
# Define the symbol colour | |
if [ "$state" = "OK" ]; then | |
sfcol="sfcolor${count}=#aaaaaa" | |
fi | |
if [ "$state" = "WARN" ]; then | |
sfcol="sfcolor${count}=#ff8800" | |
fi | |
if [ "$state" = "DANGER" ]; then | |
sfcol="sfcolor${count}=#ff0000" | |
fi | |
# Append the symbol and percentage to the output | |
if [[ $count -eq 1 ]]; then | |
data="${symbol}${pct}" | |
else | |
data="${data} ${symbol}${pct}" | |
fi | |
# Append the symbol colour to the parameters | |
if [[ $count -eq 1 ]]; then | |
parm="${sfcol}" | |
else | |
parm="${parm} ${sfcol}" | |
fi | |
((count++)) | |
done | |
# Prepend standard parameters | |
parm="color=#ffffff sfsize=14 ${parm}" | |
# Echo the full output | |
echo "${data} | ${parm}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment