92 lines
2.1 KiB
Go
92 lines
2.1 KiB
Go
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}
|
|
}
|
|
|
|
func (w *Wifi) getEncryption(line string) string {
|
|
enc := "unkn"
|
|
if strings.Contains(line, "WPA2 PSK") {
|
|
enc = "psk"
|
|
} else if strings.Contains(line, "none") {
|
|
enc = "none"
|
|
}
|
|
return enc
|
|
}
|
|
|
|
func (w *Wifi) parseWifiCells(stdout string) int {
|
|
new := false
|
|
mac, ssid, enc := "", "", ""
|
|
for _, line := range strings.Split(strings.TrimSuffix(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:") {
|
|
enc = w.getEncryption(line)
|
|
}
|
|
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
|
|
}
|
|
|
|
// GetWifiCells retrieves all available 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(time.Second)
|
|
res = w.exec.Run("iwinfo", w.iface, "scan")
|
|
if res.ReturnCode != 0 {
|
|
log.Fatal(res.Stderr)
|
|
return res.ReturnCode
|
|
}
|
|
}
|
|
return w.parseWifiCells(res.Stdout)
|
|
}
|
|
|
|
// 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
|
|
}
|