-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathPineBattery.py
226 lines (171 loc) · 7.16 KB
/
PineBattery.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
#!/usr/bin/env python3
# coding: utf-8
import subprocess
import json
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, GLib
class App(object):
"""
docstring
"""
def __init__(self, builder, ravg=10, interval=500):
self.device = builder.get_object('device_id')
self.cap_label = builder.get_object('cap_label')
self.cap_gauge = builder.get_object('cap_gauge')
self.voltage = builder.get_object('voltage_label')
self.current = builder.get_object('current_label')
self.power = builder.get_object('power_label')
self.sensor0 = builder.get_object('sensor0_value')
self.sensor1 = builder.get_object('sensor1_value')
self.sensor2 = builder.get_object('sensor2_value')
self.health = builder.get_object('health_label')
self.status = builder.get_object('status_label')
self.load = builder.get_object('load_label')
self.uptime = builder.get_object('uptime_label')
self.voltage_now = 0
self.current_now = 0
self.path = get_battery_path()
self.voltage_max_path = f"{self.path}/{get_voltage_max_path(self.path)}"
self.discharging = True
self.ravg = ravg
self.capacity_values = []
self.voltage_values = []
self.voltage_now_values = []
self.current_values = []
self.temperature_values = init_temp_sensors()
sensor_labels = ['sensor0_label', 'sensor1_label', 'sensor2_label']
sensor_values = ['sensor0_value', 'sensor1_value', 'sensor2_value']
sensor_names = self.temperature_values.keys()
# Set the sensor labels to match 'sensors' output
for label, name in zip(sensor_labels[:len(sensor_names)], sensor_names):
builder.get_object(label).set_text(f"{name.split('_')[0]} :")
# Blanks the sensor labels and values if not available
for label, value in zip(sensor_labels[len(sensor_names):],
sensor_values[len(sensor_names):]):
builder.get_object(label).set_text("")
builder.get_object(value).set_text("")
self.update_health()
self.updateValues()
# Start the auto-updater in the background with the selected interval
GLib.timeout_add(interval=interval, function=self.updateValues)
def calc_ravg(self, attr_name, value):
values = getattr(self, attr_name)
while len(values) >= self.ravg:
del(values[0])
values.append(value)
setattr(self, attr_name, values)
return sum(values) / len(values)
def calc_ravg_temp(self, chip, temp):
temps = self.temperature_values[chip]
while len(temps) >= self.ravg:
del(temps[0])
temps.append(temp)
self.temperature_values[chip] = temps
return sum(temps) / len(temps)
def updateValues(self):
self.update_capacity()
self.update_status()
self.update_voltage()
self.update_current()
self.update_power()
self.update_temperatures()
self.update_load()
self.update_uptime()
return True # Auto-updater stops if function doesn't return True
def update_capacity(self):
capacity = int(cat(f"{self.path}/capacity"))
ravg_capacity = self.calc_ravg("capacity_values", capacity)
self.cap_label.set_text(f"{ravg_capacity:.0f} %")
self.cap_gauge.set_value(ravg_capacity)
def update_voltage(self):
voltage = int(cat(self.voltage_max_path)) / 1000000
ravg_voltage = self.calc_ravg("voltage_values", voltage)
self.voltage.set_text(f"{ravg_voltage:.3f} V")
voltage_now = int(cat(f"{self.path}/voltage_now")) / 1000000
self.voltage_now = self.calc_ravg("voltage_now_values", voltage_now)
def update_current(self):
current = int(cat(f"{self.path}/current_now")) / 1000000
current = -current if self.discharging else current
ravg_current = self.calc_ravg("current_values", current)
self.current.set_text(f"{ravg_current:.3f} A")
self.current_now = ravg_current
def update_power(self):
power = self.voltage_now * self.current_now
self.power.set_text(f"{power:.3f} W")
def update_temperatures(self):
chips = self.temperature_values.keys()
labels = [self.sensor0, self.sensor1, self.sensor2]
data = sensors()
for chip, label in zip(chips, labels[:len(chips)]):
temp = data[chip]["temp1"]["temp1_input"]
ravg_temp = self.calc_ravg_temp(chip, temp)
label.set_text(f'{ravg_temp:.1f} °C')
def update_health(self):
health = cat(f"{self.path}/health")
if health:
self.health.set_text(f"Health : {health}")
else:
self.health.set_text("Health : N/A")
def update_status(self):
status = cat(f"{self.path}/status")
if status == "Discharging":
self.discharging = True
else:
self.discharging = False
self.status.set_text(status)
def update_load(self):
load = cat("/proc/loadavg")[:14].replace(" ", ", ")
self.load.set_text(f"Load : {load}")
def update_uptime(self):
self.uptime.set_text(f"Uptime : {uptime()[3:]}") # Removes "up "
def abs_path(filename):
script_path = "/".join(__file__.split("/")[:-1])
return f"{script_path}/{filename}"
def cat(path):
task = subprocess.Popen(["cat", path], stdout=subprocess.PIPE)
for item in task.stdout:
return item.decode("utf-8").strip()
def get_battery_path():
task = subprocess.Popen(["ls", "/sys/class/power_supply/"], stdout=subprocess.PIPE)
for item in task.stdout:
d_item = item.decode("utf-8").strip()
if "battery" in d_item:
return f"/sys/class/power_supply/{d_item}"
def ls(path):
task = subprocess.Popen(["ls", path], stdout=subprocess.PIPE)
return [item.decode("utf-8").strip() for item in task.stdout]
def get_voltage_max_path(battery_path):
parameters = ls(battery_path)
if "voltage_ocv" in parameters:
# It's a PinePhone or a PineTab
return "voltage_ocv"
elif "voltage_max" in parameters:
# It's a PinePhone Pro
return "voltage_max"
else:
# It's something else (PineBookPro)
return "voltage_now"
def uptime():
task = subprocess.Popen(["uptime", "-p"], stdout=subprocess.PIPE)
for item in task.stdout:
return item.decode("utf-8").strip()
def sensors():
task = subprocess.Popen(["sensors", "-j"], stdout=subprocess.PIPE)
buffer = ""
for item in task.stdout:
buffer += item.decode("utf-8").strip()
return json.loads(buffer)
def init_temp_sensors():
chips = sorted([chip for chip in sensors() if "cpu" in chip or "gpu" in chip])
return {chip:[] for chip in chips[:3]} # [:3] to make sure we get max 3 sensors
def main():
builder = Gtk.Builder()
builder.add_from_file(abs_path('UI.glade'))
window = builder.get_object('main_window')
window.connect('delete-event', Gtk.main_quit)
builder.connect_signals(App(builder))
window.show_all()
Gtk.main()
if __name__ == "__main__":
main()