| 1 |
''' |
| 2 |
Module of Linux API for plyer.battery. |
| 3 |
''' |
| 4 |
|
| 5 |
from math import floor |
| 6 |
from os import environ |
| 7 |
from os.path import exists, join |
| 8 |
from subprocess import Popen, PIPE |
| 9 |
from plyer.facades import Battery |
| 10 |
from plyer.utils import whereis_exe |
| 11 |
|
| 12 |
|
| 13 |
class LinuxBattery(Battery): |
| 14 |
''' |
| 15 |
Implementation of Linux battery API via accessing the sysclass power_supply |
| 16 |
path from the kernel. |
| 17 |
''' |
| 18 |
|
| 19 |
def _get_state(self): |
| 20 |
status = {"isCharging": None, "percentage": None} |
| 21 |
|
| 22 |
kernel_bat_path = join('/sys', 'class', 'power_supply', 'BAT0') |
| 23 |
uevent = join(kernel_bat_path, 'uevent') |
| 24 |
|
| 25 |
with open(uevent) as fle: |
| 26 |
lines = [ |
| 27 |
line.decode('utf-8').strip() |
| 28 |
for line in fle.readlines() |
| 29 |
] |
| 30 |
output = { |
| 31 |
line.split('=')[0]: line.split('=')[1] |
| 32 |
for line in lines |
| 33 |
} |
| 34 |
|
| 35 |
is_charging = output['POWER_SUPPLY_STATUS'] == 'Charging' |
| 36 |
total = float(output['POWER_SUPPLY_CHARGE_FULL']) |
| 37 |
now = float(output['POWER_SUPPLY_CHARGE_NOW']) |
| 38 |
|
| 39 |
capacity = floor(now / total * 100) |
| 40 |
|
| 41 |
status['percentage'] = capacity |
| 42 |
status['isCharging'] = is_charging |
| 43 |
return status |
| 44 |
|
| 45 |
|
| 46 |
class UPowerBattery(Battery): |
| 47 |
''' |
| 48 |
Implementation of UPower battery API. |
| 49 |
''' |
| 50 |
|
| 51 |
def _get_state(self): |
| 52 |
|
| 53 |
old_lang = environ.get('LANG', '') |
| 54 |
environ['LANG'] = 'C' |
| 55 |
status = {"isCharging": None, "percentage": None} |
| 56 |
|
| 57 |
|
| 58 |
|
| 59 |
|
| 60 |
|
| 61 |
dev = "/org/freedesktop/UPower/devices/battery_BAT0" |
| 62 |
upower_process = Popen( |
| 63 |
["upower", "--show-info", dev], |
| 64 |
stdout=PIPE |
| 65 |
) |
| 66 |
output = upower_process.communicate()[0].decode() |
| 67 |
environ['LANG'] = old_lang |
| 68 |
if not output: |
| 69 |
return status |
| 70 |
state = percentage = None |
| 71 |
|
| 72 |
for line in output.splitlines(): |
| 73 |
if 'state' in line: |
| 74 |
state = line.rpartition(':')[-1].strip() |
| 75 |
|
| 76 |
if 'percentage' in line: |
| 77 |
percentage = line.rpartition(':')[-1].strip()[:-1] |
| 78 |
|
| 79 |
|
| 80 |
|
| 81 |
percentage = float( |
| 82 |
percentage.replace(',', '.') |
| 83 |
) |
| 84 |
|
| 85 |
if state: |
| 86 |
status['isCharging'] = state == "charging" |
| 87 |
status['percentage'] = percentage |
| 88 |
return status |
| 89 |
|
| 90 |
|
| 91 |
def instance(): |
| 92 |
''' |
| 93 |
Instance for facade proxy. |
| 94 |
''' |
| 95 |
import sys |
| 96 |
if whereis_exe('upower'): |
| 97 |
return UPowerBattery() |
| 98 |
sys.stderr.write("upower not found.") |
| 99 |
|
| 100 |
if exists(join('/sys', 'class', 'power_supply', 'BAT0')): |
| 101 |
return LinuxBattery() |
| 102 |
return Battery() |