pythonbatterylevel

How do i optimise my python code which reads Battery Staus


Basically i was trying to make a Py script what runs in background to notify the user when to plug in the charger and when to disconnect

the problem which i am facing is with the performance,The script uses more CPU time(May be because i used while loop)

Tell me if there is any better method to handle such a scenario.

I have already tried using sleep time but that did not work.

class Battery_code:

    def __init__(self, c_var):
        self.c_var = c_var

    def mbox(self, title, text, style):
        return Custom.windll.user32.MessageBoxW(0, text, title, style)



    while 1:
        battery = Reader.sensors_battery()
        plugged = battery.power_plugged
        percent = str(battery.percent)
        if plugged is False and int(percent) in range(40, 80, 1) and c_var == 0:
            speak.Speak("Charger is Disconnected Now")
            c_var += 1
            time.sleep(2)
        if plugged is True and int(percent) in range(40, 80, 1) and c_var == 0:
            speak.Speak("Charger is Connected Now")
            c_var += 1
            time.sleep(2)
        if plugged is True and int(percent) > 80:
            mbox('',
                 'Battery is at [' + percent + '%] and Still Plugged Please Unplug ', 0)
            speak.Speak("Please Unplug the charger to increase battery life")
            c_var = 0
        if plugged is False and int(percent) < 40:
            mbox('',
                 'Battery is at [' + percent + '%] Please Connect Charger  ', 0)
            speak.Speak("Please Connect charger to increase battery life")
            c_var = 0
    time.sleep(3)

Solution

  • use "battery.secsleft" to figure out how much time the user has left.

    Then with some simple math you can figure out when to give the alert and sleep until then. Of course, this can vary by usage, so you can use some extra padding for the time.

    Also, in cases: if plugged is True and int(percent) > 80: and if plugged is False and int(percent) < 40:

    you forgot to use sleep.