-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbattery.py
executable file
·86 lines (73 loc) · 2.45 KB
/
battery.py
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
import os
import subprocess
import re
PWR_SPPLY = '/sys/class/power_supply/BAT0'
brightness_regex = re.compile(r"(\d*)")
class Battery(object):
def __init__(self):
if not os.path.exists(PWR_SPPLY):
raise FileNotFoundError(
"Default path to batter '{}' does not exist.".format(
PWR_SPPLY
)
)
@staticmethod
def _read_battery_descriptor(self, file):
"""
params: files in the directory
"""
file = os.path.join(PWR_SPPLY, file)
if not os.path.isfile(file):
raise FileNotFoundError(
"Invalid path '{}': File Not Found".format(
file
)
)
command = "cat {}".format(file)
try:
process = subprocess.Popen(
command,
stdout=subprocess.PIPE,
shell=True
)
result = process.stdout.read().decode().split("\n")[0]
finally:
process.stdout.close()
return result
@property
def percentage_remaining(self):
return int(_Battery._read_battery_descriptor("capacity"))
@property
def is_charging(self):
return _Battery._read_battery_descriptor("status") != "Discharging"
def get_brightness():
command = "gdbus call --session --dest org.gnome.SettingsDaemon.Power "\
"--object-path /org/gnome/SettingsDaemon/Power "\
"--method org.freedesktop.DBus.Properties.Get "\
"org.gnome.SettingsDaemon.Power.Screen Brightness"
try:
process = subprocess.Popen(
command,
stdout=subprocess.PIPE,
shell=True
)
result = brightness_regex.findall(process.stdout.read().decode())
finally:
process.stdout.close()
return int("".join(result))
def set_brightness(value: int):
if value not in range(101):
raise ValueError("Value must be between 0 and 100")
command = 'gdbus call --session --dest org.gnome.SettingsDaemon.Power '\
'--object-path /org/gnome/SettingsDaemon/Power '\
'--method org.freedesktop.DBus.Properties.Set '\
'org.gnome.SettingsDaemon.Power.Screen Brightness "<int32 {}>" '\
'> /dev/null'.format(value)
subprocess.call(
command,
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
)
bat = Battery()
print(bat._read_battery_descriptor(file='charge_now'))