-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathdriver.go
592 lines (536 loc) · 17.7 KB
/
driver.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
// Copyright (C) 2019 Evgeny Kuznetsov ([email protected])
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
package main
import (
"bytes"
"errors"
"os"
"os/exec"
"regexp"
"strconv"
"strings"
"time"
"github.com/nicksnyder/go-i18n/v2/i18n"
)
const (
kbdlightTimeoutDriverEndpoint = "/sys/devices/platform/huawei-wmi/kbdlight_timeout"
fnlockDriverEndpoint = "/sys/devices/platform/huawei-wmi/fn_lock_state"
threshKernelPath = "/sys/class/power_supply/BAT"
threshKernelMin = "/charge_control_start_threshold"
threshKernelMax = "/charge_control_end_threshold"
saveValuesPath = "/etc/default/huawei-wmi/"
)
var (
fnlockEndpoints = []fnlockEndpoint{}
threshEndpoints = []threshEndpoint{}
threshSaveEndpoints = []threshDriver{
{threshDriverSingle{path: (saveValuesPath + "charge_control_thresholds")}},
{threshDriverSingle{path: (saveValuesPath + "charge_thresholds")}},
}
threshDriver1 = threshDriver{threshDriverSingle{path: "/sys/devices/platform/huawei-wmi/charge_thresholds"}}
threshDriver2 = threshDriver{threshDriverSingle{path: "/sys/devices/platform/huawei-wmi/charge_control_thresholds"}}
kdblightTimeoutEndpoints = []kdblightTimeoutEndpoint{
kdblightTimeoutDriver{path: kbdlightTimeoutDriverEndpoint},
}
)
func init() {
fndrv := fnlockDriver{path: fnlockDriverEndpoint}
fnlockEndpoints = append(fnlockEndpoints, fndrv)
threshEndpoints = append(threshEndpoints, threshDriver2, threshDriver1)
for i := 0; i < 10; i++ {
min := threshKernelPath + strconv.Itoa(i) + threshKernelMin
max := threshKernelPath + strconv.Itoa(i) + threshKernelMax
threshEndpoints = append(threshEndpoints, threshDriver{threshDriverMinMax{pathMin: min, pathMax: max}})
}
if config.useScripts {
sudo := "/usr/bin/sudo"
fnscr := fnlockScript{toggleCmd: exec.Command(sudo, "-n", "fnlock", "toggle"), getCmd: exec.Command(sudo, "-n", "fnlock", "status")}
fnlockEndpoints = append(fnlockEndpoints, fnscr)
cmdLine := []string{sudo, "-n", "batpro"}
batpro := threshScript{
getCmd: exec.Command(sudo, append(cmdLine, "status")...),
setCmd: exec.Command(sudo, append(cmdLine, "custom")...),
offCmd: exec.Command(sudo, append(cmdLine, "off")...),
}
threshEndpoints = append(threshEndpoints, batpro)
}
}
type fnlockEndpoint interface {
toggle()
get() (bool, error)
isWritable() bool
}
type threshEndpoint interface {
set(min, max int)
get() (min, max int, err error)
isWritable() bool
}
type fnlockScript struct {
getCmd *exec.Cmd
toggleCmd *exec.Cmd
}
type fnlockDriver struct {
path string
}
type wmiDriver interface {
write(min, max int) error
get() (min, max int, err error)
}
type threshDriver struct {
wmiDriver
}
type threshDriverSingle struct {
path string
}
type threshDriverMinMax struct {
pathMin string
pathMax string
}
type threshScript struct {
getCmd *exec.Cmd
setCmd *exec.Cmd
offCmd *exec.Cmd
}
type kdblightTimeoutEndpoint interface {
set(int)
get() (int, error)
isWritable() bool
}
type kdblightTimeoutDriver struct {
path string
}
func (drv kdblightTimeoutDriver) set(i int) {
if i < 0 {
return
}
err := os.WriteFile(drv.path, []byte(strconv.Itoa(i)), 0664)
if err != nil {
logError.Println(localizer.MustLocalize(&i18n.LocalizeConfig{
DefaultMessage: &i18n.Message{
ID: "CantSetKdblightTimeout",
Other: "Failed to set keyboard light timeout",
},
}))
}
}
func (drv kdblightTimeoutDriver) get() (int, error) {
if _, err := os.Stat(drv.path); err != nil {
logTrace.Printf("Couldn't access %q.", drv.path)
return 0, err
}
val, err := os.ReadFile(drv.path)
if err != nil {
logError.Println(localizer.MustLocalize(&i18n.LocalizeConfig{MessageID: "CantReadKdblightTimeout"}))
logTrace.Println(err)
return 0, err
}
result, err := strconv.Atoi(strings.TrimSpace(string(val)))
if err != nil || result < 0 {
logWarning.Println(localizer.MustLocalize(&i18n.LocalizeConfig{
DefaultMessage: &i18n.Message{
ID: "StrangeKdblightTimeout",
Other: "Keyboard light timeout reported by driver doesn't make sense",
},
}))
}
return result, err
}
func (drv kdblightTimeoutDriver) isWritable() bool {
val, err := drv.get()
if err == nil {
err = os.WriteFile(drv.path, []byte(strconv.Itoa(val)), 0664)
if err == nil {
logTrace.Println("successful write to driver interface")
return true
}
}
logTrace.Println(err)
logWarning.Println(localizer.MustLocalize(&i18n.LocalizeConfig{
DefaultMessage: &i18n.Message{
ID: "ReadOnlyDriver",
Other: "Driver interface is readable but not writeable.",
},
}))
return false
}
func (drv fnlockDriver) get() (bool, error) {
if _, err := os.Stat(drv.path); err != nil {
logTrace.Printf("Couldn't access %q.", drv.path)
return false, err
}
val, err := os.ReadFile(drv.path)
if err != nil {
logError.Println(localizer.MustLocalize(&i18n.LocalizeConfig{MessageID: "CantReadFnlock"}))
logTrace.Println(err)
}
value := strings.TrimSpace(string(val))
switch value {
case "0":
logTrace.Println("Fn-lock is OFF")
return false, err
case "1":
logTrace.Println("Fn-lock is ON")
return true, err
default:
logWarning.Println(localizer.MustLocalize(&i18n.LocalizeConfig{DefaultMessage: &i18n.Message{ID: "StrangeFnlock", Other: "Fn-lock state reported by driver doesn't make sense"}}))
return false, errors.New("state is reported as " + value)
}
}
func btobb(b bool) []byte {
var s string
if b {
s = "1"
} else {
s = "0"
}
return []byte(s)
}
func (drv fnlockDriver) checkWritable() bool {
val, err := drv.get()
if err == nil {
err = os.WriteFile(drv.path, btobb(val), 0664)
if err == nil {
logTrace.Println("successful write to driver interface")
return true
}
}
logTrace.Println(err)
logWarning.Println(localizer.MustLocalize(&i18n.LocalizeConfig{DefaultMessage: &i18n.Message{ID: "ReadOnlyDriver", Other: "Driver interface is readable but not writeable."}}))
return false
}
func (drv fnlockDriver) toggle() {
val, err := drv.get()
if err != nil {
logError.Println(localizer.MustLocalize(&i18n.LocalizeConfig{MessageID: "CantReadFnlock"}))
logTrace.Println(err)
return
}
value := btobb(!val)
err = os.WriteFile(drv.path, value, 0644)
if err != nil {
logTrace.Println(err)
logWarning.Println(localizer.MustLocalize(&i18n.LocalizeConfig{DefaultMessage: &i18n.Message{ID: "CantSetFnlockDriver", Other: "Could not set Fn-Lock status through driver interface"}}))
return
}
logTrace.Println("successful write to driver interface")
}
func (scr threshScript) isWritable() bool {
return true
}
func (drv threshDriver) isWritable() bool {
logTrace.Println("Checking if the threshold endpoint is writable...")
return drv.checkWritable()
}
func (drv fnlockDriver) isWritable() bool {
logTrace.Println("Checking if the fnlock endpoint is writable...")
return drv.checkWritable()
}
func (scr fnlockScript) isWritable() bool {
return true
}
func (scr fnlockScript) get() (bool, error) {
cmd := scr.getCmd
var out bytes.Buffer
cmd.Stdout = &out
err := cmd.Run()
if err != nil {
logError.Println(localizer.MustLocalize(&i18n.LocalizeConfig{DefaultMessage: &i18n.Message{ID: "CantReadFnlockScript", Other: "Failed to get fnlock status from script"}}))
}
state := parseOnOffStatus(out.String())
if state == "on" {
return true, err
}
return false, err
}
func (scr fnlockScript) toggle() {
cmd := scr.toggleCmd
if err := cmd.Run(); err != nil {
logError.Println(localizer.MustLocalize(&i18n.LocalizeConfig{DefaultMessage: &i18n.Message{ID: "CantToggleFnlock", Other: "Failed to toggle Fn-Lock"}}))
}
}
func (drv threshDriverSingle) get() (min, max int, err error) {
if _, err = os.Stat(drv.path); err != nil {
logTrace.Printf("Couldn't access %q.", drv.path)
return
}
var values [2]string
val, err := os.ReadFile(drv.path)
if err != nil {
logError.Println(localizer.MustLocalize(&i18n.LocalizeConfig{DefaultMessage: &i18n.Message{ID: "CantReadBatteryDriver", Other: "Failed to get thresholds from driver interface"}}))
logTrace.Println(err)
}
valuesReceived := strings.Split(strings.TrimSpace(string(val)), " ")
logTrace.Println("got values from interface:", valuesReceived)
if len(valuesReceived) != 2 {
logError.Println(localizer.MustLocalize(&i18n.LocalizeConfig{DefaultMessage: &i18n.Message{ID: "CantUnderstandBattery", Other: "Can not make sense of driver interface value {{.Value}}"}, TemplateData: map[string]interface{}{"Value": val}}))
return
}
for i := 0; i < 2; i++ {
values[i] = valuesReceived[i]
}
min, max, err = valuesAtoi(values[0], values[1])
return
}
func valuesAtoi(mins, maxs string) (min, max int, err error) {
min, err = strconv.Atoi(mins)
if err != nil {
logTrace.Println(err)
}
max, err = strconv.Atoi(maxs)
if err != nil {
logTrace.Println(err)
}
logTrace.Printf("interpreted values: min %d%%, max %d%%\n", min, max)
return
}
func (drv threshDriverMinMax) writeDo(min, max int) error {
if err := os.WriteFile(drv.pathMin, []byte(strconv.Itoa(min)), 0664); err != nil {
logError.Println(localizer.MustLocalize(&i18n.LocalizeConfig{DefaultMessage: &i18n.Message{ID: "CantSetBatteryMin", Other: "Failed to set min threshold"}}))
return err
}
if err := os.WriteFile(drv.pathMax, []byte(strconv.Itoa(max)), 0664); err != nil {
logError.Println(localizer.MustLocalize(&i18n.LocalizeConfig{DefaultMessage: &i18n.Message{ID: "CantSetBatteryMax", Other: "Failed to set max threshold"}}))
return err
}
return nil
}
func (drv threshDriverMinMax) write(min, max int) error {
err := drv.writeDo(0, 100)
if err != nil {
return err
}
err = drv.writeDo(min, max)
if err == nil {
logTrace.Println("successful write to driver interface")
}
return err
}
func (drv threshDriverMinMax) get() (min, max int, err error) {
if _, err = os.Stat(drv.pathMin); err != nil {
logTrace.Printf("Couldn't access %q.", drv.pathMin)
return
}
var values [2]string
val, err := os.ReadFile(drv.pathMin)
if err != nil {
logError.Println(localizer.MustLocalize(&i18n.LocalizeConfig{DefaultMessage: &i18n.Message{ID: "CantReadBatteryMin", Other: "Failed to get min threshold from driver interface"}}))
logTrace.Println(err)
return
}
values[0] = string(val)
val, err = os.ReadFile(drv.pathMax)
if err != nil {
logError.Println(localizer.MustLocalize(&i18n.LocalizeConfig{DefaultMessage: &i18n.Message{ID: "CantReadBatteryMax", Other: "Failed to get max threshold from driver interface"}}))
logTrace.Println(err)
return
}
values[1] = string(val)
for i := 0; i < 2; i++ {
values[i] = strings.TrimSuffix(values[i], "\n")
}
min, max, err = valuesAtoi(values[0], values[1])
return
}
func (drv threshDriverSingle) write(min, max int) error {
values := []byte(strconv.Itoa(min) + " " + strconv.Itoa(max) + "\n")
err := os.WriteFile(drv.path, values, 0664)
if err != nil {
logError.Println(localizer.MustLocalize(&i18n.LocalizeConfig{MessageID: "CantSetBattery"}))
} else {
logTrace.Println("successful write to driver interface")
}
return err
}
func (drv threshDriver) checkWritable() bool {
min, max, err := drv.get()
if err != nil {
return false
}
err = drv.write(min, max)
return (err == nil)
}
func (drv threshDriver) set(min, max int) {
if err := drv.write(min, max); err != nil {
return
}
if config.wait {
logTrace.Println("thresholds pushed to driver, will wait for them to be set")
// driver takes some time to set values due to ACPI bug
for i := 1; i < 5; i++ {
time.Sleep(900 * time.Millisecond)
logTrace.Println("checking thresholds, attempt", i)
newMin, newMax, err := drv.get()
if min == newMin && max == newMax && err == nil {
logTrace.Println("thresholds set as expected")
break
}
logTrace.Println("not set yet")
}
logTrace.Println("alright, going on")
}
}
func (scr threshScript) get() (min, max int, err error) {
cmd := scr.getCmd
var out bytes.Buffer
cmd.Stdout = &out
err = cmd.Run()
if err != nil {
logError.Println(localizer.MustLocalize(&i18n.LocalizeConfig{DefaultMessage: &i18n.Message{ID: "CantReadBatteryScript", Other: "Failed to get battery protection status from script"}}))
return
}
state, min, max := parseStatus(out.String())
if state == "on" {
min = 0
max = 100
}
return
}
func (scr threshScript) set(min, max int) {
var cmd *exec.Cmd
if min == 0 && max == 100 {
cmd = scr.offCmd
} else {
cmd = scr.setCmd
cmd.Args = append(cmd.Args, strconv.Itoa(min), strconv.Itoa(max))
}
if err := cmd.Run(); err != nil {
logError.Println(localizer.MustLocalize(&i18n.LocalizeConfig{MessageID: "CantSetBattery"}))
}
}
func setThresholds(min int, max int) {
config.thresh.set(min, max)
if config.threshPers != nil {
logTrace.Println("Saving values for persistence...")
config.threshPers.set(min, max)
}
}
func getStatus() string {
var r, status string
min, max, err := config.thresh.get()
if err != nil {
r = localizer.MustLocalize(&i18n.LocalizeConfig{DefaultMessage: &i18n.Message{ID: "BatteryProtectionStatusError", Other: "ERROR: can not get BP status!"}})
} else {
if min >= 0 && min <= 100 && max >= 0 && max <= 100 && min <= max {
switch {
case min == 0 && (max == 100 || max == 0):
status = localizer.MustLocalize(&i18n.LocalizeConfig{MessageID: "StatusOff"})
r = localizer.MustLocalize(&i18n.LocalizeConfig{DefaultMessage: &i18n.Message{ID: "BatteryProtectionOff", Other: "Battery protection is {{.Status}}"}, TemplateData: map[string]interface{}{"Status": status}})
return r
case min == 40 && max == 70:
status = localizer.MustLocalize(&i18n.LocalizeConfig{MessageID: "StatusHome"})
case min == 70 && max == 90:
status = localizer.MustLocalize(&i18n.LocalizeConfig{MessageID: "StatusOffice"})
case min == 95 && max == 100:
status = localizer.MustLocalize(&i18n.LocalizeConfig{MessageID: "StatusTravel"})
default:
status = localizer.MustLocalize(&i18n.LocalizeConfig{MessageID: "StatusCustom", TemplateData: map[string]interface{}{"Min": min, "Max": max}})
}
} else {
logWarning.Println(localizer.MustLocalize(&i18n.LocalizeConfig{DefaultMessage: &i18n.Message{ID: "StrangeThresholds", Other: "BP thresholds don't make sense: min {{.Min}}%, max {{.Max}}%"}, TemplateData: map[string]interface{}{"Min": min, "Max": max}}))
status = localizer.MustLocalize(&i18n.LocalizeConfig{MessageID: "StatusOn"})
r = localizer.MustLocalize(&i18n.LocalizeConfig{DefaultMessage: &i18n.Message{ID: "BatteryProtectionStatusStrange", Other: "{{.Status}}, but thresholds make no sense."}, TemplateData: map[string]interface{}{"Status": status}})
return r
}
r = localizer.MustLocalize(&i18n.LocalizeConfig{DefaultMessage: &i18n.Message{ID: "BatteryProtectionStatus", Other: "Battery protection mode: {{.Status}}"}, TemplateData: map[string]interface{}{"Status": status}})
}
return r
}
func getFnlockStatus() string {
var r, status string
state, err := config.fnlock.get()
if state {
status = localizer.MustLocalize(&i18n.LocalizeConfig{MessageID: "StatusOn"})
} else {
status = localizer.MustLocalize(&i18n.LocalizeConfig{MessageID: "StatusOff"})
}
if err != nil {
r = localizer.MustLocalize(&i18n.LocalizeConfig{DefaultMessage: &i18n.Message{ID: "FnlockStatusError", Other: "ERROR: Fn-Lock state unknown"}})
} else {
r = localizer.MustLocalize(&i18n.LocalizeConfig{DefaultMessage: &i18n.Message{ID: "FnlockStatus", Other: "Fn-Lock is {{.Status}}"}, TemplateData: map[string]interface{}{"Status": status}})
}
return r
}
func getKbdlightTimeoutStatus() string {
var r string
timeout, err := config.kdblightTimeout.get()
if err != nil {
r = localizer.MustLocalize(&i18n.LocalizeConfig{
DefaultMessage: &i18n.Message{
ID: "KdblightTimeoutStatusError",
Other: "ERROR: Keyboard light timeout unknown",
},
})
} else if timeout == 0 {
r = localizer.MustLocalize(&i18n.LocalizeConfig{
DefaultMessage: &i18n.Message{
ID: "KdblightTimeoutStatusOff",
Other: "Keyboard light timeout is off",
},
})
} else {
r = localizer.MustLocalize(&i18n.LocalizeConfig{
DefaultMessage: &i18n.Message{
ID: "KdblightTimeoutStatusOn",
One: "Keyboard light timeout is {{.Timeout}}s.",
Other: "Keyboard light timeout is {{.Timeout}}s.",
},
TemplateData: map[string]interface{}{"Timeout": timeout},
PluralCount: timeout,
})
}
return r
}
func parseOnOffStatus(s string) string {
stateRe := regexp.MustCompile(`^o(n|ff)$`)
lines := strings.Split(s, "\n")
state := ""
for _, line := range lines {
if stateRe.MatchString(line) {
state = line
}
}
return state
}
func parseStatus(s string) (string, int, int) {
stateRe := regexp.MustCompile(`^battery protection is o[a-z]{1,}`)
minRe := regexp.MustCompile(`^minimum \d* %$`)
maxRe := regexp.MustCompile(`^maximum \d* %$`)
lines := strings.Split(s, "\n")
state := ""
min := 0
max := 0
for _, line := range lines {
if stateRe.MatchString(line) {
state = (strings.TrimPrefix(line, "battery protection is "))
}
if minRe.MatchString(line) {
val, err := strconv.Atoi((strings.TrimPrefix(strings.TrimSuffix(line, " %"), "minimum ")))
if err != nil {
min = 0
} else {
min = val
}
}
if maxRe.MatchString(line) {
val, err := strconv.Atoi((strings.TrimPrefix(strings.TrimSuffix(line, " %"), "maximum ")))
if err != nil {
max = 0
} else {
max = val
}
}
}
return state, min, max
}