-
Notifications
You must be signed in to change notification settings - Fork 1
/
NetworkWidget.cpp
82 lines (76 loc) · 1.95 KB
/
NetworkWidget.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#include "NetworkWidget.h"
#include <iostream>
#include <math.h>
#include <QFile>
#include <QTextStream>
NetworkWidget::NetworkWidget(QLabel* l) : interface("eth0"), down(true), lastbytes(0)
{
label = l;
}
void NetworkWidget::Update()
{
if (GetFile("/proc/net/dev") == "/proc/net/dev")
DoUpdate();
}
void NetworkWidget::DoUpdate()
{
QFile f(QString(GetFile("/proc/net/dev", false).c_str()));
f.open(QIODevice::ReadOnly);
QTextStream stream(&f);
QString contents = stream.readAll();
f.close();
contents.replace(":", " ");
contents.replace("\n", " ");
size_t val = 0;
QStringList l = contents.split(" ", QString::SkipEmptyParts);
for (size_t i = 0; i < l.length(); ++i)
{
if (l[i].toStdString() == interface)
{
if (down)
{
// On 32-bit archs it's possible to overflow size_t, so truncate to only the
// last nine digits. If you need to be able to measure more than a gigabyte of
// bandwidth, switch to 64-bits. :-)
if (sizeof(val) > 4)
val = l[i + 1].toULong();
else
val = l[i + 1].right(9).toULong();
}
else
{
if (sizeof(val) > 4)
val = l[i + 9].toULong();
else
val = l[i + 9].right(9).toULong();
}
break;
}
}
size_t currbytes = val;
int elapsed = timer.restart();
float rate = (currbytes - lastbytes) / (float(elapsed) / 1000.f) / float(KB());
rate = floor(rate * 10.f) / 10.f;
lastbytes = currbytes;
float percent = rate / max;
if (type == Text)
{
QString qrate;
qrate.setNum(rate);
QString text = format;
text.replace("%s", qrate);
SetText(text);
}
else if (type == Image)
{
SetLabelMask(percent);
}
else if (type == Graph)
{
DrawGraph(percent);
}
}
void NetworkWidget::ProcessFinished(QString)
{
DoUpdate();
}