Posts Tagged ‘lua’
awesome 3.2 battery monitoring widget
Lua code to monitor battery status through thinkpad’s smapi. It generates, e.g., [-] 02:15 (86%) if the battery is 86% full, discharging and has an estimated remaining time of 2 hours 15 mins, [+] 00:30 (50%) if it’s expected to be fully charged in 30 mins, etc. Also, use 100:green:50:yellow:20:red bg color setup. Use with e.g. a textbox widget.
function read_file (path, ...)
-- read a text file and return its content
-- ... can be, e.g., "*n" for a number or "*a" for all, etc.
local f = io.open(path)
local result = f:read(...)
f:close()
return result
end
function format_time(num)
local h,m = math.floor(num/60),num%60
return string.format("%02d:%02d", h,m)
end
function battery_status (bat)
-- bat should be, e.g., BAT0
local path = "/sys/devices/platform/smapi/"
if read_file(path .. bat .. "/installed") == "0" then
-- battery not installed
return "[N/A]"
end
local percent = tonumber(read_file(path .. bat .. "/remaining_percent"))
local state = read_file(path .. bat .. "/state")
local msg
if state == "charging" then
msg = "[+] " .. format_time(
read_file(path .. bat .. "/remaining_charging_time"))
elseif state == "discharging" then
msg = "[-] " .. format_time(
read_file(path .. bat .. "/remaining_running_time"))
elseif state == "idle" then
msg = "[ ]"
else
msg = "*" .. state .. "* "
end
local pre,post
if percent > 50 then
pre,post = '<span font="mono" bgcolor="green" color="black">', '</span>'
elseif percent > 20 then
pre,post = '<span font="mono" bgcolor="yellow" color="black">','</span>'
else
pre,post = '<span font="mono" bgcolor="red" color="yellow">','</span>'
end
return pre .. msg .. " (" .. percent .. "%)" .. post
end
-- print(battery_status("BAT0"))