-
Notifications
You must be signed in to change notification settings - Fork 3
/
qAsyncSerial.cpp
99 lines (88 loc) · 2.37 KB
/
qAsyncSerial.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
/**
* Author: Terraneo Federico
* Distributed under the Boost Software License, Version 1.0.
*/
#include "qAsyncSerial.h"
#include "asyncSerial.h"
#include <QStringList>
#include <QRegExp>
#include <QDebug>
/**
* Implementation details of QAsyncSerial class.
*/
class QAsyncSerialImpl
{
public:
CallbackAsyncSerial serial;
QString receivedData;
};
QAsyncSerial::QAsyncSerial(): pimpl(new QAsyncSerialImpl){
qDebug() << "QAsyncSerial::QAsyncSerial()";
}
QAsyncSerial::QAsyncSerial(QString devname, unsigned int baudrate) : pimpl(new QAsyncSerialImpl){
open(devname,baudrate);
}
void QAsyncSerial::open(QString devname, unsigned int baudrate)
{
qDebug() << "QAsyncSerial::open()";
try {
pimpl->serial.open(devname.toStdString(),baudrate);
} catch(boost::system::system_error&)
{
//Errors during open
}
pimpl->serial.setCallback(bind(&QAsyncSerial::readCallback,this, _1, _2));
}
void QAsyncSerial::close()
{
qDebug() << "QAsyncSerial::close()";
pimpl->serial.clearCallback();
try {
pimpl->serial.close();
} catch(boost::system::system_error&)
{
//Errors during port close
}
pimpl->receivedData.clear();//Clear eventual data remaining in read buffer
}
bool QAsyncSerial::isOpen()
{
return pimpl->serial.isOpen();
}
bool QAsyncSerial::errorStatus()
{
return pimpl->serial.errorStatus();
}
void QAsyncSerial::write(QString data)
{
pimpl->serial.writeString(data.toStdString());
}
QAsyncSerial::~QAsyncSerial()
{
pimpl->serial.clearCallback();
try {
pimpl->serial.close();
} catch(...)
{
//Don't throw from a destructor
}
}
void QAsyncSerial::readCallback(const char *data, size_t size)
{
qDebug() << "readCallback()";
pimpl->receivedData+=QString::fromLatin1(data, size);
if(pimpl->receivedData.contains('\n'))
{
QStringList lineList=pimpl->receivedData.split(QRegExp("\r\n|\n"));
//If line ends with \n lineList will contain a trailing empty string
//otherwise it will contain part of a line without the terminating \n
//In both cases lineList.at(lineList.size()-1) should not be sent
//with emit.
int numLines=lineList.size()-1;
pimpl->receivedData=lineList.at(lineList.size()-1);
for(int i=0;i<numLines;i++)
{
Q_EMIT lineReceived(lineList.at(i));
}
}
}