forked from actuallymentor/battery
-
-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathbattery.sh
executable file
·2848 lines (2467 loc) · 93.6 KB
/
battery.sh
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
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/bin/bash
## ###############
## Update management
## variables are used by this binary as well at the update script
## ###############
BATTERY_CLI_VERSION="v2.0.21"
BATTERY_VISUDO_VERSION="v1.0.2"
# Path fixes for unexpected environments
PATH=/opt/homebrew/bin:/opt/homebrew/sbin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin
## ###############
## Variables
## ###############
binfolder=/usr/local/bin
visudo_folder=/private/etc/sudoers.d
visudo_file=${visudo_folder}/battery
configfolder=$HOME/.battery
config_file=$configfolder/config_battery
pidfile=$configfolder/battery.pid
logfile=$configfolder/battery.log
pid_sig=$configfolder/sig.pid
daemon_path=$HOME/Library/LaunchAgents/battery.plist
calibrate_pidfile=$configfolder/calibrate.pid
schedule_path=$HOME/Library/LaunchAgents/battery_schedule.plist
shutdown_path=$HOME/Library/LaunchAgents/battery_shutdown.plist
daily_log=$configfolder/daily.log
calibrate_log=$configfolder/calibrate.log
github_link="https://raw.githubusercontent.com/js4jiang5/BatteryOptimizer_for_MAC/main"
## ###############
## 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
# CLI help message
helpmessage="
Battery CLI utility $BATTERY_CLI_VERSION
Usage:
battery maintain PERCENTAGE[10-100,stop,suspend,recover] SAILING_TARGET[5-99]
- PERCENTAGE is battery level upper bound above which charging is stopped
- SAILING_TARGET is battery level lower bound below which charging is started. default value is PERCENTAGE-5 if not specified
Examples:
battery maintain 80 50 # maintain at 80% with sailing to 50%
battery maintain 80 # equivalent to battery maintain 80 75
battery maintain stop # kill running battery maintain process, disable daemon, and enable charging. maintain will not run after reboot
battery maintain suspend # suspend running battery maintain process and enable charging. maintain is automatically resumed after AC adapter is reconnected. used for temporary charging to 100% before travel
battery maintain recover # recover battery maintain process
battery calibrate
calibrate the battery by discharging it to 15%, then recharging it to 100%, and keeping it there for 1 hour, then discharge to maintained percentage level
if macbook lid is not open or AC adapter is not connected, a remind notification will be received.
calibration will be started automatically once macbook lid is open and AC adapter is connected
notification will be received when each step is completed or error occurs till the end of calibration
if you prefer the notifications to stay on until you dismiss it, setup notifications as follows
system settings > notifications > applications > Script Editor > Choose "Alerts"
when external monitor is used, you must setup notifications as follows in order to receive notification successfully
system settings > notifications > check 'Allow notifications when mirroring or sharing the display'
eg: battery calibrate # start calibration
eg: battery calibrate stop # stop calibration and resume maintain
battery schedule
schedule periodic calibration at most 4 separate days per month, or specified weekday every 1~12 weeks, or specified one day every 1~3 month. default is one day per month on Day 1 at 9am.
Examples:
battery schedule # calibrate on Day 1 at 9am
battery schedule day 1 8 15 22 # calibrate on Day 1, 8, 15, 22 at 9am.
battery schedule day 3 18 hour 13 # calibrate on Day 3, 18 at 13:00
battery schedule day 6 16 26 hour 18 minute 30 # calibrate on Day 6, 16, 26 at 18:30
battery schedule weekday 0 week_period 2 hour 21 minute 30 # calibrate on Sunday every 2 weeks at 21:30
battery schedule day 5 month_period 3 hour 21 minute 30 # calibrate every 3 month on Day 5 at 21:00
battery schedule disable # disable periodic calibration
battery schedule enable # enable periodic calibration
Restrictions:
1. at most 4 days per month are allowed
2. valid day range [1-28]
3. valid hour range [0-23]
4. valid minute range [0-59]
5. valid weekday range [0-6] 0:Sunday, 1:Monday, ...
6. valid week_period range [1-12]
7. valid month_period range [1-3]
battery charge LEVEL[1-100, stop]
charge the battery to a certain percentage, and disable charging when that percentage is reached
eg: battery charge 90
eg: battery charge stop # kill running battery charge process and stop charging
battery discharge LEVEL[1-100, stop]
block power input from the adapter until battery falls to this level
eg: battery discharge 90
eg: battery discharge stop # kill running battery discharge process and stop discharging
battery status
output battery SMC status, capacity, temperature, health, and cycle count
battery dailylog
output daily log and show daily log store location
battery changelog
show the changelog of the latest version on Github
battery calibratelog
show calibrate history
battery logs LINES[integer, optional]
output logs of the battery CLI and GUI
eg: battery logs 100
battery language LANG[tw,us]
eg: battery language tw # show status and notification in traditional Chinese if available
eg: battery language us # show status and notification in English
battery update
update the battery utility to the latest version
battery version
show current 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
"
# Visudo instructions
visudoconfig="
# Visudo settings for the battery utility installed from https://github.com/js4jiang5/BatteryOptimizer_for_MAC
# intended to be placed in $visudo_file 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, $binfolder/smc -k CH0J -w 00, $binfolder/smc -k CH0J -r, $binfolder/smc -k CH0K -w 00, $binfolder/smc -k CH0K -r, $binfolder/smc -d off
Cmnd_Alias DISCHARGEON = $binfolder/smc -k CH0I -w 01, $binfolder/smc -k CH0J -w 01, $binfolder/smc -k CH0K -w 01, $binfolder/smc -d on
Cmnd_Alias LEDCONTROL = $binfolder/smc -k ACLC -w 04, $binfolder/smc -k ACLC -w 03, $binfolder/smc -k ACLC -w 02, $binfolder/smc -k ACLC -w 01, $binfolder/smc -k ACLC -w 00, $binfolder/smc -k ACLC -r
Cmnd_Alias BATTERYBCLM = $binfolder/smc -k BCLM -w 0a, $binfolder/smc -k BCLM -w 64, $binfolder/smc -k BCLM -r
Cmnd_Alias BATTERYCHWA = $binfolder/smc -k CHWA -w 00, $binfolder/smc -k CHWA -w 01, $binfolder/smc -k CHWA -r
Cmnd_Alias BATTERYACEN = $binfolder/smc -k ACEN -w 00, $binfolder/smc -k ACEN -w 01, $binfolder/smc -k ACEN -r
Cmnd_Alias BATTERYBFCL = $binfolder/smc -k BFCL -w 00, $binfolder/smc -k BFCL -w 5f, $binfolder/smc -k BFCL -r
Cmnd_Alias BATTERYCHBI = $binfolder/smc -k CHBI -r
Cmnd_Alias BATTERYB0AC = $binfolder/smc -k B0AC -r
ALL ALL = NOPASSWD: BATTERYOFF
ALL ALL = NOPASSWD: BATTERYON
ALL ALL = NOPASSWD: DISCHARGEOFF
ALL ALL = NOPASSWD: DISCHARGEON
ALL ALL = NOPASSWD: LEDCONTROL
ALL ALL = NOPASSWD: BATTERYBCLM
ALL ALL = NOPASSWD: BATTERYCHWA
ALL ALL = NOPASSWD: BATTERYACEN
ALL ALL = NOPASSWD: BATTERYBFCL
ALL ALL = NOPASSWD: BATTERYCHBI
ALL ALL = NOPASSWD: BATTERYB0AC
"
# Get parameters
battery_binary=$0
action=$1
setting=$2
subsetting=$3
thirdsetting=$4
# check the availability of SMC keys
[[ $(smc -k BCLM -r) =~ "no data" ]] && has_BCLM=false || has_BCLM=true;
[[ $(smc -k CH0B -r) =~ "no data" ]] && has_CH0B=false || has_CH0B=true;
[[ $(smc -k CH0C -r) =~ "no data" ]] && has_CH0C=false || has_CH0C=true;
[[ $(smc -k CH0I -r) =~ "no data" ]] && has_CH0I=false || has_CH0I=true;
[[ $(smc -k CH0J -r) =~ "no data" ]] && has_CH0J=false || has_CH0J=true;
[[ $(smc -k CH0K -r) =~ "no data" ]] && has_CH0K=false || has_CH0K=true;
[[ $(smc -k ACEN -r) =~ "no data" ]] && has_ACEN=false || has_ACEN=true;
[[ $(smc -k ACLC -r) =~ "no data" ]] && has_ACLC=false || has_ACLC=true;
[[ $(smc -k CHWA -r) =~ "no data" ]] && has_CHWA=false || has_CHWA=true;
[[ $(smc -k BFCL -r) =~ "no data" ]] && has_BFCL=false || has_BFCL=true;
[[ $(smc -k ACFP -r) =~ "no data" ]] && has_ACFP=false || has_ACFP=true;
## ###############
## Helpers
## ###############
function valid_action() {
local action=$1
# List of valid actions
VALID_ACTIONS=("" "visudo" "maintain" "calibrate" "schedule" "charge" "discharge"
"status" "dailylog" "calibratelog" "logs" "language" "update" "version" "reinstall" "uninstall"
"maintain_synchronous" "status_csv" "create_daemon" "disable_daemon" "remove_daemon" "changelog")
VALID_ACTIONS_USER=("" "visudo" "maintain" "calibrate" "schedule" "charge" "discharge"
"status" "dailylog" "calibratelog" "logs" "language" "update" "version" "reinstall" "uninstall" "changelog")
# Check if action is valid
local action_valid=false
for valid_action in "${VALID_ACTIONS[@]}"; do
if [[ "$action" == "$valid_action" ]]; then
action_valid=true
break
fi
done
if ! $action_valid; then
echo "Error: Unknown command '$action'"
# Find similar commands
echo "Did you mean one of these?"
for valid_action in "${VALID_ACTIONS_USER[@]}"; do
if [[ "$valid_action" == *"${action:0:3}"* ]]; then
echo " - $valid_action"
fi
done
echo "Run 'battery' without parameters, for list of valid commands."
return 1
fi
return 0
}
function ha_webhook() {
DST=http://homeassistant.local:8123
WEBHOOKID=$(read_config webhookid)
if [[ $WEBHOOKID ]]; then
if [ $4 ]; then
curl -sS -X POST \
-H "Content-Type: application/json"\
-d "{\"stage\": \"$1\" , \"battery\": \"$2\" , \"voltage\": \"$3\" , \"health\": \"$4\"}" \
$DST/api/webhook/$WEBHOOKID
elif [ $3 ]; then
curl -sS -X POST \
-H "Content-Type: application/json"\
-d "{\"stage\": \"$1\" , \"battery\": \"$2\" , \"voltage\": \"$3\"}" \
$DST/api/webhook/$WEBHOOKID
elif [ $2 ]; then
curl -sS -X POST \
-H "Content-Type: application/json"\
-d "{\"stage\": \"$1\" , \"battery\": \"$2\"}" \
$DST/api/webhook/$WEBHOOKID
else
curl -sS -X POST \
-H "Content-Type: application/json"\
-d "{\"stage\": \"$1\" }" \
$DST/api/webhook/$WEBHOOKID
fi
fi
}
function log() {
echo -e "$(date +%D-%T) - $1"
}
function logLF() {
echo -e "\n$(date +%D-%T) - $1"
}
function logn() {
echo -e -n "$(date +%D-%T) - $1"
}
function logd() {
echo -e "$(date +%Y/%m/%d) $1"
}
function valid_percentage() {
if ! [[ "$1" =~ ^[0-9]+$ ]] || [[ "$1" -lt 0 ]] || [[ "$1" -gt 100 ]]; then
return 1
else
return 0
fi
}
function valid_month_period() {
if ! [[ "$1" =~ ^[0-9]+$ ]] || [[ "$1" -lt 1 ]] || [[ "$1" -gt 3 ]]; then
return 1
else
return 0
fi
}
function valid_day() {
if ! [[ "$1" =~ ^[0-9]+$ ]] || [[ "$1" -lt 1 ]] || [[ "$1" -gt 28 ]]; then
return 1
else
return 0
fi
}
function valid_hour() {
if ! [[ "$1" =~ ^[0-9]+$ ]] || [[ "$1" -lt 0 ]] || [[ "$1" -gt 23 ]]; then
return 1
else
return 0
fi
}
function valid_minute() {
if ! [[ "$1" =~ ^[0-9]+$ ]] || [[ "$1" -lt 0 ]] || [[ "$1" -gt 59 ]]; then
return 1
else
return 0
fi
}
function valid_weekday() {
if ! [[ "$1" =~ ^[0-9]+$ ]] || [[ "$1" -lt 0 ]] || [[ "$1" -gt 6 ]]; then
return 1
else
return 0
fi
}
function valid_week_period() {
if ! [[ "$1" =~ ^[0-9]+$ ]] || [[ "$1" -lt 1 ]] || [[ "$1" -gt 12 ]]; then
return 1
else
return 0
fi
}
function format00() {
value=$1
if [ $value -lt 10 ]; then
value=0$(echo $value | tr -d '0')
if [ "$value" == "0" ]; then
value="00"
fi
fi
echo $value
}
function check_next_calibration_date() {
schedule=$(read_config calibrate_schedule)
if [[ -z $schedule ]]; then
echo 0
return
fi
LANG=en_us_8859_1
if [[ $schedule == *"every"* ]] && [[ $schedule == *"Week"* ]] && [[ $schedule == *"Year"* ]]; then
weekday=$(echo $schedule | awk '{print $4}')
week_period=$(echo $schedule | awk '{print $6}')
time=$(echo $schedule | awk '{print $9}')
week=$(echo $schedule | awk '{print $13}')
year=$(echo $schedule | awk '{print $16}')
hour=${time%:*}
minute=${time#*:}
if [[ $schedule =~ "MON" ]]; then weekday=1; elif
[[ $schedule =~ "TUE" ]]; then weekday=2; elif
[[ $schedule =~ "WED" ]]; then weekday=3; elif
[[ $schedule =~ "THU" ]]; then weekday=4; elif
[[ $schedule =~ "FRI" ]]; then weekday=5; elif
[[ $schedule =~ "SAT" ]]; then weekday=6; elif
[[ $schedule =~ "SUN" ]]; then weekday=7;
fi
start_sec="$(echo `date -j -f "%Y-%V-%u %H:%M:%S" "$year-$week-$weekday $hour:$minute:00" +%s`)"
if [[ $((10#$(date +%V))) -eq 1 ]]; then # Week 1 is special, need to check if it is valid
if [[ `date -v+7d +%Y` -gt `date +%Y` ]]; then # cross year for Week 1 if year is different after 7 days
schedule_sec="$(echo `date -j -f "%Y-%V-%u %H:%M:%S" "$(date +%Y)-$(($(date -v-7d +%V)+1))-$weekday $hour:$minute:00" +%s`)"
elif [[ $weekday -lt `date +%u` ]]; then # weekday is before today that might be invalid for Week 1
schedule_sec="$(echo `date -j -f "%Y-%V-%u %H:%M:%S" "$(date +%Y)-$(($(date +%V)+1))-$weekday $hour:$minute:00" +%s`)"
else
schedule_sec="$(echo `date -j -f "%Y-%V-%u %H:%M:%S" "$(date +%Y)-$(date +%V)-$weekday $hour:$minute:00" +%s`)"
fi
else
schedule_sec="$(echo `date -j -f "%Y-%V-%u %H:%M:%S" "$(date +%Y)-$(date +%V)-$weekday $hour:$minute:00" +%s`)"
fi
now=`date +%s`
for i in {0..12}; do # at most 12 weeks
schedule_diff_sec=$((schedule_sec - start_sec))
if [[ $((schedule_diff_sec % (week_period*7*24*60*60))) == 0 ]] && [[ $schedule_sec -gt $now ]]; then
next_s=$schedule_sec
break;
else
schedule_sec=$((schedule_sec+ (7*24*60*60)))
fi
done
#for i in {0..31} ; do
# schedule_diff_sec=$((schedule_sec + i*86400 -start_sec))
# now_diff_sec=$((schedule_sec + i*86400 -now))
# if [[ $((schedule_diff_sec % (week_period*7*24*60*60))) == 0 ]] && [[ $schedule_diff_sec -ge 0 ]] && [[ $now_diff_sec -gt 0 ]]; then
# calibrate_date="$(echo `date -v+${i}d +%Y/%m/%d`)";
# next_s=$((schedule_sec + i*86400))
# break
# fi
#done
else
n_days=0
days[0]=
days[1]=
days[2]=
days[3]=
schedule=${schedule/weekday}
day_loc=$(echo "$schedule" | tr " " "\n" | grep -n "day" | cut -d: -f1)
if [[ $day_loc ]]; then
for i_day in {1..4}; do
value=$(echo $schedule | awk '{print $"'"$((day_loc+i_day))"'"}')
if valid_day $value; then
days[$n_days]=$(format00 $value)
n_days=$(($n_days+1))
else
break
fi
done
fi
time=${schedule#*" at "}
time=${time%" starting"*}
hour=${time%:*}
minute=${time#*:}
month_loc=$(echo "$schedule" | tr " " "\n" | grep -n "Month" | cut -d: -f1)
if [[ $month_loc ]]; then
month=$(echo $schedule | awk '{print $"'"$((month_loc+1))"'"}');
month=$(format00 $month)
fi
year_loc=$(echo "$schedule" | tr " " "\n" | grep -n "Year" | cut -d: -f1)
if [[ $year_loc ]]; then
year=$(echo $schedule | awk '{print $"'"$((year_loc+1))"'"}');
fi
month_period_loc=$(echo "$schedule" | tr " " "\n" | grep -n "every" | cut -d: -f1)
if [[ $month_period_loc ]]; then
month_period=$(echo $schedule | awk '{print $"'"$((month_period_loc+1))"'"}');
month_diff=$(((`date +%Y` - $year)*12 + `date +%m` - $month))
else # calibrate every month case
month_period=1
month_diff=0
fi
now=`date +%s`
diff_min=$((86400*100)) # need to find the min in case users put larger day in front
for i_month in {0..3}; do # at most 3 months
if [[ $((($month_diff + $i_month) % $month_period)) -eq 0 ]]; then
for i_day in $(seq 0 $((n_days-1))); do # check this month
if [[ $((`date +%m` + i_month)) -gt 12 ]]; then # cross year
year=$(date -v+1y +%Y)
else
year=$(date +%Y)
fi
#echo "$year $(date -v+${i_month}m +%m) ${days[$i_day]}"
schedule_sec="$(echo `date -j -f "%Y-%m-%d %H:%M:%S" "$year-$(date -v+${i_month}m +%m)-${days[$i_day]} $hour:$minute:00" +%s`)"
diff=$((schedule_sec - now))
#echo "$diff $diff_min"
if [[ $diff -gt 0 ]] && [[ $diff -lt $diff_min ]]; then
next_s=$schedule_sec
diff_min=$diff
#echo "diff_min = $diff_min"
fi
done
fi
done
fi
echo $next_s
}
function show_schedule() {
# check if schedule is enabled
enable_exist="$(launchctl print gui/$(id -u $USER) | grep "=> enabled")"
if [[ $enable_exist ]]; then # new version that replace => false with => enabled
schedule_enabled="$(launchctl print gui/$(id -u $USER) | grep enabled | grep "com.battery_schedule.app")"
else # old version that use => false
schedule_enabled="$(launchctl print gui/$(id -u $USER) | grep "=> false" | grep "com.battery_schedule.app")"
schedule_enabled=${schedule_enabled/false/enabled}
fi
schedule_txt="$(read_config calibrate_schedule)"
if [[ $schedule_enabled =~ "enabled" ]]; then
if [[ $schedule_txt ]]; then
if $is_TW; then
if ! [[ $schedule_txt =~ "week" ]]; then
if ! [[ $schedule_txt =~ "month" ]]; then
schedule_txt=${schedule_txt/"Schedule calibration on day"/"電池自動校正時程安排在"}
schedule_txt=${schedule_txt/"at"/"日"}
else
schedule_txt=${schedule_txt/"Schedule calibration on day"/"電池自動校正時程安排在"}
schedule_txt=${schedule_txt/"every "/"日每"}
schedule_txt=${schedule_txt/"month at"/"個月"}
schedule_txt=${schedule_txt%" starting"*}
fi
else
schedule_txt=${schedule_txt/"Schedule calibration on"/"電池自動校正時程安排在"}
schedule_txt=${schedule_txt/"SUN"/"星期日"}
schedule_txt=${schedule_txt/"MON"/"星期一"}
schedule_txt=${schedule_txt/"TUE"/"星期二"}
schedule_txt=${schedule_txt/"WED"/"星期三"}
schedule_txt=${schedule_txt/"THU"/"星期四"}
schedule_txt=${schedule_txt/"FRI"/"星期五"}
schedule_txt=${schedule_txt/"SAT"/"星期六"}
schedule_txt=${schedule_txt/"every "/"每"}
schedule_txt=${schedule_txt/"week at"/"週"}
schedule_txt=${schedule_txt%" starting"*}
fi
log "$schedule_txt 開始"
#check_next_calibration_date
log "下次校正日期是 `date -j -f "%s" "$(echo $(check_next_calibration_date) | awk '{print $NF}')" +%Y/%m/%d`"
else
schedule_txt=${schedule_txt%" starting"*}
log "$schedule_txt"
log "Next calibration date is `date -j -f "%s" "$(echo $(check_next_calibration_date) | awk '{print $NF}')" +%Y/%m/%d`"
fi
else
if $is_TW; then
log "您尚未設定電池自動校正時程"
else
log "You haven't scheduled calibration yet"
fi
fi
else
if [[ $schedule_txt ]]; then
if $is_TW; then
log "您的電池自動校正時程已暫停,要恢復請執行"
else
log "Your calibration schedule is disabled. Enable it by"
fi
log "battery schedule enable"
else
if $is_TW; then
log "您尚未設定電池自動校正時程"
else
log "You haven't scheduled calibration yet"
fi
fi
fi
}
## #################
## SMC Manipulation
## #################
# Change magsafe color
# see community sleuthing: https://github.com/actuallymentor/battery/issues/71
function change_magsafe_led_color() {
color=$1
if [[ "$color" == "auto" ]]; then
charging_status=$(get_charging_status)
if $has_ACLC; then
color=$(read_smc_hex ACLC);
if [ "$charging_status" == "1" ] && [ "$color" != "04" ] ; then # orange for charging
color="orange"
elif [ "$charging_status" == "0" ] && [ "$color" != "03" ] ; then # green for not charging
color="green"
elif [ "$charging_status" == "2" ] && [ "$color" != "01" ] ; then # none for discharging
color="none"
else
return 0
fi
elif $has_BFCL; then
color=$(read_smc_hex BFCL);
if [ "$charging_status" == "1" ] && [ "$color" != "5f" ] ; then # orange for charging
color="orange"
elif [ "$charging_status" == "0" ] && [ "$color" != "00" ] ; then # green for not charging
color="green"
else
return 0
fi
else
return 0
fi
fi
if $has_ACLC || $has_BFCL; then
#log "MagSafe LED function invoked"
log "💡 Setting magsafe color to $color"
else
return 0
fi
if [[ "$color" == "green" ]]; then
#log "setting LED to green"
if $has_ACLC; then sudo smc -k ACLC -w 03; fi
if $has_BFCL; then sudo smc -k BFCL -w 00; fi
elif [[ "$color" == "orange" ]]; then
#log "setting LED to orange"
if $has_ACLC; then sudo smc -k ACLC -w 04; fi
if $has_BFCL; then sudo smc -k BFCL -w 5f; fi
elif [[ "$color" == "none" ]]; then
#log "setting LED to none"
if $has_ACLC; then sudo smc -k ACLC -w 01; fi
if $has_BFCL; then sudo smc -k BFCL -w 5f; fi
else
# Default action: reset. Value 00 is a guess and needs confirmation
#log "resetting LED"
if $has_ACLC; then sudo smc -k ACLC -w 00; fi
if $has_BFCL; then sudo smc -k BFCL -w 00; fi
fi
}
# 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
function enable_discharging() {
disable_charging
log "🔽🪫 Enabling battery discharging"
if [[ $(get_cpu_type) == "apple" ]]; then
if $has_CH0I; then sudo smc -k CH0I -w 01; fi
if $has_ACLC; then sudo smc -k ACLC -w 01; fi
else
if $has_BCLM; then sudo smc -k BCLM -w 0a; fi
if $has_ACEN; then sudo smc -k ACEN -w 00; fi
fi
sleep 1
}
function disable_discharging() {
log "🔼🪫 Disabling battery discharging"
if [[ $(get_cpu_type) == "apple" ]]; then
if $has_CH0I; then sudo smc -k CH0I -w 00; fi
else
if $has_ACEN; then sudo smc -k ACEN -w 01; fi
fi
sleep 1
## Keep track of status
#is_charging=$(get_smc_charging_status)
#if ! valid_percentage "$setting"; then
# log "Disabling discharging: No valid maintain percentage set, enabling charging"
# # use direct commands since enable_charging also calls disable_discharging, and causes an eternal loop
# sudo smc -k CH0B -w 00
# sudo smc -k CH0C -w 00
# change_magsafe_led_color "orange"
#elif [[ "$battery_percentage" -ge "$setting" && "$is_charging" == "enabled" ]]; then
# log "Disabling charging: Stop charge above $setting, disabling charging"
# disable_charging
# change_magsafe_led_color "green"
#elif [[ "$battery_percentage" -lt "$setting" && "$is_charging" == "disabled" ]]; then
# log "Disabling discharging: Charge below $setting, enabling charging"
# # use direct commands since enable_charging also calls disable_discharging, and causes an eternal loop
# sudo smc -k CH0B -w 00
# sudo smc -k CH0C -w 00
# change_magsafe_led_color "orange"
#fi
}
# 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
function enable_charging() {
disable_discharging
log "🔌🔋 Enabling battery charging"
if [[ $(get_cpu_type) == "apple" ]]; then
if $has_CH0B; then sudo smc -k CH0B -w 00; fi
if $has_CH0C; then sudo smc -k CH0C -w 00; fi
else
if $has_BCLM; then sudo smc -k BCLM -w 64; fi
fi
sleep 1
}
function disable_charging() {
log "🔌🪫 Disabling battery charging"
if [[ $(get_cpu_type) == "apple" ]]; then
if $has_CH0B; then sudo smc -k CH0B -w 02; fi
if $has_CH0C; then sudo smc -k CH0C -w 02; fi
else
if $has_BCLM; then sudo smc -k BCLM -w 0a; fi
fi
sleep 1
}
function get_smc_charging_status() {
if [[ $(get_cpu_type) == "apple" ]]; then
hex_status=$(read_smc_hex CH0C)
if [[ "$hex_status" == "00" ]]; then
echo "enabled"
else
echo "disabled"
fi
else
bclm_hex_status=$(read_smc_hex BCLM)
acen_hex_status=$(read_smc_hex ACEN)
if [[ "$bclm_hex_status" == "64" ]] && [[ "$acen_hex_status" == "01" ]]; then
echo "enabled"
else
echo "disabled"
fi
fi
}
function get_smc_discharging_status() {
if [[ $(get_cpu_type) == "apple" ]]; then
hex_status=$(read_smc_hex CH0I)
if [[ "$hex_status" == "00" ]]; then
echo "not discharging"
else
echo "discharging"
fi
else
acen_hex_status=$(read_smc_hex ACEN)
if [[ "$acen_hex_status" == "01" ]]; then
echo "not discharging"
else
echo "discharging"
fi
fi
}
## ###############
## Statistics
## ###############
function get_battery_percentage() {
battery_percentage=$(read_smc BRSC)
if [ $battery_percentage -gt 100 ]; then
battery_percentage=$((battery_percentage/256)) # BRSC is battery_level in some system, but bettery_level in others
fi
echo $battery_percentage
}
function get_accurate_battery_percentage() {
MaxCapacity=$(ioreg -l -n AppleSmartBattery -r | grep "\"AppleRawMaxCapacity\" =" | awk '{ print $3 }' | tr ',' '.')
CurrentCapacity=$(ioreg -l -n AppleSmartBattery -r | grep "\"AppleRawCurrentCapacity\" =" | awk '{ print $3 }' | tr ',' '.')
accurate_battery_percentage=$(echo "scale=1; $CurrentCapacity*100/$MaxCapacity" | bc)
echo $accurate_battery_percentage
}
function get_remaining_time() {
time_remaining=$(pmset -g batt | tail -n1 | awk '{print $5}')
echo "$time_remaining"
}
function get_charger_state() {
ac_attached=$(pmset -g batt | tail -n1 | awk '{ x=match($0, /AC attached/) > 0; print x }')
echo "$ac_attached"
}
function get_charging_status() {
#if [[ $(get_cpu_type) == "apple" ]]; then
# is_charging=$(pmset -g batt | tail -n1 | awk '{ x=match($0, /; charging;/) > 0; print x }')
# is_discharging=$(pmset -g batt | tail -n1 | awk '{ x=match($0, /; discharging;/) > 0; print x }')
#else
charge_current=$(read_smc CHBI)
discharge_current=$(read_smc B0AC)
if [[ $charge_current == "0" ]]; then
is_charging=0
else
is_charging=1
fi
if [[ $discharge_current == "0" ]]; then
is_discharging=0
else
is_discharging=1
fi
#fi
if [ "$is_charging" == "1" ]; then # charging
echo "1"
elif [ "$is_discharging" == "1" ]; then # discharging
echo "2"
else # not charging
echo "0"
fi
}
function get_maintain_percentage() {
maintain_percentage=$(read_config maintain_percentage)
echo "$maintain_percentage" | awk '{print $1}'
}
function get_voltage() {
voltage=$(ioreg -l -n AppleSmartBattery -r | grep "\"Voltage\" =" | awk '{ print $3/1000 }' | tr ',' '.')
echo "$voltage"
}
function get_battery_health() {
MaxCapacity=$(ioreg -l -n AppleSmartBattery -r | grep "\"AppleRawMaxCapacity\" =" | awk '{ print $3 }' | tr ',' '.')
DesignCapacity=$(ioreg -l -n AppleSmartBattery -r | grep "\"DesignCapacity\" =" | awk '{ print $3 }' | tr ',' '.')
health=$(echo "scale=1; $MaxCapacity*100/$DesignCapacity" | bc)
echo $health
}
function get_battery_temperature() {
temperature=$(ioreg -l -n AppleSmartBattery -r | grep "\"VirtualTemperature\" =" | awk '{ print $3 }' | tr ',' '.')
if [ $temperature ]; then
temperature=$(echo "scale=1; ($temperature+5)/100" | bc)
else
#temperature=$(ioreg -l -n AppleSmartBattery -r | grep "\"Temperature\" =" | awk '{ print $3 }' | tr ',' '.')
#temperature=$(echo "scale=1; ($temperature+5)/100" | bc)
temperature=$(echo $(smc -k TB0T -r) | awk '{print $3}') # this value is closer to coconutBattery and AlDente
temperature=$(echo "scale=1; ($temperature*1000+50)/1000" | bc)
fi
echo $temperature
}
function get_cycle() {
cycle=$(ioreg -l -n AppleSmartBattery -r | grep "\"CycleCount\" =" | awk '{ print $3 }' | tr ',' '.')
echo "$cycle"
}
function get_charger_connection() { # 20241013 by JS
# AC is consider connected if battery is not discharging
ac_attached=$(pmset -g batt | head -n1 | awk '{ x=match($0, /AC Power/) > 0; print x }')
discharge_current=$(read_smc B0AC)
if $has_ACFP; then
acfp=$(read_smc ACFP)
else
acfp=0
fi
if [[ $discharge_current == "0" ]]; then
not_discharging=1
else
not_discharging=0
fi
ac_connected=$(($ac_attached || $not_discharging || $acfp > 0 ))
echo "$ac_connected"
}
function get_cpu_type() {
if [[ $(smc -k BCLM -r) == *"no data"* ]]; then
echo "apple"
else
echo "intel"
fi
#if [[ $(sysctl -n machdep.cpu.brand_string) == *"Intel"* ]]; then
# echo "intel"
#else
# echo "apple"
#fi
}
function get_parameter() { # get parameter value from configuration file. the format is var=value or var= value or var = value
var_loc=$(echo $(echo "$1" | tr " " "\n" | grep -n "$2" | cut -d: -f1) | awk '{print $1}')
if [ -z $var_loc ]; then
echo
else
echo $1 | awk '{print $"'"$((var_loc))"'"}' | tr '=' ' ' | awk '{print $2}'
fi
}
function get_changelog() { # get the latest changelog
if [[ -z $1 ]]; then
changelog=$(curl -sSL $github_link/CHANGELOG | sed s:\":'\\"':g 2>&1)
else
changelog=$(curl -sSL $github_link/$1 | sed s:\":'\\"':g 2>&1)
fi
n_lines=0
while read -r "line"; do
line="v${line#*v}" # remove any words before v
num=$(echo $line | tr '.' ' '| tr 'v' ' ') # extract number parts
is_version=true
n_num=0
for var in $num; do
if ! [[ "$var" =~ ^[0-9]+$ ]]; then
is_version=false
break
else
n_num=$((n_num+1))
fi
done
if [[ $line =~ "." ]] && [[ $line =~ "v" ]] && $is_version && [[ $n_num -eq 3 ]] && [[ $n_lines -gt 0 ]]; then
is_version=true
else
is_version=false
fi
if $is_version; then # found the start of 2nd version
break
fi
n_lines=$((n_lines+1))
done <<< "$changelog"
echo -e "$changelog" | awk 'NR>=2 && NR<='$n_lines
}
function get_version() { # get the latest version number
if [[ -z $1 ]]; then
changelog=$(curl -sSL $github_link/CHANGELOG | sed s:\":'\\"':g 2>&1)
else
changelog=$(curl -sSL $github_link/$1 | sed s:\":'\\"':g 2>&1)
fi
while read -r "line"; do
break
done <<< "$changelog"
echo $line
}
function lid_closed() { # 20241013 by JS
lid_is_closed=$(ioreg -r -k AppleClamshellState -d 1 | grep AppleClamshellState | tail -n1 | awk '{print $3}')
echo "$lid_is_closed"
}
function confirm_SIG() {
ack_received=1
break
echo
}
function ack_SIG() {
sigpid=$(echo $(cat "$pid_sig" 2>/dev/null) | awk '{print $1}')
sig=$(echo $(cat "$pid_sig" 2>/dev/null) | awk '{print $2}')
if [ "$sig" == "suspend" ]; then # if suspend is called by user, enable charging to 100%
maintain_status="suspended"
enable_charging
log 'ack battery maintain suspend' # send ack
elif [ "$sig" == "suspend_no_charging" ]; then # if suspend is called by another battery process, let that process handle charging
maintain_status="suspended"
log 'ack battery maintain suspend' # send ack
elif [ "$sig" == "recover" ]; then
maintain_status="active"
disable_discharging
log 'ack battery maintain recover' # send ack
fi
kill -s USR1 $sigpid 2> /dev/null;
}
function calibrate_interrupted() {
rm $calibrate_pidfile 2>/dev/null
if [[ "$(maintain_is_running)" == "1" ]] && [[ "$(echo $(cat "$pidfile" 2>/dev/null) | awk '{print $2}')" == "suspended" ]]; then
$battery_binary maintain recover
fi
#kill 0 # kill all child processes
for pid in $pid_child; do
kill -s USR1 $pid
done
exit 1
}
function charge_interrupted() {
disable_charging
if [[ "$(maintain_is_running)" == "1" ]] && [[ "$(echo $(cat "$pidfile" 2>/dev/null) | awk '{print $2}')" == "suspended" ]] && [[ "$original_maintain_status" == "active" ]]; then
$battery_binary maintain recover
fi
exit 1
}
function charge_terminated() { # terminated by another battery process, no need to handle maintain process
disable_charging
exit 1
}
function discharge_interrupted() {
disable_discharging
if [[ "$(maintain_is_running)" == "1" ]] && [[ "$(echo $(cat "$pidfile" 2>/dev/null) | awk '{print $2}')" == "suspended" ]] && [[ "$original_maintain_status" == "active" ]]; then
$battery_binary maintain recover
fi
exit 1
}
function discharge_terminated() { # terminated by another battery process, no need to handle maintain process
disable_discharging
exit 1
}
function maintain_is_running() {
# check if battery maintain is running
if test -f "$pidfile"; then # if maintain is ongoing
local pid=$(cat "$pidfile" 2>/dev/null | awk '{print $1}')
#n_pid=$(pgrep -f $battery_binary | awk 'END{print NR}')
#pid_found=0
#for ((i = 1; i <= n_pid; i++)); do
# pid_running=$(pgrep -f $battery_binary | head -n$i | tail -n1 | awk '{print $1}')
# if [ "$pid" == "$pid_running" ]; then # battery maintain is running
# pid_found=1
# break
# fi
#done
local pid_found=false
local pids=$(ps x | grep battery | awk '{print $1}')
for pid_running in $pids; do
if [ "$pid" == "$pid_running" ]; then # battery maintain is running
pid_found=true
break
fi
done
if $pid_found; then
echo 1
else
echo 0
fi
else
echo 0
fi
}
function calibrate_is_running() {