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
|
/*
* Copyright (C) 2016 Dhiraj Salian
*
* 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 2
* 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, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Suite 500, Boston, MA 02110-1335, USA.
*/
#include "SerialCom.hpp"
#include <QtSerialPort/QSerialPort>
#include <QTime>
QT_USE_NAMESPACE
/**
Constructor:
*/
SerialCom::SerialCom(QObject *parent)
: QThread(parent), waitTime(0), quit(false)
{
}
/**
Destructor:
*/
SerialCom::~SerialCom()
{
mutex.lock();
quit = true;
cond.wakeOne();
mutex.unlock();
wait();
}
/**
sendRequest(const QString, int, const QString):
Send a request to arduino
*/
void SerialCom::sendRequest(const QString &port, int waitTime, const QString &request)
{
QMutexLocker locker(&mutex);
this->port = port;
this->waitTime = waitTime;
this->request = request;
if (!isRunning())
start();
else
cond.wakeOne();
}
void SerialCom::run()
{
bool myPortNameChanged = false;
mutex.lock();
QString myPortName;
if (myPortName != port) {
myPortName = port;
myPortNameChanged = true;
}
int myWaitTimeout = waitTime;
QString myRequest = request;
mutex.unlock();
QSerialPort serial;
while (!quit) {
if (myPortNameChanged) {
serial.close();
serial.setPortName(myPortName);
if (!serial.open(QIODevice::ReadWrite)) {
emit error(tr("Can't open %1, error code %2")
.arg(port).arg(serial.error()));
return;
}
}
QByteArray requestData = myRequest.toLocal8Bit();
serial.write(requestData);
if (serial.waitForBytesWritten(waitTime)) {
if (serial.waitForReadyRead(myWaitTimeout)) {
QByteArray responseData = serial.readAll();
while (serial.waitForReadyRead(10))
responseData += serial.readAll();
QString response(responseData);
emit this->response(response);
} else {
emit timeout(tr("Wait Read Request Timed Out %1")
.arg(QTime::currentTime().toString()));
}
} else {
emit timeout(tr("Wait Write Request Timed Out %1")
.arg(QTime::currentTime().toString()));
}
mutex.lock();
cond.wait(&mutex);
if (myPortName != port) {
myPortName = port;
myPortNameChanged = true;
} else {
myPortNameChanged = false;
}
myWaitTimeout = waitTime;
myRequest = request;
mutex.unlock();
}
}
|