Object Detection  5.0
Image Processing Using Qt and Opencv
serialhandler.cpp
1 #include "serialhandler.h"
2 
3 #include <QSerialPort>
4 #include <QVariant>
5 #include "QRegExp"
6 
7 using namespace Devices;
8 
9 class SerialHandler::_SerialHandlerImpl{
10 private:
11  QSerialPort *_port;
12  SerialHandler *const _ptr;
13  QString _currentData;
14 public:
15  _SerialHandlerImpl(SerialHandler *const ptr);
16  QSerialPort *getPort() const;
17  void writeToDevice(const QString &str);
18  void setPort(QSerialPort *port);
19  void openDevice();
20  void closeDevice();
21 private:
22 };
23 
24 SerialHandler::SerialHandler(QObject *parent) : AbstractDeviceWriter(parent),
25  _pimpl{std::make_unique<SerialHandler::_SerialHandlerImpl>(this)}
26 {
27 
28 }
29 
30 SerialHandler::~SerialHandler()
31 {
32 
33 }
34 QSerialPort *SerialHandler::getPort()
35 {
36  return _pimpl->getPort();
37 }
38 
39 void SerialHandler::setPort(QSerialPort *port)
40 {
41  _pimpl->setPort(port);
42 }
43 
44 
45 
46 SerialHandler::_SerialHandlerImpl::_SerialHandlerImpl(SerialHandler *const ptr):
47  _ptr{ptr}
48 {
49 }
50 
51 QSerialPort *SerialHandler::_SerialHandlerImpl::getPort() const
52 {
53  return _port;
54 }
55 
56 void SerialHandler::_SerialHandlerImpl::writeToDevice(const QString &str)
57 {
58  if(_currentData == str)
59  return;
60  QRegExp exp("\\d+, \\d+, \\d+");
61  if(!exp.exactMatch(str)){
62  emit _ptr->errorIODevice("Error Writing To Device");
63  }
64  _currentData = str;
65  QString s = QString("(%1)").arg(str);
66  if(!_port->isOpen() || !_port->isWritable())
67  emit _ptr->errorIODevice("Error Port isn't Avialable");
68  _port->write(s.toLocal8Bit().constData());
69 
70 }
71 
72 void SerialHandler::_SerialHandlerImpl::setPort(QSerialPort *port)
73 {
74  _port = port;
75  connect(_port, &QSerialPort::errorOccurred, [&](QSerialPort::SerialPortError error){
76  emit _ptr->errorIODevice(QVariant(error).toString());
77  });
78 }
79 
80 void SerialHandler::_SerialHandlerImpl::openDevice()
81 {
82  if(!_port->open(QIODevice::WriteOnly))
83  emit _ptr->errorIODevice("Error Opening Device");
84 }
85 
86 void SerialHandler::_SerialHandlerImpl::closeDevice()
87 {
88  _port->close();
89 }
90 
91 
92 void SerialHandler::writeToDevice(const QString &str)
93 {
94  _pimpl->writeToDevice(str);
95 }
96 
97 
98 void Devices::SerialHandler::closeDevice()
99 {
100  _pimpl->closeDevice();
101 }
102 
103 void SerialHandler::openDevice()
104 {
105  _pimpl->openDevice();
106 }