module ServState class NetworkUsage BYTES_IN_KB = 1024 attr_reader :speeds def update time_diff = Time.new - @old_time @old_time = Time.new data = net_data data.each do |interface, values| down = values[0] - @old_traffic[interface][0] up = values[1] - @old_traffic[interface][1] down_speed = (down / BYTES_IN_KB / time_diff).round(2) up_speed = (up / BYTES_IN_KB / time_diff).round(2) @speeds[interface] = [down_speed, up_speed] end @old_traffic = data end private def initialize @speeds = Hash.new @old_time = Time.new @old_traffic = net_data update end # returns hash with hash[:interface] = [total download bytes, total upload bytes] def net_data # now we have two problems output = `ip -s link`.split("\n").grep(/([0-9]:\ )|(([0-9]+\ +){6})/) data = Hash.new output.each_cons(3) do |lines| if lines[0] =~ /^[0-9]:/ name = lines[0].split[1].chop down = lines[1].split[0].to_i up = lines[2].split[0].to_i data[name] = [down, up] end end data end end end