Debian Codegraph @

obvious/net/init.lua

raw symbols SCIP
1 -----------------------------------
2 -- Author: Uli Schlachter --
3 -- Copyright 2009 Uli Schlachter --
4 -----------------------------------
5
6 local io = io
7 local tonumber = tonumber
8 local lib = {
9 widget = require("obvious.lib.widget")
10 }
11
12 -- Returns the total traffic send/received on some interface
13 local function netinfo(interface)
14 local net = io.open("/proc/net/dev")
15 local ret = { }
16
17 -- Init in case we don't find any matches
18 ret.recv = 0
19 ret.send = 0
20
21 for line in net:lines() do
22 if line:match("^%s+" .. interface) then
23 ret.recv = tonumber(line:match(":%s*(%d+)"))
24 ret.send = tonumber(line:match("(%d+)%s+%d+%s+%d+%s+%d+%s+%d+%s+%d+%s+%d+$"))
25 end
26 end
27 net:close()
28 return ret
29 end
30
31 local function get_data(object)
32 local last = object.last
33 local cur = netinfo(object.device)
34 object.last = cur
35
36 local ret = { }
37 if last then
38 ret.recv = cur.recv - last.recv
39 ret.send = cur.send - last.send
40 else
41 ret.recv = 0
42 ret.send = 0
43 end
44
45 -- This can happen e.g. when an interface is brought down and up again
46 -- or when some counter overflows
47 if ret.recv < 0 then
48 ret.recv = 0
49 end
50 if ret.send < 0 then
51 ret.send = 0
52 end
53
54 return ret
55 end
56
57 local function data(device, key)
58 local device = device or "eth0"
59 local ret = {}
60
61 ret.device = device
62 ret.get = function(obj)
63 return get_data(obj)[key]
64 end
65
66 return lib.widget.from_data_source(ret)
67 end
68
69 local function recv(device)
70 return data(device, "recv")
71 end
72
73 local function send(device)
74 return data(device, "send")
75 end
76
77 return {
78 recv = recv,
79 send = send,
80 }
81
82 -- vim:ft=lua:ts=2:sw=2:sts=2:tw=80:et