wmtools/i3bar_battery.nim

95 lines
2.1 KiB
Nim
Executable file

import i3bar_base
import strutils
import std/times
import std/os
proc battery_exists(): bool =
let state = strip(readFile("/sys/class/power_supply/BAT0/present"))
if state == "1":
return true
return false
proc is_charging(): bool =
let state = strip(readFile("/sys/class/power_supply/BAT0/status"))
case state:
of "Charging":
return true
else:
return false
proc get_charge(): int =
var charge = 0
let chg = strip(readFile("/sys/class/power_supply/BAT0/capacity"))
if chg != "":
charge = parseInt(chg)
return charge
proc get_design(charge: int, state: bool): (string, string, string, string) =
var icon = ""
var icon_colour = lightgreen
var col = foreground
var bg = black
var border = lightgreen
if is_charging():
icon = ""
else:
case charge:
of 0..5:
icon_colour = black
col = black
bg = red
of 6..19:
icon_colour = alert
border = alert
of 20..39:
icon_colour = yellow
border = yellow
icon = ""
of 40..59:
icon_colour = green
border= green
icon = ""
of 60..79:
icon_colour = green
border= green
icon = ""
of 80..100:
icon_colour = lightgreen
border = lightgreen
icon = ""
else:
icon = "x "
let text = "<span foreground=\"" & icon_colour & "\">" & icon & "</span>" & $charge & "%"
return (text, col, bg, border)
proc get_output(charge: int, state: bool): i3barData =
let (text,col,bg_col,bord_col) = get_design(charge, state)
let data = i3barData(
full_text: text,
color: col,
border: bord_col,
background: bg_col
)
return data
proc get_battery_info() =
var last_charge = -1
var last_state = false
while true:
let charge = get_charge()
let state = is_charging()
if charge != last_charge or state != last_state:
let data = get_output(charge, state)
outputJSON(data)
last_charge = charge
last_state = state
sleep(1000)
proc main() =
if battery_exists():
get_battery_info()
main()