warning of power cable still plugged in

tkimpton
Valued Contributor II

Hi guys

Im trying to work out a script and wondered if anyone may be able to help?

I am running a script at logout that will detect if the AC power is still plugged in and remind people to unplug it before they leave the office to avoid damage to battery cells.

The problem i have is trying to work out to get an if argument that will detect if the battery power is more than 80%.

This is what i have so far

#!/bin/bash

##### ENVIRONMENT VARIABLES #####

# Specify a laptop using system profiler

Laptop=`system_profiler SPHardwareDataType | grep -E "MacBook"`

# Get the battery percentage
Bat=`ioreg -n AppleSmartBattery -r | awk '$1~/Capacity/{c[$1]=$3} END{OFMT="%.2f%%"; max=c[""MaxCapacity""]; print (max>0? 100*c[""CurrentCapacity""]/max: "?")}'`

# Specifying the message

MSG="Your power cable is still plugged in.

Remove it please otherwise you are at risk of damaging the cells in the battery leaving it plugged in for long periods of time.

                   Thank you"


#### DO NOT MODIFY BELOW THIS LINE ####


## Check if all the conditions are met
if [ "$Laptop" ] && [[ $(pmset -g ps | head -1) =~ "AC Power" ]] ; then


# Display the message with a 5 minute timeout
sudo /Library/Application Support/JAMF/bin/jamfHelper.app/Contents/MacOS/jamfHelper 
-windowType utility -title "Warning" -description "$MSG" -timeout 300 -button1 "OK" 
-icon /System/Library/CoreServices/CoreTypes.bundle/Contents/Resources/AlertCautionIcon.icns -iconSize 96

fi

exit 0
3 ACCEPTED SOLUTIONS

tkimpton
Valued Contributor II

i decided to change the if statement to

if [ "$Laptop" ] && [[ "$Bat" == "100%" ]] && [[ $(pmset -g ps | head -1) =~ "AC Power" ]] ; then

seeing as the culprits are probably going to have it plugged in all day anyway and will most likely be at 100% when they shutdown or either log out.

View solution in original post

mm2270
Legendary Contributor III

If you still want to look at the percentage and only warn if the battery charge is beyond a certain threshold, you could calculate the pct in a different way. Not sure if the code you have above is something you found somewhere, but the issue is that the output includes the % sign, which would make it hard to do an integer greater than/less than comparison.
Instead, you can pull the current battery capacity and the Max battery capacity (not design capacity, but what it can currently hold) and then use bash to do a percentage calculation.

#!/bin/bash

BattCurrent=$( ioreg -n AppleSmartBattery -r | awk '/CurrentCapacity/{print $NF}' )
BattMax=$( ioreg -n AppleSmartBattery -r | awk '/MaxCapacity/{print $NF}' )
BattPct=$((BattCurrent*100/BattMax))

if [[ "$BattPct" -ge "80" ]]; then
    echo "Battery charge is above 80%. Current charge is: $BattPct%"
fi

View solution in original post

sean
Valued Contributor

There's some fantastic maths, but did you realise that pmset gives you the battery percentage? In fact, if you test for battery status, the you don't have to bother checking System Profiler to work out the model, only laptops have batteries.

#!/bin/bash

BatteryTest=`pmset -g batt`

if [[ "$BatteryTest" =~ "100%" ]] && [[ "$BatteryTest" =~ "AC" ]]
then
        # If you wanted the percentage then
        # Bat=`echo ${BatteryTest%%*} | awk '{print $NF}'`
        echo "Take the power out"
fi

View solution in original post

16 REPLIES 16

tkimpton
Valued Contributor II

i decided to change the if statement to

if [ "$Laptop" ] && [[ "$Bat" == "100%" ]] && [[ $(pmset -g ps | head -1) =~ "AC Power" ]] ; then

seeing as the culprits are probably going to have it plugged in all day anyway and will most likely be at 100% when they shutdown or either log out.

tkimpton
Valued Contributor II

double post

mm2270
Legendary Contributor III

If you still want to look at the percentage and only warn if the battery charge is beyond a certain threshold, you could calculate the pct in a different way. Not sure if the code you have above is something you found somewhere, but the issue is that the output includes the % sign, which would make it hard to do an integer greater than/less than comparison.
Instead, you can pull the current battery capacity and the Max battery capacity (not design capacity, but what it can currently hold) and then use bash to do a percentage calculation.

#!/bin/bash

BattCurrent=$( ioreg -n AppleSmartBattery -r | awk '/CurrentCapacity/{print $NF}' )
BattMax=$( ioreg -n AppleSmartBattery -r | awk '/MaxCapacity/{print $NF}' )
BattPct=$((BattCurrent*100/BattMax))

if [[ "$BattPct" -ge "80" ]]; then
    echo "Battery charge is above 80%. Current charge is: $BattPct%"
fi

mm2270
Legendary Contributor III

Double post

bajones
Contributor II

@tkimpton What sort of damage are you trying to avoid? The only required task with Apple batteries (and all Li Ion and LiPo batteries AFAIK) is to fully discharge them once a month to maintain their full charge capacity. They can be plugged in safely 24/7 for the rest of the month.

tkimpton
Valued Contributor II

@mm2270 Thanks very much that's very helpful, much appreciated :)

@bajones its just what I want to do

sean
Valued Contributor

There's some fantastic maths, but did you realise that pmset gives you the battery percentage? In fact, if you test for battery status, the you don't have to bother checking System Profiler to work out the model, only laptops have batteries.

#!/bin/bash

BatteryTest=`pmset -g batt`

if [[ "$BatteryTest" =~ "100%" ]] && [[ "$BatteryTest" =~ "AC" ]]
then
        # If you wanted the percentage then
        # Bat=`echo ${BatteryTest%%*} | awk '{print $NF}'`
        echo "Take the power out"
fi

tkimpton
Valued Contributor II

@sean good point, thanks :)

tkimpton
Valued Contributor II

sweet...thanks guys :)

#!/bin/bash

##### INTRO #####
#
# With help from Mike and Sean on the jamf community https://jamfnation.jamfsoftware.com/discussion.html?id=9998
#
# Laptop batteries aren't lasting very long because of people leaving them charging overnight and not using them as laptops
#
# This script is design to run at logout to remind the user to unplug it


##### ENVIRONMENT VARIABLES #####

# Use pmset to look for AC power
BatteryTest=`pmset -g batt`

# Get the percentage of the battery
Bat=`echo ${BatteryTest%%*} | awk '{print $NF}'`

MSG="Your battery is at $Bat% and your power cable is still plugged in.

Remove it please otherwise you are at risk of damaging the cells through over charging.

                Thank you"



####### DO NOT MODIFY BELOW THIS LINE #######


if [[ "$BatteryTest" =~ "100%" ]] && [[ "$BatteryTest" =~ "AC" ]]

then


# Display the message with a 5 minute timeout
sudo /Library/Application Support/JAMF/bin/jamfHelper.app/Contents/MacOS/jamfHelper 
-windowType utility -title "Warning" -description "$MSG" -timeout 300 -button1 "OK"  
-icon /System/Library/CoreServices/CoreTypes.bundle/Contents/Resources/AlertCautionIcon.icns -iconSize 96

echo "$Bat"

fi

exit 0

tkimpton
Valued Contributor II

a loop would be cool, but im unsure how to implement that, anyone have any ideas please?

jacob_salmela
Contributor II

Something like this maybe?

#!/bin/bash
#------VARIABLES-------
desiredPercentage="80"
battStatus=$(pmset -g batt | awk '/charging|discharging|charged/ {print $3}' | cut -d";" -f1)

#------FUNCTIONS-------
########################
function monitorCharge()
    {
    # While the battery is set to "charging" or "charged"
    while [ "$battStatus" = "charging" ] || [ "$battStatus" = "charged" ]
        do  
            # Check the status of the battery to see if changed since entering the loop
            battStatus=$(pmset -g batt | awk '/charging|discharging|charged/ {print $3}' | cut -d";" -f1)

            # Check battery percentage and store it in a variable
            currentPercentage=$(pmset -g batt | grep -o "[0-9]+%;" | cut -d"%" -f1)

            # If the current battery is greater than or equal to the desired percentage, then
            if [ "$currentPercentage" -ge "$desiredPercentage" ];then

                # Let the user know
                # Or run some other commands
                say "Unplug me before you leave." 
            fi 
    # Close the while loop
    done
    }

#----BEGIN SCRIPT-----
monitorCharge

I wrote a script last year to drain the battery since we store the laptops over the summer--the code above, slightly modified, seems to get the desired effect.

tkimpton
Valued Contributor II

@jacob_salmela thanks very much i really appreciate it :)

tkimpton
Valued Contributor II

duplicate post

joelreid
New Contributor III

Anyone can do whatever they please, but addressing random readers out there as an advisory; some of the approaches and actions mentioned in this thread could be harmful to your batteries, or at least please be careful not to misinterpret anything above. Get the facts and do what's best for your mobile devices.
- Modern Li-ion and Li-poly batteries do need some exercise, but overall battery lifespan is reduced by having a high cycle count, even partials. (e.g. two half-drains = one full-drain “cycle”. Apple batteries even count their own cycles!)
- Occasional drains to zero are okay, and have a silver lining of recalibrating charge-percent readings, but frequent drains to zero are unnecessary and cause permanent capacity loss.
- Modern Li-ion and Li-poly batteries should never be stored empty. It causes permanent capacity loss or inability to take a charge at all.
- [Apple] power managers will never over-charge a battery. Trickle-charging during everyday use is mostly okay as long as it never gets hot while charging (in a bag, direct sunlight, etc.).

Here's howtogeek's nice rundown of best-practices and info for laptop/tablet/phone batteries in this, the post-NiCd/NimH age.
And Apple's general battery advice and notebook battery care. Hmm… and for fun, Dell, Sony, and Lenovo.

cheers! —Joel, edu casper guy by day, EE on the weekends.

tkimpton
Valued Contributor II

@jreid thanks but I'm going to just activate the policy over holidays eg xmas etc

tkimpton
Valued Contributor II

@@jreid a good read thanks very much for the clarification :)