ArinDash/widgets/networkdevices.go

70 lines
1.9 KiB
Go

package widgets
import (
"ArinDash/apis/networking"
"ArinDash/util"
"context"
"fmt"
"sort"
"strings"
"time"
"github.com/mum4k/termdash/cell"
"github.com/mum4k/termdash/terminal/terminalapi"
"github.com/mum4k/termdash/widgetapi"
"github.com/mum4k/termdash/widgets/text"
)
type NetworkDevicesOptions struct {
}
func NetworkDevices() NetworkDevicesOptions {
widgetOptions["NetworkDevicesOptions"] = createNetworkDevicesList
return NetworkDevicesOptions{}
}
func createNetworkDevicesList(ctx context.Context, _ terminalapi.Terminal, _ interface{}) widgetapi.Widget {
list := util.PanicOnErrorWithResult(text.New())
go util.Periodic(ctx, 20*time.Second, func() error {
devices := networking.GetDevices()
list.Reset()
for _, mac := range sortedKeys(devices) {
status := cell.ColorGray
if devices[mac].Online {
status = cell.ColorGreen
}
//if err := list.Write(fmt.Sprintf("|%-15s|", mac), text.WriteCellOpts(cell.FgColor(cell.ColorGray))); err != nil {
// return err
//}
if err := list.Write(fmt.Sprintf("%2s ", devices[mac].Icon), text.WriteCellOpts(cell.BgColor(status), cell.FgColor(cell.ColorBlack))); err != nil {
return err
}
if err := list.Write(fmt.Sprint("|"), text.WriteCellOpts(cell.FgColor(cell.ColorGray))); err != nil {
return err
}
if err := list.Write(fmt.Sprintf(" %s", devices[mac].Name), text.WriteCellOpts(cell.FgColor(cell.ColorWhite))); err != nil {
return err
}
if err := list.Write(fmt.Sprintf(" (%s)\n", devices[mac].IP), text.WriteCellOpts(cell.FgColor(cell.ColorGray))); err != nil {
return err
}
}
return nil
})
return list
}
func sortedKeys(devices map[string]networking.Device) []string {
macs := make([]string, 0, len(devices))
for mac := range devices {
macs = append(macs, mac)
}
sort.SliceStable(macs, func(i, j int) bool {
return strings.Compare(devices[macs[i]].Name, devices[macs[j]].Name) < 0
})
return macs
}