Logo Search packages:      
Sourcecode: karamba version File versions  Download package

networksensor.cpp

/***************************************************************************
 *   Copyright (C) 2003 by Hans Karlsson                                   *
 *   karlsson.h@home.se                                                      *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 ***************************************************************************/
#include "networksensor.h"

NetworkSensor::NetworkSensor( QString dev, int interval ):Sensor( interval )
{
   device = dev.lower();
   if( device == "" )
      device = "eth0";

     getInOutBytes(receivedBytes,transmittedBytes);
    netTimer.start();

}
NetworkSensor::~NetworkSensor()
{
}
void NetworkSensor::getInOutBytes ( unsigned long &in,unsigned long &out) const
{
    QFile file("/proc/net/dev");
    QString line;
    if ( file.open(IO_ReadOnly | IO_Translate) )
    {
        QTextStream t( &file );        // use a text stream
        line = t.readLine();
        while(line !=0 && !line.contains(device))
        {
            line = t.readLine();
        }
        if ( line.contains( device ) )
        {
            QRegExp rx( "\\W+"+device+":\\D*(\\d+)(?:\\D+\\d+){7}\\D+(\\d+)", false);
            rx.search(line);
            in = rx.cap(1).toULong();
            out = rx.cap(2).toULong();
       }
        else
        {
            qDebug("Network sensor: can not find " + device );
            in = 0;
            out = 0;
        }
    file.close();
    }
}

void NetworkSensor::update()
{
    SensorParams *sp;
    Meter *meter;
    QObjectListIt it( *objList );
    QString format;
    int decimals;

    unsigned long inB, outB;
    const double delay = (double) netTimer.elapsed(); // msec elapsed since last update
    getInOutBytes( inB, outB );
    netTimer.restart();

    while( it != 0 )
    {
        sp = (SensorParams*)(*it);
        meter = sp->getMeter();
        format = sp->getParam( "FORMAT" );
      decimals = ( sp->getParam( "DECIMALS" ) ).toInt();
        if (format.length() == 0 )
        {
            format = "%in";
        }

        format.replace( QRegExp("%in", false), QString::number( (inB - receivedBytes)/delay, 'f', decimals ) );
        format.replace( QRegExp("%out", false), QString::number( (outB - transmittedBytes)/delay, 'f', decimals ) );

        meter->setValue( format );
        ++it;
    }
    receivedBytes = inB;
    transmittedBytes = outB;
}

Generated by  Doxygen 1.6.0   Back to index