-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathserialportworker.cpp
More file actions
47 lines (41 loc) · 1.14 KB
/
serialportworker.cpp
File metadata and controls
47 lines (41 loc) · 1.14 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
#include "serialportworker.h"
#include <QSerialPortInfo>
#include <QDebug>
SerialPortWorker::SerialPortWorker(const QString &portName, int baudRate, QObject *parent)
: QObject(parent), serialPort(new QSerialPort(this))
{
serialPort->setPortName(portName);
serialPort->setBaudRate(baudRate);
connect(serialPort, &QSerialPort::errorOccurred, this, [this](QSerialPort::SerialPortError error) {
if (error != QSerialPort::NoError) {
emit errorOccurred(serialPort->errorString());
}
});
}
SerialPortWorker::~SerialPortWorker()
{
stop();
}
void SerialPortWorker::start()
{
if (!serialPort->open(QIODevice::ReadWrite)) {
emit errorOccurred(serialPort->errorString());
}
}
void SerialPortWorker::stop()
{
if (serialPort->isOpen()) {
serialPort->close();
}
}
void SerialPortWorker::writeDataToCom(const QByteArray &data)
{
if (serialPort->isOpen()) {
qint64 bytesWritten = serialPort->write(data);
if (bytesWritten == -1) {
emit errorOccurred(serialPort->errorString());
}
} else {
emit errorOccurred("Serial port is not open");
}
}