-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathcmd.go
606 lines (504 loc) · 18.2 KB
/
cmd.go
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
package main
import (
"encoding/json"
"fmt"
"strconv"
"github.com/distatus/battery"
"github.com/fatih/color"
"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"github.com/charlie0129/batt/pkg/version"
)
var (
logLevel = "info"
)
var (
gBasic = "Basic:"
gAdvanced = "Advanced:"
gInstallation = "Installation:"
commandGroups = []string{
gBasic,
gAdvanced,
}
)
// NewCommand .
func NewCommand() *cobra.Command {
cmd := &cobra.Command{
Use: "batt",
Short: "batt is a tool to control battery charging on Apple Silicon MacBooks",
Long: `batt is a tool to control battery charging on Apple Silicon MacBooks.
Website: https://github.com/charlie0129/batt`,
SilenceUsage: true,
PersistentPreRunE: func(_ *cobra.Command, _ []string) error {
return setupLogger()
},
}
globalFlags := cmd.PersistentFlags()
globalFlags.StringVarP(&logLevel, "log-level", "l", "info", "log level (trace, debug, info, warn, error, fatal, panic)")
globalFlags.StringVar(&configPath, "config", configPath, "config file path")
globalFlags.StringVar(&unixSocketPath, "daemon-socket", unixSocketPath, "batt daemon unix socket path")
for _, i := range commandGroups {
cmd.AddGroup(&cobra.Group{
ID: i,
Title: i,
})
}
cmd.AddCommand(
NewDaemonCommand(),
NewVersionCommand(),
NewLimitCommand(),
NewDisableCommand(),
NewSetDisableChargingPreSleepCommand(),
NewSetPreventIdleSleepCommand(),
NewStatusCommand(),
NewAdapterCommand(),
NewLowerLimitDeltaCommand(),
NewSetControlMagSafeLEDCommand(),
NewInstallCommand(),
NewUninstallCommand(),
)
return cmd
}
// NewVersionCommand .
func NewVersionCommand() *cobra.Command {
return &cobra.Command{
Use: "version",
Short: "Print version",
Run: func(cmd *cobra.Command, _ []string) {
cmd.Printf("%s %s\n", version.Version, version.GitCommit)
},
}
}
// NewDaemonCommand .
func NewDaemonCommand() *cobra.Command {
cmd := &cobra.Command{
Use: "daemon",
Hidden: true,
Short: "Run batt daemon in the foreground",
GroupID: gAdvanced,
Run: func(_ *cobra.Command, _ []string) {
logrus.Infof("batt version %s commit %s", version.Version, version.GitCommit)
runDaemon()
},
}
f := cmd.Flags()
f.BoolVar(&alwaysAllowNonRootAccess, "always-allow-non-root-access", false,
"Always allow non-root users to access the daemon.")
return cmd
}
// NewLimitCommand .
func NewLimitCommand() *cobra.Command {
return &cobra.Command{
Use: "limit [percentage]",
Short: "Set upper charge limit",
GroupID: gBasic,
Long: `Set upper charge limit.
This is a percentage from 10 to 100.
Setting the limit to 10-99 will enable the battery charge limit. However, setting the limit to 100 will disable the battery charge limit, which is the default behavior of macOS.`,
RunE: func(_ *cobra.Command, args []string) error {
if len(args) != 1 {
return fmt.Errorf("invalid number of arguments")
}
ret, err := put("/limit", args[0])
if err != nil {
return fmt.Errorf("failed to set limit: %v", err)
}
if ret != "" {
logrus.Infof("daemon responded: %s", ret)
}
logrus.Infof("successfully set battery charge limit to %s%%", args[0])
return nil
},
}
}
// NewDisableCommand .
func NewDisableCommand() *cobra.Command {
return &cobra.Command{
Use: "disable",
Short: "Disable batt",
GroupID: gBasic,
Long: `Disable batt.
Stop batt from controlling battery charging. This will allow your Mac to charge to 100%.`,
RunE: func(_ *cobra.Command, _ []string) error {
ret, err := put("/limit", "100")
if err != nil {
return fmt.Errorf("failed to disable batt: %v", err)
}
if ret != "" {
logrus.Infof("daemon responded: %s", ret)
}
logrus.Infof("successfully disabled batt. Charge limit has been reset to 100%%. To re-enable batt, just set a charge limit using \"batt limit\".")
return nil
},
}
}
// NewSetPreventIdleSleepCommand .
func NewSetPreventIdleSleepCommand() *cobra.Command {
cmd := &cobra.Command{
Use: "prevent-idle-sleep",
Short: "Set whether to prevent idle sleep during a charging session",
GroupID: gAdvanced,
Long: `Set whether to prevent idle sleep during a charging session.
Due to macOS limitations, batt will be paused when your computer goes to sleep. As a result, when you are in a charging session and your computer goes to sleep, there is no way for batt to stop charging (since batt is paused by macOS) and the battery will charge to 100%. This option, together with disable-charging-pre-sleep, will prevent this from happening.
This option tells macOS NOT to go to sleep when the computer is in a charging session, so batt can continue to work until charging is finished. Note that it will only prevent **idle** sleep, when 1) charging is active 2) battery charge limit is enabled. So your computer can go to sleep as soon as a charging session is completed.
However, this options does not prevent manual sleep (limitation of macOS). For example, if you manually put your computer to sleep (by choosing the Sleep option in the top-left Apple menu) or close the lid, batt will still be paused and the issue mentioned above will still happen. This is where disable-charging-pre-sleep comes in.`,
}
cmd.AddCommand(
&cobra.Command{
Use: "enable",
Short: "Prevent idle sleep during a charging session",
RunE: func(_ *cobra.Command, _ []string) error {
ret, err := put("/prevent-idle-sleep", "true")
if err != nil {
return fmt.Errorf("failed to set prevent idle sleep: %v", err)
}
if ret != "" {
logrus.Infof("daemon responded: %s", ret)
}
logrus.Infof("successfully enabled idle sleep prevention")
return nil
},
},
&cobra.Command{
Use: "disable",
Short: "Do not prevent idle sleep during a charging session",
RunE: func(_ *cobra.Command, _ []string) error {
ret, err := put("/prevent-idle-sleep", "false")
if err != nil {
return fmt.Errorf("failed to set prevent idle sleep: %v", err)
}
if ret != "" {
logrus.Infof("daemon responded: %s", ret)
}
logrus.Infof("successfully disabled idle sleep prevention")
return nil
},
},
)
return cmd
}
// NewSetDisableChargingPreSleepCommand .
func NewSetDisableChargingPreSleepCommand() *cobra.Command {
cmd := &cobra.Command{
Use: "disable-charging-pre-sleep",
Short: "Set whether to disable charging before sleep if charge limit is enabled",
GroupID: gAdvanced,
Long: `Set whether to disable charging before sleep if charge limit is enabled.
As described in preventing-idle-sleep, batt will be paused by macOS when your computer goes to sleep, and there is no way for batt to continue controlling battery charging. This option will disable charging just before sleep, so your computer will not overcharge during sleep, even if the battery charge is below the limit.`,
}
cmd.AddCommand(
&cobra.Command{
Use: "enable",
Short: "Disable charging before sleep during a charging session",
RunE: func(_ *cobra.Command, _ []string) error {
ret, err := put("/disable-charging-pre-sleep", "true")
if err != nil {
return fmt.Errorf("failed to set disable charging pre sleep: %v", err)
}
if ret != "" {
logrus.Infof("daemon responded: %s", ret)
}
logrus.Infof("successfully enabled disable-charging-pre-sleep")
return nil
},
},
&cobra.Command{
Use: "disable",
Short: "Do not disable charging before sleep during a charging session",
RunE: func(_ *cobra.Command, _ []string) error {
ret, err := put("/disable-charging-pre-sleep", "false")
if err != nil {
return fmt.Errorf("failed to set disable charging pre sleep: %v", err)
}
if ret != "" {
logrus.Infof("daemon responded: %s", ret)
}
logrus.Infof("successfully disabled disable-charging-pre-sleep")
return nil
},
},
)
return cmd
}
// NewAdapterCommand .
func NewAdapterCommand() *cobra.Command {
cmd := &cobra.Command{
Use: "adapter",
Short: "Enable or disable power input",
GroupID: gBasic,
Long: `Cut or restore power from the wall. This has the same effect as unplugging/plugging the power adapter, even if the adapter is physically plugged in.
This is useful when you want to use your battery to lower the battery charge, but you don't want to unplug the power adapter.
NOTE: if you are using Clamshell mode (using a Mac laptop with an external monitor and the lid closed), *cutting power will cause your Mac to go to sleep*. This is a limitation of macOS. There are ways to prevent this, but it is not recommended for most users.`,
}
cmd.AddCommand(
&cobra.Command{
Use: "disable",
Short: "Disable power adapter",
RunE: func(_ *cobra.Command, _ []string) error {
ret, err := put("/adapter", "false")
if err != nil {
return fmt.Errorf("failed to disable power adapter: %v", err)
}
if ret != "" {
logrus.Infof("daemon responded: %s", ret)
}
logrus.Infof("successfully disabled power adapter")
return nil
},
},
&cobra.Command{
Use: "enable",
Short: "Enable power adapter",
RunE: func(_ *cobra.Command, _ []string) error {
ret, err := put("/adapter", "true")
if err != nil {
return fmt.Errorf("failed to enable power adapter: %v", err)
}
if ret != "" {
logrus.Infof("daemon responded: %s", ret)
}
logrus.Infof("successfully enabled power adapter")
return nil
},
},
&cobra.Command{
Use: "status",
Short: "Get the current status of power adapter",
RunE: func(_ *cobra.Command, _ []string) error {
ret, err := get("/adapter")
if err != nil {
return fmt.Errorf("failed to get power adapter status: %v", err)
}
switch ret {
case "true":
logrus.Infof("power adapter is enabled")
case "false":
logrus.Infof("power adapter is disabled")
default:
logrus.Errorf("unknown power adapter status")
}
return nil
},
},
)
return cmd
}
// NewStatusCommand .
func NewStatusCommand() *cobra.Command {
return &cobra.Command{
Use: "status",
GroupID: gBasic,
Short: "Get the current status of batt",
Long: `Get batt status, battery info, and configuration.`,
RunE: func(cmd *cobra.Command, _ []string) error {
// Get various info first.
ret, err := get("/charging")
if err != nil {
return fmt.Errorf("failed to get charging status: %v", err)
}
charging, err := strconv.ParseBool(ret)
if err != nil {
return err
}
ret, err = get("/plugged-in")
if err != nil {
return fmt.Errorf("failed to check if you are plugged in: %v", err)
}
pluggedIn, err := strconv.ParseBool(ret)
if err != nil {
return err
}
ret, err = get("/adapter")
if err != nil {
return fmt.Errorf("failed to get power adapter status: %v", err)
}
adapter, err := strconv.ParseBool(ret)
if err != nil {
return err
}
ret, err = get("/current-charge")
if err != nil {
return fmt.Errorf("failed to get current charge: %v", err)
}
currentCharge, err := strconv.Atoi(ret)
if err != nil {
return fmt.Errorf("failed to unmarshal current charge: %v", err)
}
ret, err = get("/battery-info")
if err != nil {
return fmt.Errorf("failed to get battery info: %v", err)
}
var bat battery.Battery
err = json.Unmarshal([]byte(ret), &bat)
if err != nil {
return fmt.Errorf("failed to unmarshal battery info: %v", err)
}
ret, err = get("/config")
if err != nil {
return fmt.Errorf("failed to get config: %v", err)
}
conf := Config{}
err = json.Unmarshal([]byte(ret), &conf)
if err != nil {
return fmt.Errorf("failed to unmarshal config: %v", err)
}
// Charging status.
cmd.Println(bold("Charging status:"))
additionalMsg := " (refreshes can take up to 2 minutes)"
if charging {
cmd.Println(" Allow charging: " + bool2Text(true) + additionalMsg)
cmd.Print(" Your Mac will charge")
if !pluggedIn {
cmd.Print(", but you are not plugged in yet.") // not plugged in but charging is allowed.
} else {
cmd.Print(".") // plugged in and charging is allowed.
}
cmd.Println()
} else if conf.Limit < 100 {
cmd.Println(" Allow charging: " + bool2Text(false) + additionalMsg)
cmd.Print(" Your Mac will not charge")
if pluggedIn {
cmd.Print(" even if you plug in")
}
low := conf.Limit - conf.LowerLimitDelta
if currentCharge >= conf.Limit {
cmd.Print(", because your current charge is above the limit.")
} else if currentCharge < conf.Limit && currentCharge >= low {
cmd.Print(", because your current charge is above the lower limit. Charging will be allowed after current charge drops below the lower limit.")
}
if pluggedIn && currentCharge < low {
if adapter {
cmd.Print(". However, if no manual intervention is involved, charging should be allowed soon. Wait 2 minutes and come back.")
} else {
cmd.Print(", because adapter is disabled.")
}
}
cmd.Println()
}
if adapter {
cmd.Println(" Use power adapter: " + bool2Text(true))
cmd.Println(" Your Mac will use power from the wall (to operate or charge), if it is plugged in.")
} else {
cmd.Println(" Use power adapter: " + bool2Text(false))
cmd.Println(" Your Mac will not use power from the wall (to operate or charge), even if it is plugged in.")
}
cmd.Println()
// Battery Info.
cmd.Println(bold("Battery status:"))
cmd.Printf(" Current charge: %s\n", bold("%d%%", currentCharge))
state := "not charging"
switch bat.State {
case battery.Charging:
state = color.GreenString("charging")
case battery.Discharging:
state = color.RedString("discharging")
case battery.Full:
state = "full"
}
cmd.Printf(" State: %s\n", bold("%s", state))
cmd.Printf(" Full capacity: %s\n", bold("%.1f Wh", bat.Design/1e3))
cmd.Printf(" Charge rate: %s\n", bold("%.1f W", bat.ChargeRate/1e3))
cmd.Printf(" Voltage: %s\n", bold("%.2f V", bat.DesignVoltage))
cmd.Println()
// Config.
cmd.Println(bold("Batt configuration:"))
if conf.Limit < 100 {
cmd.Printf(" Upper limit: %s\n", bold("%d%%", conf.Limit))
cmd.Printf(" Lower limit: %s (%d-%d)\n", bold("%d%%", conf.Limit-conf.LowerLimitDelta), conf.Limit, conf.LowerLimitDelta)
} else {
cmd.Printf(" Charge limit: %s\n", bold("100%% (batt disabled)"))
}
cmd.Printf(" Prevent idle-sleep when charging: %s\n", bool2Text(conf.PreventIdleSleep))
cmd.Printf(" Disable charging before sleep if charge limit is enabled: %s\n", bool2Text(conf.DisableChargingPreSleep))
cmd.Printf(" Allow non-root users to access the daemon: %s\n", bool2Text(conf.AllowNonRootAccess))
cmd.Printf(" Control MagSafe LED: %s\n", bool2Text(conf.ControlMagSafeLED))
return nil
},
}
}
// NewLowerLimitDeltaCommand .
func NewLowerLimitDeltaCommand() *cobra.Command {
cmd := &cobra.Command{
Use: "lower-limit-delta",
Short: "Set the delta between lower and upper charge limit",
GroupID: gAdvanced,
Long: `Set the delta between lower and upper charge limit.
When you set a charge limit, for example, on a Lenovo ThinkPad, you can set two percentages. The first one is the upper limit, and the second one is the lower limit. When the battery charge is above the upper limit, the computer will stop charging. When the battery charge is below the lower limit, the computer will start charging. If the battery charge is between the two limits, the computer will keep whatever charging state it is in.
batt have similar features. The charge limit you have set (using 'batt limit') will be used as the upper limit. By default, The lower limit will be set to 2% less than the upper limit. Same as using 'batt lower-limit-delta 2'. To customize the lower limit, use 'batt lower-limit-delta'.
For example, if you want to set the lower limit to be 5% less than the upper limit, run 'sudo batt lower-limit-delta 5'. By doing this, if you have your charge (upper) limit set to 60%, the lower limit will be 55%.`,
RunE: func(_ *cobra.Command, args []string) error {
if len(args) != 1 {
return fmt.Errorf("invalid number of arguments")
}
delta, err := strconv.Atoi(args[0])
if err != nil {
return fmt.Errorf("invalid delta: %v", err)
}
ret, err := put("/lower-limit-delta", strconv.Itoa(delta))
if err != nil {
return fmt.Errorf("failed to set lower limit delta: %v", err)
}
if ret != "" {
logrus.Infof("daemon responded: %s", ret)
}
logrus.Infof("successfully set lower limit delta to %d%%", delta)
return nil
},
}
return cmd
}
// NewSetControlMagSafeLEDCommand .
func NewSetControlMagSafeLEDCommand() *cobra.Command {
cmd := &cobra.Command{
Use: "magsafe-led",
Short: "Control MagSafe LED according to battery charging status",
GroupID: gAdvanced,
Long: `This option can make the MagSafe LED on your MacBook change color according to the charging status. For example:
- Green: charge limit is reached and charging is stopped.
- Orange: charging is in progress.
- Off: just woken up from sleep, charing is disabled and batt is waiting before controlling charging.
Note that you must have a MagSafe LED on your MacBook to use this feature.`,
}
cmd.AddCommand(
&cobra.Command{
Use: "enable",
Short: "Control MagSafe LED according to battery charging status",
RunE: func(_ *cobra.Command, _ []string) error {
ret, err := put("/magsafe-led", "true")
if err != nil {
return fmt.Errorf("failed to set magsafe: %v", err)
}
if ret != "" {
logrus.Infof("daemon responded: %s", ret)
}
logrus.Infof("successfully enabled magsafe led controlling")
return nil
},
},
&cobra.Command{
Use: "disable",
Short: "Do not control MagSafe LED",
RunE: func(_ *cobra.Command, _ []string) error {
ret, err := put("/magsafe-led", "false")
if err != nil {
return fmt.Errorf("failed to set magsafe: %v", err)
}
if ret != "" {
logrus.Infof("daemon responded: %s", ret)
}
logrus.Infof("successfully disabled magsafe led controlling")
return nil
},
},
)
return cmd
}
func bool2Text(b bool) string {
if b {
return color.New(color.Bold, color.FgGreen).Sprint("✔")
}
return color.New(color.Bold, color.FgRed).Sprint("✘")
}
func bold(format string, a ...interface{}) string {
return color.New(color.Bold).Sprintf(format, a...)
}