forked from actuallymentor/battery
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbattery-cli
executable file
·547 lines (413 loc) · 13.9 KB
/
battery-cli
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
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
#!/usr/bin/env bash
# Use `env` for use the first bash found in PATH, maybe the user has a newer version installed
## ###############
## Update management
## variables are used by this binary as well at the update script
## ###############
readonly BATTERY_CLI_VERSION="v1.0.0"
# Path fixes for unexpected environments
PATH=/bin:/usr/bin:/usr/local/bin:/usr/sbin:/opt/homebrew/bin
## ###############
## Variables
## ###############
battery_exec=$(which battery)
binfolder=$(dirname $battery_exec)
visudo_path=/private/etc/sudoers.d/battery_cli
configfolder=$HOME/.config/battery_cli
pidfile=$configfolder/battery_cli.pid
logfile=$configfolder/battery_cli.log
maintain_percentage_tracker_file=$configfolder/maintain.percentage
daemon_path=$HOME/Library/LaunchAgents/battery_cli.plist
## ###############
## Housekeeping
## ###############
# Create config folder if needed
mkdir -p $configfolder
# create logfile if needed
touch $logfile
# Trim logfile if needed
logsize=$(stat -f%z "$logfile")
max_logsize_bytes=5000000
if (( logsize > max_logsize_bytes )); then
tail -n 100 $logfile > $logfile
fi
# TODO: add check for homebrew installation
# check brew installation or standalone
# extended_help_message=""
# [[ $dirname -eq "/usr/local/bin" ]] && extended_help_message="
# "
# Get parameters
action=$1
setting=$2
## ###############
## Helpers
## ###############
get_visudo_privileges() {
# Visudo instructions
visudoconfig="
# Visudo settings for the battery utility installed from https://github.com/kevinm6/battery-cli
# intended to be placed in $visudo_path on a mac
Cmnd_Alias BATTERYOFF = $binfolder/smc -k CH0B -w 02, $binfolder/smc -k CH0C -w 02, $binfolder/smc -k CH0B -r, $binfolder/smc -k CH0C -r
Cmnd_Alias BATTERYON = $binfolder/smc -k CH0B -w 00, $binfolder/smc -k CH0C -w 00
Cmnd_Alias DISCHARGEOFF = $binfolder/smc -k CH0I -w 00, $binfolder/smc -k CH0I -r
Cmnd_Alias DISCHARGEON = $binfolder/smc -k CH0I -w 01
ALL ALL = NOPASSWD: BATTERYOFF
ALL ALL = NOPASSWD: BATTERYON
ALL ALL = NOPASSWD: DISCHARGEOFF
ALL ALL = NOPASSWD: DISCHARGEON
"
echo -e "$visudoconfig" >> $configfolder/visudo.tmp
sudo visudo -c -f $configfolder/visudo.tmp &> /dev/null
if [ "$?" -eq "0" ]; then
sudo cp $configfolder/visudo.tmp $visudo_path
rm $configfolder/visudo.tmp
fi
sudo chmod 440 $visudo_path
}
log() {
echo -e "$(date +%D-%T) - $1"
}
## ###############
## Statistics
## ###############
# Re:discharging, we're using keys uncovered by @howie65: https://github.com/actuallymentor/battery/issues/20#issuecomment-1364540704
# CH0I seems to be the "disable the adapter" key
enable_discharging() {
log "🔽🪫 Enabling battery discharging"
sudo smc -k CH0I -w 01
}
disable_discharging() {
log "🔼🪫 Disabling battery discharging"
sudo smc -k CH0I -w 00
}
# Re:charging, Aldente uses CH0B https://github.com/davidwernhart/AlDente/blob/0abfeafbd2232d16116c0fe5a6fbd0acb6f9826b/AlDente/Helper.swift#L227
# but @joelucid uses CH0C https://github.com/davidwernhart/AlDente/issues/52#issuecomment-1019933570
# so I'm using both since with only CH0B I noticed sometimes during sleep it does trigger charging
enable_charging() {
log "🔌🔋 Enabling battery charging"
sudo smc -k CH0B -w 00
sudo smc -k CH0C -w 00
disable_discharging
}
disable_charging() {
log "🔌🪫 Disabling battery charging"
sudo smc -k CH0B -w 02
sudo smc -k CH0C -w 02
}
get_smc_charging_status() {
hex_status=$( smc -k CH0B -r | awk '{print $4}' | sed s:\):: )
if [[ "$hex_status" == "00" ]]; then
echo "enabled"
else
echo "disabled"
fi
}
get_smc_discharging_status() {
hex_status=$( smc -k CH0I -r | awk '{print $4}' | sed s:\):: )
if [[ "$hex_status" == "0" ]]; then
echo "not discharging"
else
echo "discharging"
fi
}
get_battery_percentage() {
battery_percentage=`pmset -g batt | tail -n1 | awk '{print $3}' | sed s:\%\;::`
echo "$battery_percentage"
}
get_remaining_time() {
time_remaining=`pmset -g batt | tail -n1 | awk '{print $5}'`
echo "$time_remaining"
}
get_maintain_percentage() {
maintain_percentage=$( cat $maintain_percentage_tracker_file 2> /dev/null )
echo "$maintain_percentage"
}
# CLI help message
get_help_message() {
helpmessage="
Battery CLI utility $BATTERY_CLI_VERSION
Usage:
battery status
output battery SMC status, % and time remaining
battery log LINES[integer, optional]
output logs of the battery CLI and GUI
eg: battery logs 100
battery maintain LEVEL[1-100,stop]
reboot-persistent battery level maintenance: turn off charging above, and on below a certain value
eg: battery maintain 80
eg: battery maintain stop
battery charging SETTING[on/off]
manually set the battery to (not) charge
eg: battery charging on
battery adapter SETTING[on/off]
manually set the adapter to (not) charge even when plugged in
eg: battery adapter off
battery charge LEVEL[1-100]
charge the battery to LEVEL percentage, and disable charging when that percentage is reached
eg: battery charge 90
battery discharge LEVEL[1-100]
block power input from the adapter until battery falls to this level
eg: battery discharge 90
battery visudo
ensure you don't need to call battery with sudo
This is already used in the setup script and in brew installation, so you should't need it.
The following are only for installation without Homebrew, DON'T USE them if you installed
battery-cli with homebrew ( brew install battery-cli ):
battery update
update the battery utility to the latest version
battery reinstall
reinstall the battery utility to the latest version (reruns the installation script)
battery uninstall
enable charging, remove the smc tool, and the battery script
"
echo -e "$helpmessage"
}
# manage first run
[ ! -f $visudo_path ] && get_visudo_privileges
## ###############
## Actions
## ###############
case "$action" in
# Help message
"")
get_help_message
exit 0
;;
# Visudo message
"visudo")
get_visudo_privileges
exit 0
;;
# Reinstall helper
"reinstall")
echo "This will run curl -sS https://raw.githubusercontent.com/kevinm6/battery-cli/main/setup.sh | bash"
if [[ ! "$setting" == "silent" ]]; then
echo "Press any key to continue"
read
fi
curl -sS https://raw.githubusercontent.com/kevinm6/battery-cli/main/setup.sh | bash
exit 0
;;
# Update helper
"update")
# Check if we have the most recent version
if curl -sS https://raw.githubusercontent.com/kevinm6/battery-cli/main/battery.sh | grep -q "$BATTERY_CLI_VERSION"; then
echo "No need to update, offline version number matches remote version number"
else
echo "This will run curl -sS https://raw.githubusercontent.com/kevinm6/battery-cli/main/update.sh | bash"
if [[ ! "$setting" == "silent" ]]; then
echo "Press any key to continue"
read
fi
curl -sS https://raw.githubusercontent.com/kevinm6/battery-cli/main/update.sh | bash
fi
exit 0
;;
# Uninstall helper
"uninstall")
if [[ ! "$setting" == "silent" ]]; then
echo "This will enable charging, and remove the smc tool and battery script"
echo "Press any key to continue"
read
fi
enable_charging
disable_discharging
battery remove_daemon
sudo rm -v "$binfolder/smc" "$binfolder/battery"
pkill -f $battery_exec
exit 0
;;
# Charging on/off controller
"charging")
log "Setting $action to $setting"
# Disable running daemon
battery maintain stop
# Set charging to on and off
[[ "$setting" == "on" ]] && enable_charging ||
[[ "$setting" == "off" ]] && disable_charging
exit 0
;;
# Discharge on/off controller
"adapter")
log "Setting $action to $setting"
# Disable running daemon
battery maintain stop
# Set charging to on and off
[[ "$setting" == "on" ]] && enable_charging ||
[[ "$setting" == "off" ]] && disable_charging
exit 0
;;
# Charging on/off controller
"charge")
# Disable running daemon
battery maintain stop
# Disable charge blocker if enabled
battery adapter on
# Start charging
battery_percentage=$( get_battery_percentage )
log "Charging to $setting% from $battery_percentage%"
enable_charging
# Loop until battery percent is exceeded
while [[ "$battery_percentage" -lt "$setting" ]]; do
log "Battery at $battery_percentage%"
caffeinate -is sleep 60
battery_percentage=$( get_battery_percentage )
done
disable_charging
log "Charging completed at $battery_percentage%"
exit 0
;;
# Discharging on/off controller
"discharge")
# Start charging
battery_percentage=$( get_battery_percentage )
log "Discharging to $setting% from $battery_percentage%"
enable_discharging
# Loop until battery percent is exceeded
while [[ "$battery_percentage" -gt "$setting" ]]; do
log "Battery at $battery_percentage% (target $setting%)"
caffeinate -is sleep 60
battery_percentage=$( get_battery_percentage )
done
disable_discharging
log "Discharging completed at $battery_percentage%"
;;
# Maintain at level
"maintain_synchronous")
# Recover old maintain status if old setting is found
if [[ "$setting" == "recover" ]]; then
# Before doing anything, log out environment details as a debugging trail
log "Debug trail. User: $USER, config folder: $configfolder, logfile: $logfile, file called with 1: $1, 2: $2"
maintain_percentage=$( cat $maintain_percentage_tracker_file 2> /dev/null )
if [[ $maintain_percentage ]]; then
log "Recovering maintenance percentage $maintain_percentage"
setting=$( echo $maintain_percentage)
else
log "No setting to recover, exiting"
exit 0
fi
fi
# Before we start maintaining the battery level, first discharge to the target level
log "Triggering discharge to $setting before enabling charging limiter"
battery discharge "$setting"
log "Discharge pre battery-maintenance complete, continuing to battery maintenance loop"
# Start charging
battery_percentage=$( get_battery_percentage )
log "Charging to and maintaining at $setting% from $battery_percentage%"
# Loop until battery percent is exceeded
while true; do
# Keep track of status
is_charging=$( get_smc_charging_status )
if [[ "$battery_percentage" -ge "$setting" && "$is_charging" == "enabled" ]]; then
log "Charge above $setting"
disable_charging
elif [[ "$battery_percentage" -lt "$setting" && "$is_charging" == "disabled" ]]; then
log "Charge below $setting"
enable_charging
fi
sleep 60
battery_percentage=$( get_battery_percentage )
done
exit 0
;;
# Asynchronous battery level maintenance
"maintain")
# Kill old process silently
if test -f "$pidfile"; then
pid=$( cat "$pidfile" 2> /dev/null )
kill $pid &> /dev/null
fi
if [[ "$setting" == "stop" ]]; then
log "Killing running maintain daemons & enabling charging as default state"
rm $pidfile 2> /dev/null
rm $maintain_percentage_tracker_file 2> /dev/null
battery remove_daemon
enable_charging
battery status
exit 0
fi
if ! [[ "$setting" =~ ^-?[0-9]+$ ]]; then
echo -e "Error: $setting is not a valid setting for battery maintain. Perhaps you meant 'stop'?"
exit 1
fi
if ! [[ "$setting" =~ ^[0-9]+$ ]] || [[ "$setting" -lt 0 ]] || [[ "$setting" -gt 100 ]]; then
echo -e "Error: $setting is not a valid setting for battery maintain. Please use a number between 0 and 100"
exit 1
fi
# Start maintenance script
log "Starting battery maintenance at $setting%"
nohup battery maintain_synchronous $setting >> $logfile &
# Store pid of maintenance process and setting
echo $! > $pidfile
pid=$( cat "$pidfile" 2> /dev/null )
echo $setting > $maintain_percentage_tracker_file
log "Maintaining battery at $setting%"
# Enable the daemon that continues maintaining after reboot
battery create_daemon
exit 0
;;
# Status logger
"status")
log "Battery at $( get_battery_percentage )% ($( get_remaining_time ) remaining), smc charging $( get_smc_charging_status )"
if test -f $pidfile; then
maintain_percentage=$( cat $maintain_percentage_tracker_file 2> /dev/null )
log "Your battery is currently being maintained at $maintain_percentage%"
fi
exit 0
;;
# Status logger in csv format
"status_csv")
echo "$( get_battery_percentage ),$( get_remaining_time ),$( get_smc_charging_status ),$( get_smc_discharging_status ),$( get_maintain_percentage )"
;;
# launchd daemon creator, inspiration: https://www.launchd.info/
"create_daemon")
daemon_definition="
<?xml version=\"1.0\" encoding=\"UTF-8\"?>
<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">
<plist version=\"1.0\">
<dict>
<key>Label</key>
<string>com.battery_cli</string>
<key>ProgramArguments</key>
<array>
<string>$binfolder/battery</string>
<string>maintain_synchronous</string>
<string>recover</string>
</array>
<key>StandardOutPath</key>
<string>$logfile</string>
<key>StandardErrorPath</key>
<string>$logfile</string>
<key>RunAtLoad</key>
<true/>
</dict>
</plist>
"
mkdir -p "${daemon_path%/*}"
echo "$daemon_definition" > "$daemon_path"
exit 0
;;
# Remove daemon
"remove_daemon")
rm $daemon_path 2> /dev/null
exit 0
;;
# Display logs
"log")
amount="${2:-100}"
echo -e "👾 Battery CLI logs:\n"
tail -n $amount $logfile
echo -e "\n🖥️ Battery GUI logs:\n"
tail -n $amount "$configfolder/gui.log"
echo -e "\n📁 Config folder details:\n"
ls -lah $configfolder
echo -e "\n⚙️ Battery data:\n"
battery status
battery | grep -E "v\d.*"
exit 0
;;
*) # fallback
get_help_message
exit 0
;;
esac