vicious/bat.lua

80 lines
2.4 KiB
Lua
Raw Normal View History

2009-09-29 22:33:19 +02:00
---------------------------------------------------
-- Licensed under the GNU General Public License v2
2010-01-02 21:21:54 +01:00
-- * (c) 2010, Adrian C. <anrxc@sysphere.org>
2009-09-29 22:33:19 +02:00
---------------------------------------------------
-- {{{ Grab environment
local tonumber = tonumber
local setmetatable = setmetatable
local string = { format = string.format }
local helpers = require("vicious.helpers")
local math = {
min = math.min,
floor = math.floor
}
-- }}}
-- Batsys: 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)
-- Apple PMU and ACPI/procfs battery widgets are in the [contrib] branch
local battery = helpers.pathtotable("/sys/class/power_supply/" .. batid)
local battery_state = {
["Full\n"] = "",
["Unknown\n"] = "",
["Charged\n"] = "",
["Charging\n"] = "+",
["Discharging\n"] = "-"
}
-- Check if the battery is present
if not battery.present == "1\n" then
return {battery_state["Unknown\n"], 0, "N/A"}
2009-10-04 00:54:27 +02:00
end
2009-10-04 00:54:27 +02:00
-- Get state information
local state = battery_state[battery.status] or battery_state["Unknown\n"]
-- Get capacity information
if battery.charge_now then
remaining, capacity = battery.charge_now, battery.charge_full
elseif battery.energy_now then
remaining, capacity = battery.energy_now, battery.energy_full
else
return {battery_state["Unknown\n"], 0, "N/A"}
end
-- Calculate percentage (but work around broken BAT/ACPI implementations)
local percent = math.min(math.floor(remaining / capacity * 100), 100)
-- Get charge information
if battery.current_now then
rate = battery.current_now
else -- Todo: other rate sources, as with capacity?
return {state, percent, "N/A"}
end
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, "N/A"}
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 })