-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserial.cpp
58 lines (50 loc) · 1.74 KB
/
serial.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
#include "serial.h"
#include "log.h"
#include <QCoreApplication>
#include <QObject>
#include <QtSerialPort/QtSerialPort>
QT_USE_NAMESPACE
Serial::Serial(QString portName, QObject *parent)
: QObject(parent)
{
m_serialPort.setPortName(portName);
m_serialPort.setBaudRate(QSerialPort::Baud9600);
if (!m_serialPort.open(QIODevice::ReadWrite)) {
WARN( QObject::tr("Failed to open port %1, error: %2")
.arg(portName)
.arg(m_serialPort.errorString()));
exit(1);
}
connect(&m_serialPort, SIGNAL(readyRead()), SLOT(handleReadyRead()));
connect(&m_serialPort, SIGNAL(error(QSerialPort::SerialPortError)),
SLOT(handleError(QSerialPort::SerialPortError)));
}
Serial::~Serial() { }
void Serial::handleReadyRead()
{
while (m_serialPort.bytesAvailable() >= 9){
QByteArray d = m_serialPort.read(9);
INFO("RX PLC " + QString(d.toHex()));
emit (newData(d));
}
}
void Serial::writeToDevice(QByteArray data)
{
m_serialPort.write(data);
INFO("TX PLC " + QString(data.toHex()));
// docs for 1141 state to write twice to bus with a delay of
// 12.5ms in between, but I could not notice any difference
// in the systems behavior...
//// QThread::usleep(12500);
//// m_serialPort.write(data);
//// INFO(">B " + QString(data.toHex()));
}
void Serial::handleError(QSerialPort::SerialPortError serialPortError)
{
if (serialPortError == QSerialPort::ReadError) {
WARN( QObject::tr("An I/O error occurred while reading the data from port %1, error: %2")
.arg(m_serialPort.portName())
.arg(m_serialPort.errorString()));
QCoreApplication::exit(1);
}
}