wmtools/nic.nim

67 lines
1.8 KiB
Nim
Raw Normal View History

2022-04-28 21:58:40 +02:00
import base
import std/[os,osproc,strutils,sequtils]
2022-02-26 22:44:00 +01:00
const default_fg = black
const default_bg = purple
const mng_cmd = "alacritty -e nmtui-connect"
const nics: seq[string] = @["wlan0","bridge0", "enp3s0","wlp2s0","enp0s20f0u3"]
2022-02-26 22:44:00 +01:00
proc getIP(nic: string): string =
2022-02-26 22:44:00 +01:00
let cmd = "ifconfig " & nic & " | grep inet | awk -F\" \" '{print $2}' | head -1 | awk '{print $1}'"
let ip = execCmdEx(cmd)
return strip(ip.output)
proc getOnlineState(nic: string): string =
try:
let oper = readFile("/sys/class/net/" & nic & "/operstate")
let state = strip(oper)
return "[" & state & "]"
except:
echo "Error getting operstate for " & nic & " : ", getCurrentExceptionMsg()
return ""
2022-02-26 22:44:00 +01:00
proc getConnState(nic: string): (string, string) =
let state = getOnlineState(nic)
let ip = getIP(nic)
2022-02-26 22:44:00 +01:00
if state == "[down]" or ip == "":
return ("disconnected", state)
return (ip, state)
proc getObject(): Info =
var data = newInfo("IP")
data.selected_bg = default_bg
data.selected_fg = default_fg
# i3bar stuff
data.border = default_bg
2022-02-26 22:44:00 +01:00
return data
proc getNetInfo*(my_nics: seq[string]) =
var my_nic_states: seq[string] = @[]
for nic in my_nics:
let (ip, state) = getConnState(nic)
my_nic_states.add(nic & ":" & state & " " & ip)
let data = getObject()
let args = concat(my_nic_states,@["manage"])
let option = outputData(data, args)
if option in my_nic_states:
discard execCmd(mng_cmd)
case option:
of "manage":
discard execCmd(mng_cmd)
2022-02-26 22:44:00 +01:00
proc getNics*(): seq[string] =
var my_nics: seq[string] = @[]
2022-07-05 14:00:40 +02:00
for nic in os.walkDir("/sys/class/net/"):
let n = replace(nic.path, "/sys/class/net/", "")
my_nics.add(n)
if len(my_nics) > 0:
return my_nics
return @["no-nic"]
2022-02-26 22:44:00 +01:00
proc main() =
getNetInfo(getNics())
2022-02-26 22:44:00 +01:00
if isMainModule:
main()