This repository has been archived by the owner on Mar 3, 2020. It is now read-only.
/
CommandParser.cpp
76 lines (67 loc) · 1.86 KB
/
CommandParser.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
#include "CommandParser.h"
#include "CommandFactory.h"
#include "SocketCommand.h"
#include <QIODevice>
CommandParser::CommandParser(QIODevice *device, CommandFactory *commandFactory, QObject *parent) :
QObject(parent) {
m_device = device;
m_expectingDataSize = -1;
m_commandFactory = commandFactory;
connect(m_device, SIGNAL(readyRead()), this, SLOT(checkNext()));
}
void CommandParser::checkNext() {
if (m_expectingDataSize == -1) {
if (m_device->canReadLine()) {
readLine();
checkNext();
}
} else {
if (m_device->bytesAvailable() >= m_expectingDataSize) {
readDataBlock();
checkNext();
}
}
}
void CommandParser::readLine() {
char buffer[128];
qint64 lineLength = m_device->readLine(buffer, 128);
if (lineLength != -1) {
buffer[lineLength - 1] = 0;
processNext(buffer);
}
}
void CommandParser::readDataBlock() {
char *buffer = new char[m_expectingDataSize + 1];
m_device->read(buffer, m_expectingDataSize);
buffer[m_expectingDataSize] = 0;
processNext(buffer);
m_expectingDataSize = -1;
delete[] buffer;
}
void CommandParser::processNext(const char *data) {
if (m_commandName.isNull()) {
m_commandName = data;
m_argumentsExpected = -1;
} else {
processArgument(data);
}
}
void CommandParser::processArgument(const char *data) {
if (m_argumentsExpected == -1) {
m_argumentsExpected = QString(data).toInt();
} else if (m_expectingDataSize == -1) {
m_expectingDataSize = QString(data).toInt();
} else {
m_arguments.append(QString::fromUtf8(data));
}
if (m_arguments.length() == m_argumentsExpected) {
Command *command = m_commandFactory->createCommand(m_commandName.toLatin1().constData(), m_arguments);
emit commandReady(command);
reset();
}
}
void CommandParser::reset() {
m_commandName = QString();
m_arguments.clear();
m_argumentsExpected = -1;
}