orion/openwrt/wifi.go

89 lines
1.9 KiB
Go
Raw Normal View History

2018-09-20 10:59:11 +02:00
package openwrt
import (
"log"
"strings"
"time"
)
// Wifi gives access to al OpenWRT Wifi operations
type Wifi struct {
exec Executor
iface string
Cells []*WifiCell
}
// NewWifi return an UCI instance to interact with UCI
func NewWifi(wIface string) *Wifi {
exec := &localExecutor{}
iface := wIface
return &Wifi{exec, iface, nil}
}
// NewWifiWithExecutor returns a Wifi Instance an gives you the ability to provide
// a different command executor than the default one.
func NewWifiWithExecutor(exec Executor, wIface string) *Wifi {
return &Wifi{exec, wIface, nil}
}
// GetWifiCells retrieves all availabe wifi cells for a card !
func (w *Wifi) GetWifiCells() int {
res := w.exec.Run("iwinfo", w.iface, "scan")
if res.ReturnCode != 0 {
log.Fatal(res.Stderr)
return res.ReturnCode
}
for res.Stdout == "Scanning not possible" {
time.Sleep(1)
res = w.exec.Run("iwinfo", w.iface, "scan")
2018-09-20 10:59:11 +02:00
if res.ReturnCode != 0 {
log.Fatal(res.Stderr)
return res.ReturnCode
}
}
new := false
mac := ""
ssid := ""
enc := ""
for _, line := range strings.Split(strings.TrimSuffix(res.Stdout, "\n"), "\n") {
if strings.HasPrefix(line, "Cell") && new == false {
new = true
mac = strings.Split(line, " ")[4]
}
if strings.Contains(line, "ESSID:") {
ssid = strings.Split(line, " ")[1]
ssid = strings.Trim(ssid, "\"")
}
if strings.Contains(line, "Encryption:") {
if strings.Contains(line, "WPA2 PSK") {
enc = "psk"
} else if strings.Contains(line, "none") {
enc = "none"
} else {
enc = "unkn"
}
}
if len(mac) > 0 && len(ssid) > 0 && len(enc) > 0 {
cell := NewWifiCell(ssid, mac, enc)
w.Cells = append(w.Cells, cell)
ssid = ""
mac = ""
enc = ""
new = false
}
}
return 0
}
// GetCell retreives an WifiCell by SSID provided in parameter
func (w *Wifi) GetCell(ssid string) *WifiCell {
for _, v := range w.Cells {
if v.Ssid == ssid {
return v
}
}
return nil
}