-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserialportreader.cpp
80 lines (62 loc) · 2.31 KB
/
serialportreader.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
#include "serialportreader.h"
SerialPortReader::SerialPortReader(QSerialPort *serialPort,
QByteArray frameStartMarker,
QByteArray frameEndMarker,
qint16 frameLength, QObject *parent)
: QObject(parent),
frameStartMarker(frameStartMarker),
frameEndMarker(frameEndMarker),
frameLength(frameLength),
serialPort(serialPort) {}
SerialPortReader::SerialPortReader() {}
SerialPortReader::~SerialPortReader() {}
void SerialPortReader::setSerialPort(QSerialPort *serialPort) {
this->serialPort = serialPort;
};
void SerialPortReader::setFrameLength(qint16 frameLength) {
this->frameLength = frameLength;
}
void SerialPortReader::setFrameStartMarker(QByteArray frameStartMarker) {
this->frameStartMarker = frameStartMarker;
};
void SerialPortReader::setFrameEndMarker(QByteArray frameEndMarker) {
this->frameEndMarker = frameEndMarker;
};
void SerialPortReader::start() {
connect(serialPort, &QSerialPort::readyRead, this,
&SerialPortReader::handleReadyRead);
connect(serialPort,
static_cast<void (QSerialPort::*)(QSerialPort::SerialPortError)>(
&QSerialPort::error),
this, &SerialPortReader::handleError);
};
void SerialPortReader::handleReadyRead() {
QByteArray data = serialPort->readAll();
dataBuffer.append(data);
if (dataBuffer.size() < frameLength) {
return; // data to short
}
int indexOfFrame = dataBuffer.indexOf(frameEndMarker + frameStartMarker) +
frameEndMarker.length();
if (indexOfFrame < 0) {
return; // frame marker not found
}
if ((dataBuffer.size() - indexOfFrame) < frameLength) {
return; // frame is not complete
}
QByteArray frame = dataBuffer.mid(indexOfFrame, frameLength);
// Remove processed data from the buffer
dataBuffer = dataBuffer.right(indexOfFrame + frameLength);
// Invoke frameRead signal
frameRead(frame);
}
void SerialPortReader::handleError(
QSerialPort::SerialPortError serialPortError) {
if (serialPortError == QSerialPort::ReadError) {
errorHandler.showMessage(
tr("An I/O error occurred while reading the data from "
"port %1, error: %2")
.arg(serialPort->portName())
.arg(serialPort->errorString()));
}
}