Debian Codegraph @

vicious/widgets/net_linux.lua

raw symbols SCIP
1 -- network status and usage widget type for GNU/Linux
2 -- Copyright (C) 2009 Lucas de Vries <[email protected]>
3 -- Copyright (C) 2010 Adrian C. <[email protected]>
4 -- Copyright (C) 2017 mutlusun <[email protected]>
5 --
6 -- This file is part of Vicious.
7 --
8 -- Vicious is free software: you can redistribute it and/or modify
9 -- it under the terms of the GNU General Public License as
10 -- published by the Free Software Foundation, either version 2 of the
11 -- License, or (at your option) any later version.
12 --
13 -- Vicious is distributed in the hope that it will be useful,
14 -- but WITHOUT ANY WARRANTY; without even the implied warranty of
15 -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 -- GNU General Public License for more details.
17 --
18 -- You should have received a copy of the GNU General Public License
19 -- along with Vicious. If not, see <https://www.gnu.org/licenses/>.
20
21 -- {{{ Grab environment
22 local tonumber = tonumber
23 local os = { time = os.time }
24 local io = { lines = io.lines }
25 local string = { match = string.match }
26 local helpers = require("vicious.helpers")
27 -- }}}
28
29 -- Initialize function tables
30 local nets = {}
31 -- Variable definitions
32 local unit = { ["b"] = 1, ["kb"] = 1024,
33 ["mb"] = 1024^2, ["gb"] = 1024^3
34 }
35
36 -- {{{ Net widget type
37 return helpers.setcall(function ()
38 local args = {}
39
40 -- Get NET stats
41 for line in io.lines("/proc/net/dev") do
42 -- Match wmaster0 as well as rt0 (multiple leading spaces)
43 local name = string.match(line, "^[%s]?[%s]?[%s]?[%s]?([%w]+):")
44 if name ~= nil then
45 -- Received bytes, first value after the name
46 local recv = tonumber(string.match(line, ":[%s]*([%d]+)"))
47 -- Transmited bytes, 7 fields from end of the line
48 local send = tonumber(string.match(line,
49 "([%d]+)%s+%d+%s+%d+%s+%d+%s+%d+%s+%d+%s+%d+%s+%d$"))
50
51 helpers.uformat(args, name .. " rx", recv, unit)
52 helpers.uformat(args, name .. " tx", send, unit)
53
54 -- Operational state and carrier detection
55 local sysnet = helpers.pathtotable("/sys/class/net/" .. name)
56 args["{"..name.." carrier}"] = tonumber(sysnet.carrier) or 0
57
58 local now = os.time()
59 if nets[name] == nil then
60 -- Default values on the first run
61 nets[name] = {}
62 helpers.uformat(args, name .. " down", 0, unit)
63 helpers.uformat(args, name .. " up", 0, unit)
64 else -- Net stats are absolute, substract our last reading
65 local interval = now - nets[name].time
66 if interval <= 0 then interval = 1 end
67
68 local down = (recv - nets[name][1]) / interval
69 local up = (send - nets[name][2]) / interval
70
71 helpers.uformat(args, name .. " down", down, unit)
72 helpers.uformat(args, name .. " up", up, unit)
73 end
74
75 nets[name].time = now
76
77 -- Store totals
78 nets[name][1] = recv
79 nets[name][2] = send
80 end
81 end
82
83 return args
84 end)
85 -- }}}