github.com/Code-Hex/battery@v1.0.0/battery_linux.go (about) 1 package battery 2 3 import ( 4 "bufio" 5 "os" 6 "path/filepath" 7 "strconv" 8 "strings" 9 ) 10 11 func Info() (percent int, elapsed int, present bool, err error) { 12 var uevents []string 13 uevents, err = filepath.Glob("/sys/class/power_supply/BAT*/uevent") 14 if err != nil { 15 return 16 } 17 if len(uevents) == 0 { 18 return 19 } 20 var f *os.File 21 for _, u := range uevents { 22 f, err = os.Open(u) 23 if err == nil { 24 break 25 } 26 } 27 if err != nil { 28 return 29 } 30 defer f.Close() 31 scanner := bufio.NewScanner(f) 32 33 var full, now, powerNow float64 34 for scanner.Scan() { 35 tokens := strings.SplitN(scanner.Text(), "=", 2) 36 if len(tokens) != 2 { 37 continue 38 } 39 switch tokens[0] { 40 case "POWER_SUPPLY_ENERGY_FULL_DESIGN": 41 full, _ = strconv.ParseFloat(tokens[1], 64) 42 case "POWER_SUPPLY_CHARGE_FULL": 43 full, _ = strconv.ParseFloat(tokens[1], 64) 44 case "POWER_SUPPLY_ENERGY_NOW": 45 now, _ = strconv.ParseFloat(tokens[1], 64) 46 case "POWER_SUPPLY_CHARGE_NOW": 47 now, _ = strconv.ParseFloat(tokens[1], 64) 48 case "POWER_SUPPLY_STATUS": 49 present = tokens[1] == "Charging" 50 case "POWER_SUPPLY_POWER_NOW": 51 powerNow, _ = strconv.ParseFloat(tokens[1], 64) 52 } 53 } 54 if full > 0 { 55 percent = int(now / full * 100) 56 } 57 if powerNow > 0 { 58 elapsed = int(now / powerNow * 60) 59 } 60 return 61 }