~kota/battery

battery/main.go -rw-r--r-- 1.8 KiB
00ecd102Dakota Walsh add license 5 months ago
                                                                                
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
// battery - Print battery charge percent or status.
package main

import (
	"fmt"
	"io/ioutil"
	"os"
	"strconv"
	"strings"
)

const (
	nowPath    string = "/sys/class/power_supply/BAT0/energy_now"
	maxPath    string = "/sys/class/power_supply/BAT0/energy_full"
	chargePath string = "/sys/class/power_supply/BAT0/status"
)

// return an int percent from two int values
func percent(n, m int) int {
	return int(float32(n) / (float32(m) / 100))
}

// read and return battery charge percentage as int
func battery(np, mp string) int {
	nb, err := ioutil.ReadFile(np)
	mb, err := ioutil.ReadFile(mp)
	if err != nil {
		fmt.Printf("failed to read file: %v\n", err)
		os.Exit(1)
	}

	// convert types
	ns := strings.TrimSuffix(string(nb), "\n")
	ni, err := strconv.Atoi(ns)
	ms := strings.TrimSuffix(string(mb), "\n")
	mi, err := strconv.Atoi(ms)

	// return int percentage
	return percent(ni, mi)
}

// read charging status and return a boolean
func charging(p string) bool {
	cb, err := ioutil.ReadFile(p)
	if err != nil {
		fmt.Printf("failed to read file: %v\n", err)
		os.Exit(1)
	}

	cs := strings.TrimSuffix(string(cb), "\n")
	if cs == "Charging" {
		return true
	} else {
		return false
	}
}

func main() {
	switch a := len(os.Args); a {
	case 1:
		// print the battery percent
		fmt.Println(battery(nowPath, maxPath))
	case 2:
		// print battery increase or no symbol
		if charging(chargePath) {
			fmt.Println(os.Args[1])
		}
	case 3:
		// print battery increase or decrease symbol
		if charging(chargePath) {
			fmt.Println(os.Args[1])
		} else {
			fmt.Println(os.Args[2])
		}
	default:
		// print battery increase or decrease symbol
		if charging(chargePath) {
			fmt.Print(battery(nowPath, maxPath), os.Args[1], "\n")
		} else {
			fmt.Print(battery(nowPath, maxPath), os.Args[2], "\n")
		}
	}
}