summaryrefslogtreecommitdiffstats
path: root/src/consoleworker.cpp
blob: 333504796cde49f6be31e4b45d9ca5a94dbd81f8 (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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#include "consoleworker.h"
#include "copythread.h"
#include "datasource/cpuload.h"
#include "datasource/networkspeed.h"

#include <QFile>
#include <QDateTime>
#include <QCoreApplication>
#include <cstdio>

ConsoleWorker::ConsoleWorker(QString fileName) :
	_thread(nullptr),
	_fileName(fileName),
	_networkSource(nullptr),
	_cpuLoadSource(nullptr),
	_startTimeMs(0)
{
	_timer.setInterval(250);
	connect(&_timer, &QTimer::timeout, this, &ConsoleWorker::updateTimer);
	QTimer::singleShot(1, [this]() {
		QFile *file = new QFile(_fileName);
		if (!file->open(QIODevice::ReadOnly)) {
			puts(tr("Could not open %1 for reading.").arg(_fileName).toLocal8Bit().constData());
			return;
		}
		_networkSource = new NetworkSpeed();
		_cpuLoadSource = new CpuLoad();
		_thread = new CopyThread(file, this);
		connect(_thread, &CopyThread::logMessage, this, &ConsoleWorker::logMessage, Qt::QueuedConnection);
		connect(_thread, &CopyThread::finished, this, &ConsoleWorker::testFinished, Qt::QueuedConnection);
		_timer.start();
		_thread->start();
	});
}

ConsoleWorker::~ConsoleWorker()
{
	delete _networkSource;
	delete _cpuLoadSource;
}

void ConsoleWorker::logMessage(CopyThread::LogMessageId msgId, QString message)
{
	if (msgId == CopyThread::TestSequentialStart) {
		_startTimeMs = QDateTime::currentMSecsSinceEpoch();
	} else if (msgId == CopyThread::TestRandomStart) {
		printf("+SEQ:%lld", (long long)_startTimeMs);
		_startTimeMs = QDateTime::currentMSecsSinceEpoch();
	} else if (msgId == CopyThread::TestFinished) {
		printf("+RND:%lld", (long long)_startTimeMs);
	}
	if (msgId == CopyThread::TestRandomStart || msgId == CopyThread::TestFinished) {
		for (const auto& i : _series) {
			printf(",%s", i.toLocal8Bit().constData());
		}
		putchar('\n');
	}
	_series.clear();
	puts(message.toLocal8Bit().constData());
}

void ConsoleWorker::testFinished()
{
	_timer.stop();
	delete _thread;
	_thread = NULL;
	QCoreApplication::instance()->quit();
}

void ConsoleWorker::updateTimer()
{
	int net = (int)_networkSource->read();
	int cpu = (int)_cpuLoadSource->read();
	int t = (int)(QDateTime::currentMSecsSinceEpoch() - _startTimeMs);
	_series.append(QString::asprintf("%d+%d+%d", t, net, cpu));
}