summaryrefslogtreecommitdiff
path: root/external/plyer/platforms/linux/battery.py
blob: 0cdb763534b497a696b9925ca3ec74d2d2147809 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
from subprocess import Popen, PIPE
from plyer.facades import Battery
from plyer.utils import whereis_exe

from os import environ


class LinuxBattery(Battery):
    def _get_state(self):
        old_lang = environ.get('LANG')
        environ['LANG'] = 'C'

        status = {"isCharging": None, "percentage": None}

        # We are supporting only one battery now
        dev = "/org/freedesktop/UPower/device/battery_BAT0"
        upower_process = Popen(["upower", "-d", dev],
                stdout=PIPE)
        output = upower_process.communicate()[0]

        environ['LANG'] = old_lang

        if not output:
            return status

        power_supply = percentage = None
        for l in output.splitlines():
            if 'power supply' in l:
                power_supply = l.rpartition(':')[-1].strip()
            if 'percentage' in l:
                percentage = float(l.rpartition(':')[-1].strip()[:-1])

        if(power_supply):
            status['isCharging'] = power_supply != "yes"

        status['percentage'] = percentage

        return status


def instance():
    import sys
    if whereis_exe('upower'):
        return LinuxBattery()
    sys.stderr.write("upower not found.")
    return Battery()