Skip to content

Instantly share code, notes, and snippets.

@julioflima
Last active February 12, 2025 15:06
Show Gist options
  • Save julioflima/f62fad64a1dc6cfe639f6e186276a363 to your computer and use it in GitHub Desktop.
Save julioflima/f62fad64a1dc6cfe639f6e186276a363 to your computer and use it in GitHub Desktop.
Bright Control

I did something, better then Apple 🍎. I don't know if you noted, but everytime I logoff in our call, my computer shutdown, because I didn't saw the alert about battery.

With this the screen will turn off, it's impossible doesn't notice, but this will happen before the computer turn off, 1% before.

touch ~/bright_control.sh


while true; do
    # Get the battery level
    battery=$(pmset -g batt | grep -o "[0-9]\+%" | sed 's/%//')
    charger=$(pmset -g batt | grep "AC Power")

    # Display information in the Terminal for debugging
    echo "πŸ”‹ Battery: $battery%"
    echo "πŸ”Œ Charger connected: $charger"

    # If the battery is at 2% or less and the charger is not connected, turn off the screen
    if [[ $battery -le 2 && -z "$charger" ]]; then
        echo "⚠️ Low battery - Turning off screen..."
        pmset displaysleepnow
    fi

    # If the charger is connected, restore brightness and prevent sleep
    if [[ -n "$charger" ]]; then
        echo "πŸ”Œ Charger detected - Restoring screen..."
        pmset -a displaysleep 10
    fi

    # Wait 5 seconds for faster detection
    sleep 5
done

chmod +x ~/bright_control.sh

chmod 644 ~/Library/LaunchAgents/com.usuario.brightcontrol.plist

chown $(whoami):staff ~/Library/LaunchAgents/com.usuario.brightcontrol.plist

nano ~/Library/LaunchAgents/com.usuario.brightcontrol.plist

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
    <dict>
        <key>Label</key>
        <string>com.usuario.brightcontrol</string>
        <key>ProgramArguments</key>
        <array>
            <string>/Users/YOUR_USER/bright_control.sh</string>
        </array>
        <key>RunAtLoad</key>
        <true/>
        <key>KeepAlive</key>
        <true/>
    </dict>
</plist>

sudo visudo

Add this line:

%admin ALL=(ALL) NOPASSWD: /usr/bin/pmset

Use :wq to save and go out.

Reboot!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment