summaryrefslogtreecommitdiffstats
path: root/src/datasource/networkspeed.cpp
blob: 451c97eb70a8bba8c93c4efd43da2aa38ad220a9 (plain) (blame)
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
#include "networkspeed.h"

NetworkSpeed::NetworkSpeed() :
	_lastBytes(0),
	_lastMs(0),
	_file(nullptr)
{
	for (QString s : QStringList()
		 << "/sys/class/net/boot0/statistics/rx_bytes"
		 << "/sys/class/net/eth0/statistics/rx_bytes"
		 << "/sys/class/net/br0/statistics/rx_bytes") {
		if (!QFile::exists(s))
			continue;
		_file = new QFile(s);
	}
	if (_file != nullptr) {
		_timer.start();
	}
}

NetworkSpeed::~NetworkSpeed()
{
	if (_file != nullptr) {
		_file->deleteLater();
	}
}

qint64 NetworkSpeed::read()
{
	char buffer[500];
	qint64 ret, now;
	if (_file == nullptr || !_file->open(QIODevice::ReadOnly)) {
		return -1;
	}
	now = _timer.elapsed();
	_file->readLine(buffer, sizeof(buffer));
	_file->close();
	QString line(buffer);
	const qint64 counter = (qint64)line.toLongLong();
	if (_lastBytes == 0) {
		ret = 0;
	} else {
		ret = counter - _lastBytes;
	}
	if (_lastMs < now) {
		ret = (ret * 1000) / (now - _lastMs);
	}
	_lastMs = now;
	_lastBytes = counter;
	return ret;
}

const QList<qint64>& NetworkSpeed::getBars() const
{
	static QList<qint64> list = QList<qint64>() << ((qint64)1024 * 1024 * 10);
	return list;
}

qint64 NetworkSpeed::getMaximum()
{
	return ((qint64)1024 * 1024 * 100);
}