File: battery.go

package info (click to toggle)
golang-github-jouyouyun-hardware 0.1.8-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 184 kB
  • sloc: ansic: 43; makefile: 4
file content (102 lines) | stat: -rw-r--r-- 2,145 bytes parent folder | download | duplicates (2)
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
package battery

import (
	"io/ioutil"
	"path/filepath"
	"strconv"
	"strings"

	"github.com/jouyouyun/hardware/utils"
)

const (
	batterySysfsDir = "/sys/class/power_supply"
)

// Battery store battery info
type Battery struct {
	Name         string
	Model        string
	Manufacturer string
	Serial       string
	Technology   string

	CapacityDesign int64
	CapacityNow    int64
}

// BatteryList store battery list
type BatteryList []*Battery

// GetBatteryList return battery list
func GetBatteryList() (BatteryList, error) {
	list, err := utils.ScanDir(batterySysfsDir, func(string) bool {
		return false
	})
	if err != nil {
		return nil, err
	}
	var batList BatteryList
	for _, name := range list {
		if !isBattery(batterySysfsDir, name) {
			continue
		}
		bat, err := newBattery(batterySysfsDir, name)
		if err != nil {
			return nil, err
		}
		batList = append(batList, bat)
	}
	return batList, nil
}

func newBattery(dir, name string) (*Battery, error) {
	uevent := filepath.Join(dir, name, "uevent")
	set, err := parseFile(uevent)
	if err != nil {
		return nil, err
	}

	var bat = Battery{
		Name:         set["POWER_SUPPLY_NAME"],
		Model:        set["POWER_SUPPLY_MODEL_NAME"],
		Manufacturer: set["POWER_SUPPLY_MANUFACTURER"],
		Serial:       set["POWER_SUPPLY_SERIAL_NUMBER"],
		Technology:   set["POWER_SUPPLY_TECHNOLOGY"],
	}
	bat.CapacityDesign, _ = strconv.ParseInt(set["POWER_SUPPLY_CHARGE_FULL_DESIGN"],
		10, 64)
	bat.CapacityNow, _ = strconv.ParseInt(set["POWER_SUPPLY_CHARGE_NOW"],
		10, 64)
	return &bat, nil
}

func isBattery(dir, name string) bool {
	filename := filepath.Join(dir, name, "type")
	ty, err := utils.ReadFileContent(filename)
	if err != nil {
		return false
	}
	return ty == "Battery"
}

func parseFile(filename string) (map[string]string, error) {
	content, err := ioutil.ReadFile(filename)
	if err != nil {
		return nil, err
	}

	var set = make(map[string]string)
	lines := strings.Split(string(content), "\n")
	for _, line := range lines {
		if len(line) == 0 {
			continue
		}
		items := strings.Split(line, "=")
		if len(items) != 2 {
			continue
		}
		set[items[0]] = items[1]
	}
	return set, nil
}