You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

136 lines
3.1 KiB
Go

package system
import (
"os/exec"
"bytes"
"hash/fnv"
"strings"
"net"
"fmt"
)
// this package serves to add in wrappers for system commands to get hwinfo from the board
// this package does not actually use the hwinfo command, but rather gathers hardware info from a variety of commands
// command for model :
// lshw -C system 2>/dev/null | head -n 1
// command for ip && mac address :
// ifconfig eth0 | awk '/inet |ether / {print $2}'
// can combine and dump into file using
// lshw -C system 2>/dev/null | head -n 1 > hwinfo.txt && ifconfig eth0 | awk '/inet |ether / {print $2}' >> hwinfo.txt
// *** will just replace info in file everytime
type HWinfo struct {
Ip string
Id uint32
Bus int
Model string
Port int
}
func (h *HWinfo) GetIp() string {
return h.Ip
}
func (h *HWinfo) GetId() uint32 {
return h.Id
}
func (h *HWinfo) GetBus() int {
return h.Bus
}
func (h *HWinfo) GetPort() int {
return h.Port
}
func (h *HWinfo) GetModel() string {
return h.Model
}
func NewHWinfo() (*HWinfo, error) {
h := &HWinfo{Port:2000}
err := h.Get()
return h, err
}
func GetId(eth string) (uint32, error) {
maccmd := fmt.Sprintf("ifconfig %v | awk '/ether / {print $2}'", eth)
var stderr bytes.Buffer
var out bytes.Buffer
cmd := exec.Command("bash","-c",maccmd)
cmd.Stdout = &out
cmd.Stderr = &stderr
if err := cmd.Run(); err != nil {
return 0, err
}
hash := fnv.New32a()
hash.Write(out.Bytes())
id := hash.Sum32()
return id, nil
}
func GetIp(eth string) (string,error) {
ipcmd := fmt.Sprintf("ifconfig %v | awk '/inet / {print $2}'",eth)
var stderr bytes.Buffer
var out bytes.Buffer
cmd := exec.Command("bash","-c",ipcmd)
cmd.Stdout = &out
cmd.Stderr = &stderr
if err := cmd.Run(); err != nil {
return "", err
}
ip := strings.Trim(out.String()," \n")
return ip, nil
}
func GetPort() (int, error) {
if addr, err := net.ResolveTCPAddr("tcp",":0"); err != nil {
return 0, err
} else if lis, err := net.ListenTCP("tcp",addr); err != nil {
return 0, err
} else {
defer lis.Close()
return lis.Addr().(*net.TCPAddr).Port, nil
}
}
func (h *HWinfo) Get() error {
// responsible for filling out struct
bus := map[string]int{"raspberrypi":1,"beaglebone":2} // eventually will replace this with a config file
ipcmd := "ifconfig eth0 | awk '/inet / {print $2}'"
maccmd := "ifconfig eth0 | awk '/ether / {print $2}'"
devcmd := "lshw -C system 2>/dev/null | head -n 1"
res := [3]bytes.Buffer{}
var stderr bytes.Buffer
cmds := []string{ipcmd,maccmd,devcmd}
for i,c := range cmds {
cmd := exec.Command("bash","-c",c)
cmd.Stdout = &res[i]
cmd.Stderr = &stderr
err := cmd.Run()
if err != nil {
return err
}
}
// formatting
ip := res[0].String()
ip = strings.Trim(ip," \n")
h.Ip = ip
hash := fnv.New32a()
hash.Write(res[1].Bytes())
h.Id = hash.Sum32()
b := res[2].String()
b = strings.Trim(b," \n")
h.Model = b
h.Bus = bus[b]
return nil
}