wmtools/battery.nim

102 lines
2.3 KiB
Nim
Raw Normal View History

2022-04-28 21:58:40 +02:00
import base
2022-02-12 16:19:43 +01:00
import strutils
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, string) =
2022-02-12 16:19:43 +01:00
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 main_text = icon & " " & $charge & "%"
2022-02-12 16:19:43 +01:00
let text = "<span foreground=\"" & icon_colour & "\">" & icon & "</span>" & $charge & "%"
return (text,main_text, col, bg, border)
2022-02-12 16:19:43 +01:00
2022-04-28 21:58:40 +02:00
proc get_output(charge: int, state: bool): Info =
let (text,main_text,col,bg_col,bord_col) = get_design(charge, state)
2022-04-28 21:58:40 +02:00
let data = Info(
title: "Battery : ",
full_text: main_text,
html_text: text,
2022-02-12 16:19:43 +01:00
color: col,
border: bord_col,
2022-04-28 21:58:40 +02:00
background: bg_col,
selected_background: bord_col,
selected_color: black
2022-02-12 16:19:43 +01:00
)
return data
proc get_battery_info() =
2022-04-28 13:34:09 +02:00
var last_charge = -1
2022-02-12 16:19:43 +01:00
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
if stoploop:
break
2022-02-12 16:19:43 +01:00
sleep(1000)
proc main() =
if battery_exists():
get_battery_info()
main()