-
Notifications
You must be signed in to change notification settings - Fork 0
/
battery.py
281 lines (225 loc) · 8.37 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
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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
#!/usr/bin/env python3
# encoding: utf-8
#
# Copyright (c) 2023 Thomas Harr <xDevThomas@gmail.com>
#
# MIT Licence. See http://opensource.org/licenses/MIT
#
# Created on 2023-01-03
#
import json
import os
import shutil
import subprocess
import sys
import tempfile
from workflow import Workflow
from workflow.util import run_command
# GitHub repo for self-updating
UPDATE_SETTINGS = {'github_slug': 'harrtho/alfred-battery'}
# GitHub Issues
HELP_URL = 'https://github.com/harrtho/alfred-battery/issues'
# Icon shown if a newer version is available
ICON_UPDATE = 'icons/update.png'
ICON_ERROR = 'icons/error.png'
ICON_CHARGING = 'icons//charging.png'
ICON_POWER = 'icons/power.png'
ICON_FULL = 'icons/full.png'
ICON_MEDIUM = 'icons/medium.png'
ICON_LOW = 'icons/low.png'
ICON_CRITICAL = 'icons/critical.png'
ICON_CLOCK = 'icons/clock.png'
ICON_TEMP = 'icons/temp.png'
ICON_CYCLES = 'icons/cycles.png'
ICON_HEALTH = 'icons/health.png'
ICON_SERIAL = 'icons/serial.png'
class BatteryInfo(object):
"""Encapsulates the functionality of the battery workflow
Display battery information of your Apple laptop.
"""
def __init__(self) -> None:
"""Create a new ``BatteryInfo`` object.
"""
self.wf = None
def battery_info_program(self):
"""Return path to BatteryInfo executable.
Returns:
str: Path to ``BatteryInfo`` executable.
"""
return self.wf.cachefile('BatteryInfo')
def battery_info_check_update(self):
key = '__battery_info_update'
# Cache that a workflow update is available. This will lead to a BatteryInfo update
if self.wf.update_available:
status = self.wf.cache_data(key, {
'available': True,
'version' : self.wf.version
})
return False
status = self.wf.cached_data(key, max_age=0)
if not status or not status.get('available'):
return False
return True
def install_battery_info(self):
bi = self.battery_info_program()
if os.path.exists(bi):
os.unlink(bi)
tempdir = tempfile.mkdtemp(prefix='aw-', dir=self.wf.cachedir)
try:
os.chdir(tempdir)
source_code = os.path.join(self.wf.workflowdir, 'BatteryInfo.swift')
binary_src = os.path.join(tempdir, 'BatteryInfo')
binary_dest = os.path.join(self.wf.cachedir, 'BatteryInfo')
cmd = [
'swiftc',
source_code]
retcode = subprocess.call(cmd)
if retcode != 0:
raise RuntimeError(f'BatteryInfo compilation exited with {retcode}')
if not os.path.exists(binary_src): # pragma: nocover
raise ValueError(f'Compiled BatteryInfo file not found: {binary_src}')
shutil.move(binary_src, binary_dest)
if not os.path.exists(binary_dest): # pragma: nocover
raise ValueError(f'Compiled BatteryInfo file not found: {binary_src}')
finally:
os.chdir(self.wf.workflowdir)
try:
shutil.rmtree(tempdir)
except OSError: # pragma: no cover
pass
# Update successfully
self.wf.cache_data('__battery_info_update', {
'available': False,
'version' : self.wf.version
})
def convert_battery_info(self, info):
try:
return True, json.loads(info)
except ValueError as e:
return False, None
def get_battery_info(self) -> tuple[bool, dict | str]:
"""Get the system battery information from your laptop
Returns:
tuple[bool, dict | str]: In case of success True and the battery info
otherwise False and None
"""
bi = self.battery_info_program()
# Install if BatteryInfo does not exist
if (not os.path.exists(bi)) or self.battery_info_check_update():
self.install_battery_info()
output = run_command([bi]).decode('utf-8')
return self.convert_battery_info(output)
def show_error(self, battery_err):
self.wf.add_item(title='Retrieved an error',
subtitle=battery_err,
valid=False,
icon=ICON_ERROR
)
def show_info(self, battery_info):
raw_current_capacity = battery_info['AppleRawCurrentCapacity']
raw_max_capacity = battery_info['AppleRawMaxCapacity']
design_capacity = battery_info['DesignCapacity']
charge = round(raw_current_capacity * 100 / raw_max_capacity, 2)
loaded = '●' * round(charge/10)
unloaded = '○' * round(10-charge/10)
cells = f'{loaded}{unloaded}'
status_info = 'Draining...'
charging = battery_info['IsCharging']
time_to_empty = battery_info['AvgTimeToEmpty']
time_to_full = battery_info['AvgTimeToFull']
time_left = 'Calculating…'
time_full = 'Calculating…'
fully_charged = battery_info['FullyCharged']
external = battery_info['ExternalConnected']
if time_to_empty < 15000:
time_left = f'{round(time_to_empty/60)}:{round(time_to_empty%60)}'
if time_to_full < 15000:
time_full = f'{round(time_to_full/60)}:{round(time_to_full%60)}'
if charging:
time_info = f'{time_full} until full'
status_info = 'Charging...'
battery_icon = ICON_CHARGING
else:
if fully_charged:
if external:
time_info = 'On AC power'
status_info = 'Fully Charged'
battery_icon = ICON_POWER
charge = '100'
cells = '●●●●●●●●●●'
else:
time_info = time_left
battery_icon = ICON_FULL
else:
time_info = time_left
battery_icon = ICON_CRITICAL
if charge > 80:
battery_icon = ICON_FULL
elif charge > 50:
battery_icon = ICON_MEDIUM
elif charge > 10:
battery_icon = ICON_LOW
temperature = round(battery_info['Temperature'] / 10 - 273, 2)
cycle_count = battery_info['CycleCount']
health = round(raw_max_capacity * 100 / design_capacity)
serial = battery_info['Serial']
self.wf.add_item(title=f'{charge}% {cells}',
subtitle=status_info,
valid=False,
icon=battery_icon
)
self.wf.add_item(title=time_info,
subtitle='Time Left',
valid=False,
icon=ICON_CLOCK
)
self.wf.add_item(title=f'{temperature} °C',
subtitle='Temperature',
valid=False,
icon=ICON_TEMP
)
self.wf.add_item(title=cycle_count,
subtitle='Charge Cycles Completed',
valid=False,
icon=ICON_CYCLES
)
self.wf.add_item(title=f'{health}%',
subtitle='Health',
valid=False,
icon=ICON_HEALTH
)
self.wf.add_item(title=serial,
subtitle='Serial',
valid=False,
icon=ICON_SERIAL
)
def run(self, wf):
"""Run the the main workflow logic
Args:
wf (Workflow): The Alfred-PyWorkflow instance
"""
self.wf = wf
# Needed as otherwise the magic arguments dont work e.g. the workflow:update
args = self.wf.args
# Notify user if update is available
# ------------------------------------------------------------------
if wf.update_available:
self.battery_info_check_update()
self.wf.add_item('Workflow Update is Available',
'↩ or ⇥ to install',
autocomplete='workflow:update',
valid=False,
icon=ICON_UPDATE)
valid, battery_info = self.get_battery_info()
if not valid:
self.show_error(battery_info)
else:
self.show_info(battery_info)
self.wf.send_feedback()
return 0
if __name__ == '__main__':
wf = Workflow(update_settings=UPDATE_SETTINGS,
help_url=HELP_URL)
log = wf.logger
batt = BatteryInfo()
sys.exit(wf.run(batt.run))