TcpServer.cpp
Go to the documentation of this file.
00001 /*
00002 Copyright (c) 2011-2014, Mathieu Labbe - IntRoLab - Universite de Sherbrooke
00003 All rights reserved.
00004 
00005 Redistribution and use in source and binary forms, with or without
00006 modification, are permitted provided that the following conditions are met:
00007     * Redistributions of source code must retain the above copyright
00008       notice, this list of conditions and the following disclaimer.
00009     * Redistributions in binary form must reproduce the above copyright
00010       notice, this list of conditions and the following disclaimer in the
00011       documentation and/or other materials provided with the distribution.
00012     * Neither the name of the Universite de Sherbrooke nor the
00013       names of its contributors may be used to endorse or promote products
00014       derived from this software without specific prior written permission.
00015 
00016 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
00017 ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
00018 WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
00019 DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY
00020 DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
00021 (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
00022 LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
00023 ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
00024 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
00025 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
00026 */
00027 #include "find_object/TcpServer.h"
00028 #include "find_object/utilite/ULogger.h"
00029 
00030 #include <QtNetwork/QNetworkInterface>
00031 #include <QtNetwork/QTcpSocket>
00032 #include <QtGui/QTransform>
00033 #include <opencv2/highgui/highgui.hpp>
00034 
00035 namespace find_object {
00036 
00037 TcpServer::TcpServer(quint16 port, QObject * parent) :
00038         QTcpServer(parent)
00039 {
00040         if (!this->listen(QHostAddress::Any, port))
00041         {
00042                 UERROR("Unable to start the TCP server: %s", this->errorString().toStdString().c_str());
00043                 return;
00044         }
00045 
00046         connect(this, SIGNAL(newConnection()), this, SLOT(addClient()));
00047 }
00048 
00049 QHostAddress TcpServer::getHostAddress() const
00050 {
00051         QHostAddress hostAddress;
00052 
00053         QList<QHostAddress> ipAddressesList = QNetworkInterface::allAddresses();
00054         // use the first non-localhost IPv4 address
00055         for (int i = 0; i < ipAddressesList.size(); ++i)
00056         {
00057                 if (ipAddressesList.at(i) != QHostAddress::LocalHost && ipAddressesList.at(i).toIPv4Address())
00058                 {
00059                         hostAddress = ipAddressesList.at(i).toString();
00060                         break;
00061                 }
00062         }
00063 
00064         // if we did not find one, use IPv4 localhost
00065         if (hostAddress.isNull())
00066         {
00067                 hostAddress = QHostAddress(QHostAddress::LocalHost);
00068         }
00069 
00070         return hostAddress;
00071 }
00072 
00073 quint16 TcpServer::getPort() const
00074 {
00075         return this->serverPort();
00076 }
00077 
00078 void TcpServer::publishDetectionInfo(const DetectionInfo & info)
00079 {
00080         QList<QTcpSocket*> clients = this->findChildren<QTcpSocket*>();
00081         if(clients.size())
00082         {
00083                 QByteArray block;
00084                 QDataStream out(&block, QIODevice::WriteOnly);
00085                 out.setVersion(QDataStream::Qt_4_0);
00086                 out << (quint16)0;
00087 
00088                 out << info;
00089 
00090                 out.device()->seek(0);
00091                 out << (quint16)(block.size() - sizeof(quint16));
00092 
00093                 for(QList<QTcpSocket*>::iterator iter = clients.begin(); iter!=clients.end(); ++iter)
00094                 {
00095                         (*iter)->write(block);
00096                 }
00097         }
00098 }
00099 
00100 void TcpServer::addClient()
00101 {
00102         while(this->hasPendingConnections())
00103         {
00104                 QTcpSocket * client =  this->nextPendingConnection();
00105                 connect(client, SIGNAL(readyRead()), this, SLOT(readReceivedData()));
00106                 connect(client, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(displayError(QAbstractSocket::SocketError)));
00107                 connect(client, SIGNAL(disconnected()), this, SLOT(connectionLost()));
00108         }
00109 }
00110 
00111 void TcpServer::readReceivedData()
00112 {
00113         QTcpSocket * client = (QTcpSocket*)sender();
00114         QDataStream in(client);
00115         in.setVersion(QDataStream::Qt_4_0);
00116 
00117         if (blockSizes_.value(client->socketDescriptor(), 0) == 0)
00118         {
00119                 if (client->bytesAvailable() < (int)sizeof(quint64))
00120                 {
00121                         return;
00122                 }
00123 
00124                 in >> blockSizes_[client->socketDescriptor()];
00125         }
00126 
00127         if (client->bytesAvailable() < (int)blockSizes_[client->socketDescriptor()])
00128         {
00129                 return;
00130         }
00131 
00132         quint32 serviceType;
00133         in >> serviceType;
00134 
00135         bool ok = true;
00136         if(serviceType == kAddObject)
00137         {
00138                 int id;
00139                 in >> id;
00140                 QString fileName;
00141                 in >> fileName;
00142                 quint64 imageSize;
00143                 in >> imageSize;
00144                 std::vector<unsigned char> buf(imageSize);
00145                 in.readRawData((char*)buf.data(), imageSize);
00146                 cv::Mat image = cv::imdecode(buf, cv::IMREAD_UNCHANGED);
00147 
00148                 UINFO("TCP service: Add %d \"%s\"", id, fileName.toStdString().c_str());
00149                 Q_EMIT addObject(image, id, fileName);
00150         }
00151         else if(serviceType == kRemoveObject)
00152         {
00153                 int id;
00154                 in >> id;
00155 
00156                 UINFO("TCP service: Remove %d", id);
00157                 Q_EMIT removeObject(id);
00158         }
00159         else
00160         {
00161                 UERROR("Unknown service type called %d", serviceType);
00162                 ok = false;
00163         }
00164 
00165         blockSizes_.remove(client->socketDescriptor());
00166         client->write(QByteArray(ok?"1":"0")); // send acknowledge
00167 }
00168 
00169 void TcpServer::displayError(QAbstractSocket::SocketError socketError)
00170 {
00171         switch (socketError)
00172         {
00173                 case QAbstractSocket::RemoteHostClosedError:
00174                         break;
00175                 case QAbstractSocket::HostNotFoundError:
00176                         UWARN("CameraTcp: Tcp error: The host was not found. Please "
00177                                         "check the host name and port settings.\n");
00178                         break;
00179                 case QAbstractSocket::ConnectionRefusedError:
00180                         UWARN("CameraTcp: The connection was refused by the peer. "
00181                                         "Make sure your images server is running, "
00182                                         "and check that the host name and port "
00183                                         "settings are correct.");
00184                         break;
00185                 default:
00186                         //UERROR("The following error occurred: %s.", this->errorString().toStdString().c_str());
00187                         break;
00188         }
00189 }
00190 
00191 void TcpServer::connectionLost()
00192 {
00193         //printf("[WARNING] CameraTcp: Connection lost!\n");
00194         blockSizes_.remove(((QTcpSocket*)sender())->socketDescriptor());
00195         ((QTcpSocket*)sender())->close();
00196         sender()->deleteLater();
00197 }
00198 
00199 } // namespace find_object


find_object_2d
Author(s): Mathieu Labbe
autogenerated on Thu Feb 11 2016 22:57:56