-
Notifications
You must be signed in to change notification settings - Fork 0
/
serialinput.cpp
107 lines (88 loc) · 2.76 KB
/
serialinput.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
#include "serialinput.h"
#include <QtSerialPort/QSerialPort>
#include <QtSerialPort/QSerialPortInfo>
SerialInput::SerialInput(): serial(0){
}
QString SerialInput::SelectSerialPort()
{
foreach (const QSerialPortInfo &info, QSerialPortInfo::availablePorts()) {
if( info.portName().contains("USB") )
if( !info.isBusy() )
return info.portName();
}
return "";
}
void SerialInput::Open(QString portName)
{
if( serial )
{
serial->close();
}
else
{
serial = new QSerialPort(this);
}
serial->setPortName(portName);
if (!serial->open(QIODevice::ReadWrite)) {
emit error(tr("Can't open '%1', error code %2")
.arg(portName).arg(serial->error()));
return;
}
if (!serial->setBaudRate(QSerialPort::Baud115200)) {
emit error(tr("Can't set baud rate 115200 baud to port %1, error code %2")
.arg(portName).arg(serial->error()));
return;
}
if (!serial->setDataBits(QSerialPort::Data8)) {
emit error(tr("Can't set 8 data bits to port %1, error code %2")
.arg(portName).arg(serial->error()));
return;
}
if (!serial->setParity(QSerialPort::NoParity)) {
emit error(tr("Can't set no patity to port %1, error code %2")
.arg(portName).arg(serial->error()));
return;
}
if (!serial->setStopBits(QSerialPort::OneStop)) {
emit error(tr("Can't set 1 stop bit to port %1, error code %2")
.arg(portName).arg(serial->error()));
return;
}
if (!serial->setFlowControl(QSerialPort::NoFlowControl)) {
emit error(tr("Can't set no flow control to port %1, error code %2")
.arg(portName).arg(serial->error()));
return;
}
connect(serial, SIGNAL(readyRead()), this, SLOT(Read()));
}
void SerialInput::Read()
{
QString s = ReadLine();
if( s != "" ) emit message(s);
}
QString SerialInput::ReadLine()
{
QString msg;
if( serial->isOpen() ) {
// if (serial->waitForReadyRead(10))
{
while(1)
{
// read all there is to read
if( serial->isReadable() )
{
buffer += serial->readAll();
}
// check for message termitator, quit if none
int i = buffer.indexOf('\r');
if( i < 0 ) break;
// we got full message so process it
msg = buffer.left(i);
// remove processed message from buffer and any leading unprintables
while(i < buffer.length() && buffer[i] <= ' ') i++;
buffer = buffer.remove(0,i);
}
}
}
return msg;
}