vicious/bat.lua

84 lines
2.5 KiB
Lua
Raw Normal View History

2009-09-29 22:33:19 +02:00
---------------------------------------------------
-- Licensed under the GNU General Public License v2
-- * (c) 2009, Adrian C. <anrxc.sysphere.org>
---------------------------------------------------
-- {{{ Grab environment
local tonumber = tonumber
local io = { open = io.open }
local setmetatable = setmetatable
local math = { floor = math.floor }
local string = {
find = string.find,
match = string.match,
format = string.format
}
-- }}}
-- Bat: provides state, charge, and remaining time for a requested battery
module("vicious.bat")
-- {{{ Battery widget type
2009-08-07 17:41:10 +02:00
local function worker(format, batid)
local battery_state = {
["full"] = "",
["unknown"] = "",
["charged"] = "",
["charging"] = "+",
["discharging"] = "-"
}
-- Get /proc/acpi/battery info
2009-10-02 20:33:58 +02:00
local f = io.open("/proc/acpi/battery/"..batid.."/info")
-- Handler for incompetent users
if not f then return {"/", "/", "/"} end
2009-10-02 20:33:58 +02:00
local infofile = f:read("*all")
f:close()
-- Check if the battery is present
if infofile == nil or string.find(infofile, "present:[%s]+no") then
2009-07-30 20:47:02 +02:00
return {"/", "/", "/"}
2009-10-04 00:54:27 +02:00
end
2009-10-04 00:54:27 +02:00
-- Get capacity information
local capacity = string.match(infofile, "last full capacity:[%s]+([%d]+).*")
2009-10-04 00:54:27 +02:00
-- Get /proc/acpi/battery state
local f = io.open("/proc/acpi/battery/"..batid.."/state")
local statefile = f:read("*all")
f:close()
2009-10-04 00:54:27 +02:00
-- Get state information
local state = string.match(statefile, "charging state:[%s]+([%a]+).*")
local state = battery_state[state] or battery_state["unknown"]
2009-10-04 00:54:27 +02:00
-- Get charge information
local rate = string.match(statefile, "present rate:[%s]+([%d]+).*")
local remaining = string.match(statefile, "remaining capacity:[%s]+([%d]+).*")
2009-10-04 00:54:27 +02:00
-- Calculate percentage
local percent = math.floor(remaining / capacity * 100)
local percent = string.format("%02d", percent)
2009-10-04 00:54:27 +02:00
-- Calculate remaining (charging or discharging) time
if state == "+" then
timeleft = (tonumber(capacity) - tonumber(remaining)) / tonumber(rate)
elseif state == "-" then
timeleft = tonumber(remaining) / tonumber(rate)
else
return { state, percent, "/" }
end
2009-10-04 00:54:27 +02:00
local hoursleft = math.floor(timeleft)
local minutesleft = math.floor((timeleft - hoursleft) * 60 )
local time = string.format("%02d:%02d", hoursleft, minutesleft)
return {state, percent, time}
end
-- }}}
setmetatable(_M, { __call = function(_, ...) return worker(...) end })