aboutsummaryrefslogtreecommitdiff
path: root/contrib/sensors.lua
blob: 3ddeb01c324b4e71b6ebb7a5470e843148a26591 (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
---------------------------------------------------
-- Licensed under the GNU General Public License v2
--  * (c) 2010, Greg D. <jabbas@jabbas.pl>
---------------------------------------------------

-- {{{ Grab environment
local tonumber = tonumber
local io = { popen = io.popen }
local setmetatable = setmetatable
local table = { insert = table.insert }
local string = {
    gsub = string.gsub,
    match = string.match
}
-- }}}


-- Sensors: provides access to lm_sensors data
-- vicious.contrib.sensors
local sensors = {}


-- {{{ Split helper function
local function datasplit(str)
    -- Splitting strings into associative array
    -- with some magic to get the values right.
    str = string.gsub(str, "\n", ":")

    local tbl = {}
    string.gsub(str, "([^:]*)", function (v)
        if string.match(v, ".") then
            table.insert(tbl, v)
        end
    end)

    local assoc = {}
    for c = 1, #tbl, 2 do
        local k  = string.gsub(tbl[c], ".*_", "")
        local v  = tonumber(string.match(tbl[c+1], "[%d]+"))
        assoc[k] = v
    end

    return assoc
end
-- }}}

-- {{{ Sensors widget type
local function worker(format, warg)
    -- Get data from all sensors
    local f = io.popen("LANG=C sensors -uA")
    local lm_sensors = f:read("*all")
    f:close()

    local sensor_data = string.gsub(
        string.match(lm_sensors, warg..":\n(%s%s.-)\n[^ ]"), " ", "")

    -- One of: crit, max
    local divisor = "crit"
    local s_data  =  datasplit(sensor_data)

    if s_data[divisor] and s_data[divisor] > 0 then
        s_data.percent = s_data.input / s_data[divisor] * 100
    end

    return {s_data.input, tonumber(s_data.percent)}
end
-- }}}

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