import base import std/[strutils,os] const battery = "BAT0" const ok_fg = lightgreen const default_fg = white const default_bg = black const warning_fg = black const warning_bg = red const low_bg = black const low_fg = red const alert_fg = black const alert_bg = yellow const med_fg = green const med_bg = black proc batteryExists(): bool = try: let state = strip(readFile("/sys/class/power_supply/" & battery & "/present")) if state == "1": return true except: echo "Error getting battery : " & getCurrentExceptionMsg() return false proc isCharging(): bool = try: let state = strip(readFile("/sys/class/power_supply/" & battery & "/status")) if state == "Charging": return true except: echo "Error getting charging status : " & getCurrentExceptionMsg() return false proc getCharge(): int = var charge = 0 try: let chg = strip(readFile("/sys/class/power_supply/" & battery & "/capacity")) if chg != "": charge = parseInt(chg) except: echo "Error getting battery level : " & getCurrentExceptionMsg() return charge proc getDesign(charge: int, state: bool): (string, string, string, string, string) = var icon = " " var icon_colour = ok_fg var col = default_fg var bg = default_bg var border = ok_fg if isCharging(): icon = " " else: case charge: of 0..5: icon_colour = warning_fg col = warning_fg bg = warning_bg of 6..19: icon_colour = low_fg border = low_bg bg = default_bg of 20..39: icon_colour = alert_fg border = alert_bg icon = " " of 40..59: icon_colour = med_fg border= med_fg icon = " " of 60..79: icon_colour = med_fg border = med_fg icon = " " of 80..100: icon_colour = ok_fg border = ok_fg icon = " " else: icon = "x " let main_text = icon & " " & $charge & "%" # This next line is here for i3bar purposes let html_text = "" & icon & "" & $charge & "%" return (html_text,main_text, col, bg, border) proc getOutput(charge: int, state: bool): Info = let (html_text,main_text,col,bg_col,highlight_col) = get_design(charge, state) var data = newInfo("Battery") data.full_text = main_text data.selected_bg = highlight_col data.selected_fg = col # may just want `black` here # i3bar stuff data.html_text = html_text data.color = col data.border = highlight_col data.background = bg_col return data proc getBatteryInfo() = var last_charge = -1 var last_state = false while true: let charge = getCharge() let state = isCharging() if charge != last_charge or state != last_state: let data = getoutput(charge, state) outputData(data) last_charge = charge last_state = state if stoploop: break sleep(1000) proc main() = if batteryExists(): getBatteryInfo() else: switchTwmMode() if isMainModule: main()