xref: /OK3568_Linux_fs/app/forlinx/flapp/src/libs/server/platformserver.cpp (revision 4882a59341e53eb6f0b4789bf948001014eff981)
1 #include "platformserver.h"
2 #include "serialport.h"
3 #include "serverhandler.h"
4 #include <QTimer>
5 #include <QDebug>
6 
PlatformServer(const QString & name,QObject * parent)7 PlatformServer::PlatformServer(const QString &name, QObject *parent)
8     :QThread(parent),m_serverName(name),m_ptr(NULL)
9 {
10 
11 }
12 
startwork()13 void PlatformServer::startwork()
14 {
15     if(m_ptr == NULL)
16     {
17         SerialPort *serial = new SerialPort(this);
18         m_ptr = serial;
19         if(!serial->config(m_arg))
20         {
21             foreach (ServerHandler *handler, m_handlers) {
22                 handler->handleError(QString("ERROR[code=%1,string=%2]")
23                                      .arg(serial->error())
24                                      .arg(serial->errorString()));
25             }
26             return;
27         }
28 
29         connect(serial, &QSerialPort::readyRead, this, [=](){
30             QByteArray d =serial->readAll();
31             foreach (ServerHandler *handler, m_handlers) {
32                 handler->handleData(d);
33             }
34         });
35 
36         connect(serial, static_cast<void(QSerialPort::*)(QSerialPort::SerialPortError serialPortError)>(&QSerialPort::error), this,
37                 [=](QSerialPort::SerialPortError serialPortError){
38 
39             qDebug()<<"error="<< serialPortError;
40             foreach (ServerHandler *handler, m_handlers) {
41                 handler->handleError(QString("ERROR[code=%1,string=%2]")
42                                      .arg(serialPortError)
43                                      .arg(serial->errorString()));
44             }
45         });
46     }
47 }
48 
stopwork()49 void PlatformServer::stopwork()
50 {
51     if(m_ptr != NULL)
52     {
53         SerialPort *serial = dynamic_cast<SerialPort*>(m_ptr);
54         if(serial->isOpen())
55         {
56             serial->close();
57         }
58         delete m_ptr;
59         m_ptr = NULL;
60     }
61 }
62 
sendData(const QByteArray & d)63 void PlatformServer::sendData(const QByteArray &d)
64 {
65     if(m_ptr != NULL)
66     {
67         SerialPort *serial = dynamic_cast<SerialPort*>(m_ptr);
68         if(serial->isOpen())
69         {
70             serial->writeData(d);
71         }
72     }
73 }
74 
config(const QVariant & arg)75 void PlatformServer::config(const QVariant &arg)
76 {
77     m_arg = arg;
78 }
79 
addHandler(ServerHandler * handler)80 void PlatformServer::addHandler(ServerHandler *handler)
81 {
82     m_handlers.append(handler);
83     handler->addService(this);
84 }
85 
removehandler(ServerHandler * handler)86 void PlatformServer::removehandler(ServerHandler *handler)
87 {
88     m_handlers.removeOne(handler);
89 }
90 
serverName()91 QString PlatformServer::serverName()
92 {
93     return m_serverName;
94 }
95