vicious/widgets/net.lua

80 lines
2.6 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>
-- * (c) 2009, Lucas de Vries <lucas@glacicle.com>
2009-09-29 22:33:19 +02:00
---------------------------------------------------
-- {{{ Grab environment
local tonumber = tonumber
local os = { time = os.time }
local io = { lines = io.lines }
local setmetatable = setmetatable
local string = { match = string.match }
local helpers = require("vicious.helpers")
-- }}}
2010-07-19 02:12:00 +02:00
-- Net: provides state and usage statistics of all network interfaces
module("vicious.widgets.net")
-- Initialize function tables
local nets = {}
-- Variable definitions
local unit = { ["b"] = 1, ["kb"] = 1024,
["mb"] = 1024^2, ["gb"] = 1024^3
}
2009-11-18 00:05:52 +01:00
-- {{{ Net widget type
2009-08-07 17:41:10 +02:00
local function worker(format)
local args = {}
-- Get NET stats
for line in io.lines("/proc/net/dev") do
-- Match wmaster0 as well as rt0 (multiple leading spaces)
2010-03-12 04:21:11 +01:00
local name = string.match(line, "^[%s]?[%s]?[%s]?[%s]?([%w]+):")
if name ~= nil then
-- Received bytes, first value after the name
2009-10-05 00:10:47 +02:00
local recv = tonumber(string.match(line, ":[%s]*([%d]+)"))
2009-11-15 02:00:14 +01:00
-- Transmited bytes, 7 fields from end of the line
local send = tonumber(string.match(line,
"([%d]+)%s+%d+%s+%d+%s+%d+%s+%d+%s+%d+%s+%d+%s+%d$"))
helpers.uformat(args, name .. " rx", recv, unit)
helpers.uformat(args, name .. " tx", send, unit)
2010-07-19 02:12:00 +02:00
-- Operational state and carrier detection
local sysnet = helpers.pathtotable("/sys/class/net/" .. name)
args["{"..name.." carrier}"] = tonumber(sysnet.carrier) or 0
2011-08-18 19:59:11 +02:00
local now = os.time()
2010-01-02 22:51:34 +01:00
if nets[name] == nil then
2009-09-14 17:25:23 +02:00
-- Default values on the first run
nets[name] = {}
helpers.uformat(args, name .. " down", 0, unit)
helpers.uformat(args, name .. " up", 0, unit)
else -- Net stats are absolute, substract our last reading
2011-08-18 19:59:11 +02:00
local interval = now - nets[name].time
if interval < 0 then interval = 1 end
local down = (recv - nets[name][1]) / interval
local up = (send - nets[name][2]) / interval
helpers.uformat(args, name .. " down", down, unit)
helpers.uformat(args, name .. " up", up, unit)
end
2011-08-18 19:59:11 +02:00
nets[name].time = now
-- Store totals
nets[name][1] = recv
nets[name][2] = send
end
end
return args
end
-- }}}
setmetatable(_M, { __call = function(_, ...) return worker(...) end })