statusmonitor/top.go

52 lines
995 B
Go
Raw Normal View History

2017-12-16 14:20:26 +00:00
package main
import (
"fmt"
"strconv"
"strings"
)
2017-12-16 18:19:27 +00:00
// adbCPU returns CPU value for the given PID via `adb shell` command.
func adbCPU(pid int64) (float64, error) {
cmd := fmt.Sprintf("top -p %d -n 1 -q -b -o %%CPU", pid)
out, err := adbShell(cmd)
if err != nil {
return 0, err
}
top, err := NewTopOutput(out)
if err != nil {
return 0, err
}
return top.CPU, nil
}
2017-12-16 14:20:26 +00:00
// TopOutput represents data from 'top' command output
// for single process.
type TopOutput struct {
CPU float64
}
// NewTopOutput creates new TopOutput from raw stdout data.
func NewTopOutput(data string) (*TopOutput, error) {
2017-12-16 18:19:27 +00:00
line := cleanTopOutput(data)
2017-12-16 14:20:26 +00:00
2017-12-16 18:19:27 +00:00
cpu, err := strconv.ParseFloat(line, 64)
2017-12-16 14:20:26 +00:00
if err != nil {
return nil, ErrParse
}
return &TopOutput{
CPU: cpu,
}, nil
}
2017-12-16 18:19:27 +00:00
func cleanTopOutput(data string) string {
2017-12-16 14:20:26 +00:00
lines := strings.Split(data, "\r")
line := strings.Replace(lines[0], "\r", "", -1)
2017-12-16 18:19:27 +00:00
line = strings.Replace(lines[0], "\b", "", -1)
2017-12-16 14:20:26 +00:00
line = strings.TrimSpace(line)
2017-12-16 18:19:27 +00:00
return line
2017-12-16 14:20:26 +00:00
}