Sha256: 83059bc2d232810c4bb2c2dc3fb0460f93e77e6ba7a79795b9dcdc6ae340798f

Contents?: true

Size: 1.04 KB

Versions: 2

Compression:

Stored size: 1.04 KB

Contents

module ServState
  class NetworkUsage

    BYTES_IN_MB = 1048576

    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_MB / time_diff).round(2)
        up_speed   = (up / BYTES_IN_MB / 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

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
ServState-0.1.1 lib/ServState/network_usage.rb
ServState-0.1.0 lib/ServState/network_usage.rb