This repository has been archived on 2024-08-02. You can view files and clone it, but cannot push or open issues or pull requests.
orion/openwrt/wifi.go

92 lines
2.1 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}
}
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 {
2018-09-20 10:59:11 +02:00
new := false
mac, ssid, enc := "", "", ""
for _, line := range strings.Split(strings.TrimSuffix(stdout, "\n"), "\n") {
2018-09-20 10:59:11 +02:00
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)
2018-09-20 10:59:11 +02:00
}
if len(mac) > 0 && len(ssid) > 0 && len(enc) > 0 {
cell := NewWifiCell(ssid, mac, enc)
w.Cells = append(w.Cells, cell)
ssid, mac, enc = "", "", ""
2018-09-20 10:59:11 +02:00
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)
}
2018-09-20 10:59:11 +02:00
// 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
}