-
Notifications
You must be signed in to change notification settings - Fork 0
/
serialport.cpp
110 lines (95 loc) · 2.37 KB
/
serialport.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
#include "serialport.h"
#include <QWidget>
#include <QDebug>
void SerialPort::connects()
{
connect(serial, SIGNAL(readyRead()), this, SLOT(lineReceived()));
connect(serial, SIGNAL(error(QSerialPort::SerialPortError)),
this, SLOT(serialError(QSerialPort::SerialPortError)));
connect(timer, SIGNAL(timeout()), this, SLOT(onTimerTimeout()));
}
SerialPort::SerialPort(QObject *parent)
: QObject(parent)
{
serial = new QSerialPort(this);
serial->setBaudRate(QSerialPort::Baud115200);
serial->setDataBits(QSerialPort::Data8);
serial->setParity(QSerialPort::NoParity);
serial->setStopBits(QSerialPort::OneStop);
serial->setFlowControl(QSerialPort::NoFlowControl);
timer = new QTimer(this);
timer->setInterval(TIMER_INTERVAL_MS);
connects();
}
SerialPort::~SerialPort()
{
close();
delete serial;
}
void SerialPort::setPortName(const QString &name)
{
if(!serial->isOpen())
serial->setPortName(name);
}
bool SerialPort::open()
{
if(!serial->isOpen())
{
if(serial->open(QSerialPort::ReadWrite))
{
timer->start();
return true;
}
}
return false;
}
void SerialPort::close()
{
if(serial->isOpen())
{
timer->stop();
serial->close();
emit connectionClosed();
}
}
bool SerialPort::isOpen() const
{
return serial->isOpen();
}
void SerialPort::setSerialMsgToSend(const QJsonObject &msg)
{
jsonToSend = msg;
}
void SerialPort::lineReceived()
{
if(serial->canReadLine())
{
auto line = serial->readLine();
line.remove(0,1);
emit readLine(line);
}
}
void SerialPort::serialError(QSerialPort::SerialPortError e)
{
switch(e)
{
case QSerialPort::ResourceError:
QMessageBox::critical(qobject_cast<QWidget *> (parent()), tr("Serial Error"), serial->errorString());
close(); break;
case QSerialPort::NoError: break;
case QSerialPort::UnknownError: break;
default:
QMessageBox::critical(qobject_cast<QWidget *> (parent()), tr("Serial Error"), serial->errorString());
break;
}
}
void SerialPort::onTimerTimeout()
{
if(serial->isOpen())
{
auto jsonDocument = QJsonDocument(jsonToSend);
auto jsonData = jsonDocument.toJson(QJsonDocument::Compact);
serial->write(jsonData + "\r\n");
jsonToSend = QJsonObject();
}
}