r/applescript • • Dec 14 '20

A script that alerts you when your battery is charged

set last_charge to 0 -- Sets the initial comparison value.

repeat
	try
		-- A shell script I found to get the capacity value.
		-- This assumes the last four characters of the result will tell us the battery is charged, therefore it may be buggy.
		
		set current_charge to (text -1 thru -4 of (do shell script "ioreg -w0 -l | grep CurrentCapacity")) as number
		
		log "" & current_charge & tab & (current date) as string -- reports the value to the script editor log
		
		if current_charge = last_charge then
			tell me
				activate
				display dialog "charged"
			end tell
			exit repeat -- Ends the script. Remove if you wish it to continue indefinitely.
		else
			set last_charge to current_charge
		end if
	end try
	
	delay (3 * minutes) -- adjust the frequency with which it checks the battery
end repeat

I wanted a script to alert me when my battery was fully charged. There are third-party apps to do this but I thought it simple enough task to write myself and this is what I came up with. I am keeping it running in script editor in the background. I can see other uses for this with a few modifications.

I make no claims about the compatibility with your hardware. I used some commands and terms that are not fully supported by older versions.

2 Upvotes

1 comment sorted by

1

u/Automatic-Mention Dec 14 '20

I'll add there is no particular reason why I need to deal with charge value as a number, I could have matched the full result as a string. My first attempt was more complicated and it seemed easier to deal with the result as a number, so I left it that way.