-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathSerialPortThread.cpp
More file actions
120 lines (106 loc) · 3.11 KB
/
SerialPortThread.cpp
File metadata and controls
120 lines (106 loc) · 3.11 KB
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
#include "serialportthread.h"
#include<QTime>
SerialPortThread::SerialPortThread(QObject *parent)
: QThread(parent), waitTimeout(0), quit(false)
{
//connect(this,SIGNAL(response(QString)),this,SLOT(Response(QString)));
}
SerialPortThread::~SerialPortThread()
{
mutex.lock();
quit = true;
mutex.unlock();
wait();
}
void SerialPortThread::run()
{
QString currentRequset;
int currentWaitTimeout;
//程序不会有重复开关的动作,因此这里不需要锁资源
bool result = serialPort.open(QSerialPort::ReadWrite);
if(!result){
emit error(tr("无法打开串口: %1, 错误代码: %2")
.arg(portName).arg(serialPort.error()));
return;
}
while(!quit)
{
mutex.lock();
currentRequset=request;
currentWaitTimeout=waitTimeout;
mutex.unlock();
mutex.lock();
if(!request.isEmpty()){
// 写请求
QByteArray requestData = currentRequset.toLocal8Bit();
serialPort.write(requestData);
if (serialPort.waitForBytesWritten(currentWaitTimeout)) ;
else {
//写请求超时
emit timeout(tr("写入操作超时: %1")
.arg(QTime::currentTime().toString()));
}
}
mutex.unlock();
mutex.lock();
// 读取返回
if(serialPort.isReadable()){
if (serialPort.waitForReadyRead(currentWaitTimeout)) {
QByteArray responseData = serialPort.readAll();
while (serialPort.waitForReadyRead(10))
responseData += serialPort.readAll();
QString response(responseData);
emit this->response(response);
} else {
emit timeout(tr("读取超时Q: %1")
.arg(QTime::currentTime().toString()));
}
}
mutex.unlock();
}
serialPort.close();
}
bool SerialPortThread::isSerialAreadyOpened()
{
return this->isRunning();
}
void SerialPortThread::Open(const QString &portName,
QSerialPort::BaudRate baudRate,
QSerialPort::Parity parity,
QSerialPort::DataBits dataBit,
QSerialPort::StopBits stopBits)
{
if(!this->serialPort.isOpen()){
this->serialPort.setPortName(portName);
this->serialPort.setBaudRate(baudRate);
this->serialPort.setParity(parity);
this->serialPort.setDataBits(dataBit);
this->serialPort.setStopBits(stopBits);
}
this->start();
}
void SerialPortThread::writeData(const QString &s)
{
if(this->isRunning())
Request(s);
}
void SerialPortThread::writeData(const QByteArray &s)
{
if(this->isRunning())
Request(s);
}
void SerialPortThread::Stop()
{
mutex.lock();
quit = true;
mutex.unlock();
wait();
}
void SerialPortThread::Request(const QString &request)
{
QMutexLocker m(&mutex);
if (isRunning())
this->request=request;
else
emit error("串口已打开");
}