Sideband/sbapp/plyer/platforms/linux/battery.py

68 lines
1.6 KiB
Python
Raw Normal View History

2022-09-16 12:07:57 -04:00
'''
Module of Linux API for plyer.battery.
'''
2023-10-19 20:37:27 -04:00
import os
2022-09-16 12:07:57 -04:00
from math import floor
from os import environ
from os.path import exists, join
from subprocess import Popen, PIPE
from plyer.facades import Battery
from plyer.utils import whereis_exe
class LinuxBattery(Battery):
'''
Implementation of Linux battery API via accessing the sysclass power_supply
path from the kernel.
'''
def _get_state(self):
status = {"isCharging": None, "percentage": None}
2023-10-19 20:37:27 -04:00
kernel_bat_path = join('/sys', 'class', 'power_supply', self.node_name)
2022-09-16 12:07:57 -04:00
uevent = join(kernel_bat_path, 'uevent')
2023-10-19 20:37:27 -04:00
with open(uevent, "rb") as fle:
2022-09-16 12:07:57 -04:00
lines = [
line.decode('utf-8').strip()
for line in fle.readlines()
]
output = {
line.split('=')[0]: line.split('=')[1]
for line in lines
}
is_charging = output['POWER_SUPPLY_STATUS'] == 'Charging'
2023-10-19 20:37:27 -04:00
charge_percent = float(output['POWER_SUPPLY_CAPACITY'])
2022-09-16 12:07:57 -04:00
2023-10-19 20:37:27 -04:00
status['percentage'] = charge_percent
2022-09-16 12:07:57 -04:00
status['isCharging'] = is_charging
return status
def instance():
'''
Instance for facade proxy.
'''
import sys
2023-10-19 20:37:27 -04:00
# if whereis_exe('upower'):
# return UPowerBattery()
# sys.stderr.write("upower not found.")
node_exists = False
bn = 0
node_name = None
for bi in range(0,10):
path = join('/sys', 'class', 'power_supply', 'BAT'+str(bi))
if os.path.isdir(path):
node_name = "BAT"+str(bi)
break
if node_name:
b = LinuxBattery()
b.node_name = node_name
return b
2022-09-16 12:07:57 -04:00
return Battery()