vicious/net.lua

87 lines
2.7 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) 2010, Henning Glawe <glaweh@debian.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 = { open = io.open }
local setmetatable = setmetatable
local string = {
match = string.match,
format = string.format
}
-- }}}
-- Net: provides usage statistics for all network interfaces
module("vicious.net")
-- Initialise function tables
local nets = {}
2009-11-18 00:05:52 +01:00
-- {{{ Helper functions
local function uformat(array, key, value)
array["{"..key.."_b}"] = string.format("%.1f", value)
array["{"..key.."_kb}"] = string.format("%.1f", value/1024)
array["{"..key.."_mb}"] = string.format("%.1f", value/1024/1024)
array["{"..key.."_gb}"] = string.format("%.1f", value/1024/1024/1024)
return array
end
-- }}}
-- {{{ Net widget type
2009-08-07 17:41:10 +02:00
local function worker(format)
-- Get /proc/net/dev
local f = io.open("/proc/net/dev")
local args = {}
for line in f:lines() do
-- Match wmaster0 as well as rt0 (multiple leading spaces)
2009-10-05 00:10:47 +02:00
if string.match(line, "^[%s]?[%s]?[%s]?[%s]?[%w]+:") then
local name = string.match(line, "^[%s]?[%s]?[%s]?[%s]?([%w]+):")
-- 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$"))
uformat(args, name .. " rx", recv)
uformat(args, name .. " tx", send)
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] = {}
uformat(args, name .. " down", 0)
uformat(args, name .. " up", 0)
nets[name].time = os.time()
else
-- Net stats are absolute, substract our last reading
local interval = os.time() - nets[name].time
nets[name].time = os.time()
local down = (recv - nets[name][1])/interval
local up = (send - nets[name][2])/interval
uformat(args, name .. " down", down)
uformat(args, name .. " up", up)
end
-- Store totals
nets[name][1] = recv
nets[name][2] = send
end
end
f:close()
return args
end
-- }}}
setmetatable(_M, { __call = function(_, ...) return worker(...) end })