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_dev_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_dev_data end # returns hash with hash[:interface] = [total download bytes, total upload bytes] def net_dev_data lines = IO.readlines('/proc/net/dev').grep(/:/) data = Hash.new lines.each do |line| splited = line.split data[splited[0].chop.to_sym] = [splited[1].to_i, splited[9].to_i] end data end end end