aboutsummaryrefslogtreecommitdiff
path: root/bat.lua
blob: ba298943d89843d9a09597db1b9b625d68815ac5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
----------------------------------------------------------
-- Licensed under the GNU General Public License version 2
--  * Copyright (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
local function worker(format, batid)
    local battery_state = {
        ["full"] = "↯",
        ["unknown"] = "⌁",
        ["charged"] = "↯",
        ["charging"] = "+",
        ["discharging"] = "-"
    }

    -- Get /proc/acpi/battery info
    local finfo = io.open("/proc/acpi/battery/"..batid.."/info")
    local infofile = finfo:read("*all")
    finfo:close()

    -- Check if the file wasn't found or the battery isn't present
    if infofile == nil or string.find(infofile, "present:[%s]+no") then
        return {"/", "/", "/"}
    else
        -- Get capacity information
        local capacity = string.match(infofile, "last full capacity:[%s]+([%d]+).*")


        -- Get /proc/acpi/battery state
        local fstate = io.open("/proc/acpi/battery/"..batid.."/state")
        local statefile = fstate:read("*all")
        fstate:close()

        -- Get state information
        local state = string.match(statefile, "charging state:[%s]+([%a]+).*")
        local state = battery_state[state] or battery_state["unknown"]

        -- Get charge information
        local rate = string.match(statefile, "present rate:[%s]+([%d]+).*")
        local remaining = string.match(statefile, "remaining capacity:[%s]+([%d]+).*")


        -- Calculate percentage
        local percent = math.floor(remaining / capacity * 100)
        local percent = string.format("%02d", percent)

        -- 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
        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
end
-- }}}

setmetatable(_M, { __call = function(_, ...) return worker(...) end })