-
Notifications
You must be signed in to change notification settings - Fork 3
/
serialthread.cpp
254 lines (209 loc) · 7.41 KB
/
serialthread.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
/*
serialthread.cpp (part of GNSS-Stylus)
Copyright (C) 2019-2021 Pasi Nuutinmaki (gnssstylist<at>sci<dot>fi)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
/**
* @file serialthread.cpp
* @brief Definitions for a class handling serial communication.
*/
//#include <memory>
#include <QElapsedTimer>
#include "serialthread.h"
SerialThread::SerialThread(const QString& serialPortFileName,
const unsigned int charTimeout,
const unsigned int maxReadDataSize,
const unsigned int serialPortBPS)
: QThread()
{
this->serialPortFileName = serialPortFileName;
this->charTimeout = charTimeout;
this->maxReadDataSize = maxReadDataSize;
this->serialPortBPS = serialPortBPS;
terminateRequest = false;
suspended = false;
}
SerialThread::~SerialThread()
{
terminateRequest = true;
this->wait(5000);
}
static const QString serialPortErrors[] =
{
"NoError",
"DeviceNotFoundError",
"PermissionError",
"OpenError",
"ParityError",
"FramingError",
"BreakConditionError",
"WriteError",
"ReadError",
"ResourceError",
"UnsupportedOperationError",
"UnknownError",
"TimeoutError",
"NotOpenError"
};
void SerialThread::run()
{
QSerialPort serialPort;
serialPort.setPortName(serialPortFileName);
serialPort.setBaudRate(serialPortBPS);
serialPort.setDataBits(QSerialPort::Data8);
serialPort.setFlowControl(QSerialPort::NoFlowControl);
serialPort.setParity(QSerialPort::NoParity);
serialPort.setStopBits(QSerialPort::OneStop);
while (!terminateRequest)
{
// Try to open serial port
do
{
if (suspended && !terminateRequest)
{
emit infoMessage("Suspending...");
while (suspended && !terminateRequest)
{
msleep(100);
}
if (!terminateRequest)
{
emit infoMessage("Resuming...");
}
}
emit infoMessage("Opening serial port \"" + serialPortFileName + "\"...");
if (!serialPort.open(QIODevice::ReadWrite))
{
QSerialPort::SerialPortError error = serialPort.error();
if (error < sizeof(serialPortErrors) / sizeof(serialPortErrors[0]))
{
emit errorMessage("Can't open serial port\"" + serialPortFileName + "\". Reason: " + serialPortErrors[error] + ". Trying again after 1 s...");
}
else
{
emit errorMessage("Can't open serial port\"" + serialPortFileName + "\", error " + QString::number(error) + ". Trying again after 1 s...");
}
sleep(1);
}
} while ((!serialPort.isOpen()) && !terminateRequest);
if (!terminateRequest)
{
flushReceiveBuffer(&serialPort);
sendMutex.lock();
sendQueue.clear();
sendMutex.unlock();
emit infoMessage("Entering main loop.");
}
QElapsedTimer lastByteReceivedTimer;
QElapsedTimer dataStartTimer;
while (!terminateRequest)
{
char readBuffer[256];
qint64 BytesRead;
unsigned long bytesToRead = sizeof(readBuffer);
if (bytesToRead > maxReadDataSize - static_cast<unsigned int>(receiveBuffer.length()))
{
bytesToRead = maxReadDataSize - static_cast<unsigned int>(receiveBuffer.length());
}
if ((serialPort.bytesAvailable() != 0) || (serialPort.waitForReadyRead(1)))
{
// Data is ready to be read
lastByteReceivedTimer.start();
if (receiveBuffer.length() == 0)
{
// No bytes received in this "burst" -> Store the starting time
dataStartTimer.start();
}
BytesRead = serialPort.read(readBuffer, bytesToRead);
if (BytesRead > 0)
{
// Bytes received -> Add them to the buffer
receiveBuffer.append(readBuffer, static_cast<int>(BytesRead));
if (static_cast<unsigned int>(receiveBuffer.length()) >= maxReadDataSize)
{
emit dataReceived(receiveBuffer, dataStartTimer.msecsSinceReference(), lastByteReceivedTimer.msecsSinceReference(), MAX_BYTES);
receiveBuffer.clear();
}
}
}
if (lastByteReceivedTimer.elapsed() >= charTimeout)
{
if (receiveBuffer.length() != 0)
{
// Byte not received inside the timeout
// -> Emit any bytes already received
emit dataReceived(receiveBuffer, dataStartTimer.msecsSinceReference(), lastByteReceivedTimer.msecsSinceReference(), TIMEOUT);
receiveBuffer.clear();
// Also emit timeout
emit serialTimeout();
}
sendMutex.lock();
// Send any pending data from queue
while(!sendQueue.isEmpty())
{
QByteArray sendArray = sendQueue.dequeue();
sendMutex.unlock();
serialPort.write(sendArray);
sendMutex.lock();
}
sendMutex.unlock();
lastByteReceivedTimer.start();
}
if (suspended && !terminateRequest)
{
emit infoMessage("Suspending...");
while (suspended && !terminateRequest)
{
sendMutex.lock();
sendQueue.clear();
sendMutex.unlock();
msleep(100);
}
if (!terminateRequest)
{
emit infoMessage("Resuming...");
flushReceiveBuffer(&serialPort);
}
}
} // while (!terminateRequest)
} // while (!terminateRequest)
serialPort.close();
emit infoMessage("Thread terminated.");
}
void SerialThread::flushReceiveBuffer(QSerialPort* serialPort)
{
while (serialPort->bytesAvailable() != 0)
{
serialPort->read(256);
}
receiveBuffer.clear();
}
void SerialThread::addToSendQueue(const QByteArray& dataToSend)
{
if (!terminateRequest)
{
QMutexLocker locker(&sendMutex);
sendQueue.enqueue(dataToSend);
}
}
void SerialThread::suspend(void)
{
suspended = true;
}
void SerialThread::resume(void)
{
suspended = false;
}
void SerialThread::requestTerminate(void)
{
terminateRequest = true;
}