Skip to content

Instantly share code, notes, and snippets.

@NeoCat
Last active December 31, 2016 13:49
Show Gist options
  • Save NeoCat/7f65988d186b7da776af357296c7e022 to your computer and use it in GitHub Desktop.
Save NeoCat/7f65988d186b7da776af357296c7e022 to your computer and use it in GitHub Desktop.
Monitor iOS battery level and stop charging when the level >= 80% (restart when the level < 80%)
#!/usr/bin/ruby
require 'timeout'
THRESH = 80 # %
SPEED = 60 # sec / %
$IDEVICEINFO_CMD = '/usr/local/bin/ideviceinfo'
$POWER_ON_CMD = 'curl -s -m 5 192.168.x.x/on'
$POWER_OFF_CMD = 'curl -s -m 5 192.168.x.x/off'
$state = nil
$caffe_pid = nil
trap(:CHLD, "IGNORE")
def get_batt(device_id)
result = nil
begin
timeout(10) {
result = `#{$IDEVICEINFO_CMD} -u #{device_id} -q com.apple.mobile.battery`
}
rescue => e
STDERR.puts "#{Time.now}\t#{e}"
end
if result =~ /BatteryCurrentCapacity:\s*(\d+)/
return $1.to_i
end
nil
end
def power_on
if $state != :on
puts "on: " + `#{$POWER_ON_CMD}`
$caffe_pid = fork { exec "caffeinate -i" }
$state = :on
end
end
def power_off
if $state != :off
puts "off: " + `#{$POWER_OFF_CMD}`
$state = :off
Process.kill :INT, $caffe_pid if $caffe_pid
$caffe_pid = nil
end
end
device_id = ARGV[0] || 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' # default serial
reset_time = Time.now
last_time = Time.new(0)
last_batt = nil
loop do
batt = get_batt device_id
if batt
last_time = Time.now
last_batt = batt
reset_time = last_time + [360, batt >= THRESH ? 360 : (THRESH - last_batt)*SPEED].min
puts "#{last_time}\t#{batt} # timeout: #{reset_time}"
if batt < THRESH
power_on
else
power_off
end
sleep 30
else
if Time.now - last_time <= 32
sleep 30
next
end
sleep 2
if Time.now >= reset_time # time out
reset_time = Time.now + 120 # avoid frequent on/off
# try turn on the device
puts "#{Time.now}\t# reset"
power_off
sleep 10
power_on
now = Time.now
if last_batt and last_batt + (now - last_time)/SPEED >= THRESH
# turn off if estimated batt >= THRESH
sleep 2
power_off
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment