diff --git a/app/main.cpp b/app/main.cpp index 1a166fe8..efb1202d 100644 --- a/app/main.cpp +++ b/app/main.cpp @@ -240,8 +240,7 @@ int main(int argc, char* argv[]) } if(!QFile::exists(configPath)) { - UERROR("Configuration file doesn't exist : %s", configPath.toStdString().c_str()); - showUsage(); + UWARN("Configuration file \"%s\" doesn't exist, it will be created with default values...", configPath.toStdString().c_str()); } } else @@ -292,7 +291,7 @@ int main(int argc, char* argv[]) UINFO(" Scene path: \"%s\"", scenePath.toStdString().c_str()); UINFO(" Settings path: \"%s\"", configPath.toStdString().c_str()); #ifdef WITH_JSONCPP - UINFO(" JSON path: \"%s\"", configPath.toStdString().c_str()); + UINFO(" JSON path: \"%s\"", jsonPath.toStdString().c_str()); #endif ////////////////////////// @@ -355,7 +354,7 @@ int main(int argc, char* argv[]) QCoreApplication app(argc, argv); TcpServer tcpServer(Settings::getGeneral_port()); - printf("IP: %s\nport: %d\n", tcpServer.getHostAddress().toString().toStdString().c_str(), tcpServer.getPort()); + UINFO("Detection sent on port: %d (IP=%s)", tcpServer.getPort(), tcpServer.getHostAddress().toString().toStdString().c_str()); // connect stuff: // [FindObject] ---ObjectsDetected---> [TcpServer] @@ -384,17 +383,8 @@ int main(int argc, char* argv[]) // start processing! while(running && !camera.start()) { - if(Settings::getCamera_6useTcpCamera()) - { - UWARN("Camera initialization failed! (with server %s:%d) Trying again in 1 second...", - Settings::getCamera_7IP().toStdString().c_str(), Settings::getCamera_8port()); - Sleep(1000); - } - else - { - UERROR("Camera initialization failed!"); - running = false; - } + UERROR("Camera initialization failed!"); + running = false; } if(running) { diff --git a/include/find_object/Camera.h b/include/find_object/Camera.h index 425bb837..0a555f29 100644 --- a/include/find_object/Camera.h +++ b/include/find_object/Camera.h @@ -12,7 +12,7 @@ #include #include -class CameraTcpClient; +class CameraTcpServer; class FINDOBJECT_EXP Camera : public QObject { Q_OBJECT @@ -27,6 +27,7 @@ public: void pause(); int getTotalFrames(); int getCurrentFrameIndex(); + int getPort(); void moveToFrame(int frame); Q_SIGNALS: @@ -45,7 +46,7 @@ private: QTimer cameraTimer_; QList images_; unsigned int currentImageIndex_; - CameraTcpClient * cameraTcpClient_; + CameraTcpServer * cameraTcpServer_; }; #endif /* CAMERA_H_ */ diff --git a/include/find_object/Settings.h b/include/find_object/Settings.h index 27bca6c8..81da5e85 100644 --- a/include/find_object/Settings.h +++ b/include/find_object/Settings.h @@ -65,8 +65,7 @@ class FINDOBJECT_EXP Settings PARAMETER(Camera, 4imageRate, double, 2.0, "Image rate in Hz (0 Hz means as fast as possible)."); // Hz PARAMETER(Camera, 5mediaPath, QString, "", "Video file or directory of images. If set, the camera is not used. See General->videoFormats and General->imageFormats for available formats."); PARAMETER(Camera, 6useTcpCamera, bool, false, "Use TCP/IP input camera."); - PARAMETER(Camera, 7IP, QString, "127.0.0.1", "The images server's IP to connect when useTcpCamera is checked."); - PARAMETER(Camera, 8port, int, 5000, "The images server's port to connect when useTcpCamera is checked."); + PARAMETER(Camera, 8port, int, 5000, "The images server's port when useTcpCamera is checked. Only one client at the same time is allowed."); PARAMETER(Camera, 9queueSize, int, 1, "Maximum images buffered from TCP. If 0, all images are buffered."); //List format : [Index:item0;item1;item3;...] diff --git a/src/AddObjectDialog.cpp b/src/AddObjectDialog.cpp index f9d2af14..69e619c0 100644 --- a/src/AddObjectDialog.cpp +++ b/src/AddObjectDialog.cpp @@ -363,6 +363,11 @@ void AddObjectDialog::update(const cv::Mat & image) ui_->cameraView->setData(keypoints, cvtCvMat2QImage(cameraImage_)); ui_->cameraView->update(); } + else + { + UWARN("Camera cannot get more images (maybe the end of stream is reached)..."); + camera_->stop(); + } } cv::Rect AddObjectDialog::computeROI(const std::vector & kpts) diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index b2ddb76d..6994900c 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -8,7 +8,7 @@ SET(headers_ui ../include/${PROJECT_PREFIX}/TcpServer.h ../include/${PROJECT_PREFIX}/ObjWidget.h ./AddObjectDialog.h - ./CameraTcpClient.h + ./CameraTcpServer.h ./ParametersToolBox.h ./AboutDialog.h ./RectItem.h @@ -46,7 +46,7 @@ SET(SRC_FILES ./RectItem.cpp ./QtOpenCV.cpp ./Camera.cpp - ./CameraTcpClient.cpp + ./CameraTcpServer.cpp ./ParametersToolBox.cpp ./Settings.cpp ./ObjWidget.cpp diff --git a/src/Camera.cpp b/src/Camera.cpp index c1759a7e..502d759d 100644 --- a/src/Camera.cpp +++ b/src/Camera.cpp @@ -11,12 +11,12 @@ #include #include #include "utilite/UDirectory.h" -#include "CameraTcpClient.h" +#include "CameraTcpServer.h" Camera::Camera(QObject * parent) : QObject(parent), currentImageIndex_(0), - cameraTcpClient_(new CameraTcpClient(this)) + cameraTcpServer_(0) { qRegisterMetaType("cv::Mat"); connect(&cameraTimer_, SIGNAL(timeout()), this, SLOT(takeImage())); @@ -33,7 +33,12 @@ void Camera::stop() capture_.release(); images_.clear(); currentImageIndex_ = 0; - cameraTcpClient_->close(); + if(cameraTcpServer_) + { + cameraTcpServer_->close(); + delete cameraTcpServer_; + cameraTcpServer_ = 0; + } } void Camera::pause() @@ -79,6 +84,15 @@ void Camera::moveToFrame(int frame) } } +int Camera::getPort() +{ + if(cameraTcpServer_) + { + return cameraTcpServer_->getPort(); + } + return 0; +} + void Camera::takeImage() { cv::Mat img; @@ -93,33 +107,29 @@ void Camera::takeImage() img = cv::imread(images_[currentImageIndex_++]); } } - else + else if(cameraTcpServer_) { - img = cameraTcpClient_->getImage(); - if(cameraTcpClient_->imagesBuffered() > 0 && Settings::getCamera_9queueSize() == 0) + img = cameraTcpServer_->getImage(); + if(cameraTcpServer_->imagesBuffered() > 0 && Settings::getCamera_9queueSize() == 0) { - UWARN("%d images buffered so far...", cameraTcpClient_->imagesBuffered()); - } - while(img.empty() && cameraTcpClient_->waitForReadyRead()) - { - img = cameraTcpClient_->getImage(); - } - if(img.empty()) - { - if(!cameraTcpClient_->waitForConnected()) - { - UWARN("Connection is lost, trying to reconnect to server (%s:%d)... (at the rate of the camera: %d ms)", - Settings::getCamera_7IP().toStdString().c_str(), - Settings::getCamera_8port(), - cameraTimer_.interval()); - cameraTcpClient_->connectToHost(Settings::getCamera_7IP(), Settings::getCamera_8port()); - } + UWARN("%d images buffered so far...", cameraTcpServer_->imagesBuffered()); } } if(img.empty()) { - UWARN("Camera: Could not grab a frame, the end of the feed may be reached..."); + if(cameraTcpServer_) + { + if(!cameraTcpServer_->isConnected()) + { + cameraTcpServer_->waitForNewConnection(100); + } + } + else + { + // In case of a directory of images or a video + Q_EMIT imageReceived(cv::Mat()); // empty image to notify that there are no more images + } } else { @@ -146,17 +156,22 @@ void Camera::takeImage() bool Camera::start() { - if(!capture_.isOpened() && images_.empty() && !cameraTcpClient_->isOpen()) + if(!capture_.isOpened() && images_.empty() && cameraTcpServer_ == 0) { if(Settings::getCamera_6useTcpCamera()) { - cameraTcpClient_->connectToHost(Settings::getCamera_7IP(), Settings::getCamera_8port()); - if(!cameraTcpClient_->waitForConnected()) + cameraTcpServer_ = new CameraTcpServer(Settings::getCamera_8port(), this); + if(!cameraTcpServer_->isListening()) { - UWARN("Camera: Cannot connect to server \"%s:%d\"", - Settings::getCamera_7IP().toStdString().c_str(), - Settings::getCamera_8port()); - cameraTcpClient_->close(); + UWARN("CameraTCP: Cannot listen to port %d", cameraTcpServer_->getPort()); + delete cameraTcpServer_; + cameraTcpServer_ = 0; + } + else + { + UINFO("CameraTCP: listening to port %d (IP=%s)", + cameraTcpServer_->getPort(), + cameraTcpServer_->getHostAddress().toString().toStdString().c_str()); } } else @@ -215,7 +230,7 @@ bool Camera::start() } } } - if(!capture_.isOpened() && images_.empty() && !cameraTcpClient_->isOpen()) + if(!capture_.isOpened() && images_.empty() && cameraTcpServer_ == 0) { UERROR("Camera: Failed to open a capture object!"); return false; diff --git a/src/CameraTcpClient.cpp b/src/CameraTcpClient.cpp deleted file mode 100644 index 0f03a51f..00000000 --- a/src/CameraTcpClient.cpp +++ /dev/null @@ -1,96 +0,0 @@ -/* - * CameraTcpClient.cpp - * - * Created on: 2014-07-31 - * Author: mathieu - */ - -#include "find_object/Settings.h" -#include "find_object/utilite/ULogger.h" - -#include "CameraTcpClient.h" - -CameraTcpClient::CameraTcpClient(QObject *parent) : - QTcpSocket(parent), - blockSize_(0) -{ - connect(this, SIGNAL(readyRead()), this, SLOT(readReceivedData())); - connect(this, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(displayError(QAbstractSocket::SocketError))); - connect(this, SIGNAL(disconnected()), this, SLOT(connectionLost())); -} - -cv::Mat CameraTcpClient::getImage() -{ - cv::Mat img; - if(images_.size()) - { - // if queue changed after tcp connection ended with images still in the buffer - int queue = Settings::getCamera_9queueSize(); - while(queue > 0 && images_.size() > queue) - { - images_.pop_front(); - } - - img = images_.front(); - images_.pop_front(); - } - return img; -} - -void CameraTcpClient::readReceivedData() -{ - QDataStream in(this); - in.setVersion(QDataStream::Qt_4_0); - - if (blockSize_ == 0) - { - if (this->bytesAvailable() < (int)sizeof(quint64)) - { - return; - } - - in >> blockSize_; - } - - if (this->bytesAvailable() < (int)blockSize_) - { - return; - } - - std::vector buf(blockSize_); - in.readRawData((char*)buf.data(), blockSize_); - images_.push_back(cv::imdecode(buf, cv::IMREAD_UNCHANGED)); - int queue = Settings::getCamera_9queueSize(); - while(queue > 0 && images_.size() > queue) - { - images_.pop_front(); - } - blockSize_ = 0; -} - -void CameraTcpClient::displayError(QAbstractSocket::SocketError socketError) -{ - switch (socketError) - { - case QAbstractSocket::RemoteHostClosedError: - break; - case QAbstractSocket::HostNotFoundError: - UWARN("CameraTcp: Tcp error: The host was not found. Please " - "check the host name and port settings.\n"); - break; - case QAbstractSocket::ConnectionRefusedError: - UWARN("CameraTcp: The connection was refused by the peer. " - "Make sure your images server is running, " - "and check that the host name and port " - "settings are correct."); - break; - default: - UERROR("The following error occurred: %s.", this->errorString().toStdString().c_str()); - break; - } -} - -void CameraTcpClient::connectionLost() -{ - //printf("[WARNING] CameraTcp: Connection lost!\n"); -} diff --git a/src/CameraTcpServer.cpp b/src/CameraTcpServer.cpp new file mode 100644 index 00000000..28399ea8 --- /dev/null +++ b/src/CameraTcpServer.cpp @@ -0,0 +1,165 @@ +/* + * CameraTcpClient.cpp + * + * Created on: 2014-07-31 + * Author: mathieu + */ + +#include "find_object/Settings.h" +#include "find_object/utilite/ULogger.h" + +#include "CameraTcpServer.h" +#include +#include +#include + +CameraTcpServer::CameraTcpServer(quint16 port, QObject *parent) : + QTcpServer(parent), + blockSize_(0) +{ + this->setMaxPendingConnections(1); + if (!this->listen(QHostAddress::Any, port)) + { + UERROR("Unable to start the Camera TCP server: %s", this->errorString().toStdString().c_str()); + return; + } + + connect(this, SIGNAL(newConnection()), this, SLOT(addClient())); +} + +cv::Mat CameraTcpServer::getImage() +{ + cv::Mat img; + if(images_.size()) + { + // if queue changed after tcp connection ended with images still in the buffer + int queue = Settings::getCamera_9queueSize(); + while(queue > 0 && images_.size() > queue) + { + images_.pop_front(); + } + + img = images_.front(); + images_.pop_front(); + } + if(this->findChildren().size() == 1) + { + this->findChildren().first()->waitForReadyRead(100); + } + return img; +} + +bool CameraTcpServer::isConnected() const +{ + return this->findChildren().size() > 0; +} + +QHostAddress CameraTcpServer::getHostAddress() const +{ + QHostAddress hostAddress; + + QList ipAddressesList = QNetworkInterface::allAddresses(); + // use the first non-localhost IPv4 address + for (int i = 0; i < ipAddressesList.size(); ++i) + { + if (ipAddressesList.at(i) != QHostAddress::LocalHost && ipAddressesList.at(i).toIPv4Address()) + { + hostAddress = ipAddressesList.at(i).toString(); + break; + } + } + + // if we did not find one, use IPv4 localhost + if (hostAddress.isNull()) + { + hostAddress = QHostAddress(QHostAddress::LocalHost); + } + + return hostAddress; +} + +quint16 CameraTcpServer::getPort() const +{ + return this->serverPort(); +} + +void CameraTcpServer::addClient() +{ + QTcpSocket * client = this->nextPendingConnection(); + + QList clients = this->findChildren(); + if(clients.size() > 1) + { + UWARN("A client is already connected. Only one connection allowed at the same time."); + client->close(); + client->deleteLater(); + } + else + { + connect(client, SIGNAL(readyRead()), this, SLOT(readReceivedData())); + connect(client, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(displayError(QAbstractSocket::SocketError))); + connect(client, SIGNAL(disconnected()), this, SLOT(connectionLost())); + } +} + +void CameraTcpServer::readReceivedData() +{ + QTcpSocket * client = (QTcpSocket*)sender(); + QDataStream in(client); + in.setVersion(QDataStream::Qt_4_0); + + if (blockSize_ == 0) + { + if (client->bytesAvailable() < (int)sizeof(quint64)) + { + return; + } + + in >> blockSize_; + } + + if (client->bytesAvailable() < (int)blockSize_) + { + return; + } + + std::vector buf(blockSize_); + in.readRawData((char*)buf.data(), blockSize_); + images_.push_back(cv::imdecode(buf, cv::IMREAD_UNCHANGED)); + int queue = Settings::getCamera_9queueSize(); + while(queue > 0 && images_.size() > queue) + { + images_.pop_front(); + } + blockSize_ = 0; +} + +void CameraTcpServer::displayError(QAbstractSocket::SocketError socketError) +{ + switch (socketError) + { + case QAbstractSocket::RemoteHostClosedError: + break; + case QAbstractSocket::HostNotFoundError: + UWARN("CameraTcp: Tcp error: The host was not found. Please " + "check the host name and port settings.\n"); + break; + case QAbstractSocket::ConnectionRefusedError: + UWARN("CameraTcp: The connection was refused by the peer. " + "Make sure your images server is running, " + "and check that the host name and port " + "settings are correct."); + break; + default: + //UERROR("The following error occurred: %s.", this->errorString().toStdString().c_str()); + break; + } +} + +void CameraTcpServer::connectionLost() +{ + //printf("[WARNING] CameraTcp: Connection lost!\n"); + ((QTcpSocket*)sender())->close(); + sender()->deleteLater(); + blockSize_ = 0; // reset +} diff --git a/src/CameraTcpClient.h b/src/CameraTcpServer.h similarity index 65% rename from src/CameraTcpClient.h rename to src/CameraTcpServer.h index 76966fd0..3d16a0ca 100644 --- a/src/CameraTcpClient.h +++ b/src/CameraTcpServer.h @@ -8,22 +8,29 @@ #ifndef CAMERATCPCLIENT_H_ #define CAMERATCPCLIENT_H_ -#include +#include #include -class CameraTcpClient : public QTcpSocket +class CameraTcpServer : public QTcpServer { Q_OBJECT; public: - CameraTcpClient(QObject * parent = 0); + CameraTcpServer(quint16 port = 0, QObject * parent = 0); cv::Mat getImage(); int imagesBuffered() const {return images_.size();} + bool isConnected() const; + + QHostAddress getHostAddress() const; + quint16 getPort() const; private Q_SLOTS: void readReceivedData(); void displayError(QAbstractSocket::SocketError socketError); void connectionLost(); +private Q_SLOTS: + void addClient(); + private: quint64 blockSize_; QVector images_; diff --git a/src/MainWindow.cpp b/src/MainWindow.cpp index f3af9085..c1d3ea84 100644 --- a/src/MainWindow.cpp +++ b/src/MainWindow.cpp @@ -99,8 +99,8 @@ MainWindow::MainWindow(FindObject * findObject, Camera * camera, QWidget * paren ui_->toolBox->getParameterWidget(Settings::kCamera_3imageHeight())->setEnabled(false); ui_->toolBox->getParameterWidget(Settings::kCamera_5mediaPath())->setEnabled(false); ui_->toolBox->getParameterWidget(Settings::kCamera_6useTcpCamera())->setEnabled(false); - ui_->toolBox->getParameterWidget(Settings::kCamera_7IP())->setEnabled(false); ui_->toolBox->getParameterWidget(Settings::kCamera_8port())->setEnabled(false); + ui_->toolBox->getParameterWidget(Settings::kCamera_9queueSize())->setEnabled(false); ui_->actionCamera_from_video_file->setVisible(false); ui_->actionCamera_from_TCP_IP->setVisible(false); ui_->actionCamera_from_directory_of_images->setVisible(false); @@ -270,7 +270,7 @@ void MainWindow::setupTCPServer() connect(this, SIGNAL(objectsFound(QMultiMap >)), tcpServer_, SLOT(publishObjects(QMultiMap >))); ui_->label_ipAddress->setText(tcpServer_->getHostAddress().toString()); ui_->label_port->setNum(tcpServer_->getPort()); - UINFO("IP: %s port: %d", tcpServer_->getHostAddress().toString().toStdString().c_str(), tcpServer_->getPort()); + UINFO("Detection sent on port: %d (IP=%s)", tcpServer_->getPort(), tcpServer_->getHostAddress().toString().toStdString().c_str()); } void MainWindow::setSourceImageText(const QString & text) @@ -430,6 +430,10 @@ void MainWindow::removeObject(ObjWidget * object) } findObject_->removeObject(object->id()); object->deleteLater(); + if(Settings::getGeneral_autoUpdateObjects()) + { + this->updateVocabulary(); + } if(!camera_->isRunning() && !sceneImage_.empty()) { this->update(); @@ -641,19 +645,20 @@ void MainWindow::setupCameraFromTcpIp() } else { - QString ip = QInputDialog::getText(this, tr("Server IP..."), "IP: ", QLineEdit::Normal, Settings::getCamera_7IP()); - if(!ip.isEmpty()) - { - int port = QInputDialog::getInteger(this, tr("Server port..."), "Port: ", Settings::getCamera_8port()); + bool ok; + int port = QInputDialog::getInteger(this, tr("Server port..."), "Port: ", Settings::getCamera_8port(), 1, USHRT_MAX, 1, &ok); - if(port > 0) + if(ok) + { + int queue = QInputDialog::getInteger(this, tr("Queue size..."), "Images buffer size (0 means infinite): ", Settings::getCamera_9queueSize(), 0, 2147483647, 1, &ok); + if(ok) { Settings::setCamera_6useTcpCamera(true); ui_->toolBox->updateParameter(Settings::kCamera_6useTcpCamera()); - Settings::setCamera_7IP(ip); - ui_->toolBox->updateParameter(Settings::kCamera_7IP()); Settings::setCamera_8port(port); ui_->toolBox->updateParameter(Settings::kCamera_8port()); + Settings::setCamera_9queueSize(queue); + ui_->toolBox->updateParameter(Settings::kCamera_9queueSize()); if(camera_->isRunning()) { this->stopProcessing(); @@ -786,6 +791,13 @@ void MainWindow::startProcessing() ui_->horizontalSlider_frames->setMaximum(totalFrames-1); } + //update camera port if TCP is used + ui_->label_port_image->setText("-"); + if(Settings::getCamera_6useTcpCamera() && camera_->getPort()) + { + ui_->label_port_image->setNum(camera_->getPort()); + } + if(updateStatusMessage) { this->statusBar()->showMessage(tr("Camera started."), 2000); @@ -800,7 +812,7 @@ void MainWindow::startProcessing() if(Settings::getCamera_6useTcpCamera()) { - QMessageBox::critical(this, tr("Camera error"), tr("Camera initialization failed! (with server %1:%2)").arg(Settings::getCamera_7IP()).arg(Settings::getCamera_8port())); + QMessageBox::critical(this, tr("Camera error"), tr("Camera initialization failed! (with port %1)").arg(Settings::getCamera_8port())); } else { @@ -829,6 +841,7 @@ void MainWindow::stopProcessing() ui_->horizontalSlider_frames->setEnabled(false); ui_->horizontalSlider_frames->setValue(0); ui_->label_frame->setVisible(false); + ui_->label_port_image->setText("-"); } void MainWindow::pauseProcessing() @@ -876,6 +889,12 @@ void MainWindow::rectHovered(int objId) void MainWindow::update(const cv::Mat & image) { + if(image.empty()) + { + UWARN("Camera cannot get more images (maybe the end of stream is reached)..."); + return; + } + // reset objects color for(QMap::iterator iter=objWidgets_.begin(); iter!=objWidgets_.end(); ++iter) { diff --git a/src/ui/mainWindow.ui b/src/ui/mainWindow.ui index fe397987..ba00aafd 100644 --- a/src/ui/mainWindow.ui +++ b/src/ui/mainWindow.ui @@ -448,6 +448,13 @@ 0 + + + + 000 + + + @@ -476,13 +483,6 @@ - - - - 000 - - - @@ -619,7 +619,7 @@ - Port + Output detection port @@ -658,6 +658,20 @@ + + + + Input image port + + + + + + + NA + + + diff --git a/tools/CMakeLists.txt b/tools/CMakeLists.txt index 232af08b..e7550ff8 100644 --- a/tools/CMakeLists.txt +++ b/tools/CMakeLists.txt @@ -1,3 +1,4 @@ ADD_SUBDIRECTORY( tcpObjectsClient ) ADD_SUBDIRECTORY( tcpImagesServer ) +ADD_SUBDIRECTORY( tcpRequest ) ADD_SUBDIRECTORY( similarity ) \ No newline at end of file diff --git a/tools/tcpImagesServer/ImagesTcpServer.cpp b/tools/tcpImagesServer/ImagesTcpServer.cpp index f56264ec..a10739a5 100644 --- a/tools/tcpImagesServer/ImagesTcpServer.cpp +++ b/tools/tcpImagesServer/ImagesTcpServer.cpp @@ -15,17 +15,17 @@ #include ImagesTcpServer::ImagesTcpServer(float hz, const QString & path, QObject * parent) : - QTcpServer(parent) + QTcpSocket(parent) { // Set camera parameters Settings::setCamera_4imageRate(hz); Settings::setCamera_5mediaPath(path); - connect(this, SIGNAL(newConnection()), this, SLOT(addClient())); connect(&camera_, SIGNAL(imageReceived(const cv::Mat &)), this, SLOT(publishImage(const cv::Mat &))); + connect(this, SIGNAL(connected()), this, SLOT(startCamera())); } -QHostAddress ImagesTcpServer::getHostAddress() const +QHostAddress ImagesTcpServer::getHostAddress() { QHostAddress hostAddress; @@ -49,21 +49,21 @@ QHostAddress ImagesTcpServer::getHostAddress() const return hostAddress; } -quint16 ImagesTcpServer::getPort() const -{ - return this->serverPort(); -} - void ImagesTcpServer::publishImage(const cv::Mat & image) { - QList clients = this->findChildren(); - if(clients.size()) + if(image.empty()) { - std::vector buf; - cv::imencode(".png", image, buf); - - for(QList::iterator iter = clients.begin(); iter!=clients.end(); ++iter) + printf("No more images...\n"); + camera_.pause(); + Q_EMIT connectionLost(); + } + else + { + if(this->waitForConnected()) { + std::vector buf; + cv::imencode(".png", image, buf); + QByteArray block; QDataStream out(&block, QIODevice::WriteOnly); out.setVersion(QDataStream::Qt_4_0); @@ -71,20 +71,20 @@ void ImagesTcpServer::publishImage(const cv::Mat & image) out.writeRawData((char*)buf.data(), (int)buf.size()); out.device()->seek(0); out << (quint64)(block.size() - sizeof(quint64)); - (*iter)->write(block); + this->write(block); + + } + else + { + printf("Lost connection...\n"); + camera_.pause(); + Q_EMIT connectionLost(); } - } - else - { - printf("Paused...\n"); - camera_.pause(); } } -void ImagesTcpServer::addClient() +void ImagesTcpServer::startCamera() { - QTcpSocket * client = this->nextPendingConnection(); - connect(client, SIGNAL(disconnected()), client, SLOT(deleteLater())); if(!camera_.isRunning()) { printf("Start...\n"); diff --git a/tools/tcpImagesServer/ImagesTcpServer.h b/tools/tcpImagesServer/ImagesTcpServer.h index f66ce4da..dc0238a2 100644 --- a/tools/tcpImagesServer/ImagesTcpServer.h +++ b/tools/tcpImagesServer/ImagesTcpServer.h @@ -5,27 +5,29 @@ * Author: mathieu */ -#ifndef TCPCLIENT_H_ -#define TCPCLIENT_H_ +#ifndef IMAGESTCPSERVER_H_ +#define IMAGESTCPSERVER_H_ #include "find_object/Camera.h" -#include +#include -class ImagesTcpServer : public QTcpServer +class ImagesTcpServer : public QTcpSocket { Q_OBJECT +public: + static QHostAddress getHostAddress(); + public: ImagesTcpServer(float hz = 10.0f, const QString & path = "", QObject * parent = 0); - QHostAddress getHostAddress() const; - quint16 getPort() const; - - private Q_SLOTS: - void addClient(); + void startCamera(); void publishImage(const cv::Mat & image); +Q_SIGNALS: + void connectionLost(); + private: Camera camera_; }; diff --git a/tools/tcpImagesServer/main.cpp b/tools/tcpImagesServer/main.cpp index 72fb81ce..82976efa 100644 --- a/tools/tcpImagesServer/main.cpp +++ b/tools/tcpImagesServer/main.cpp @@ -11,11 +11,11 @@ void showUsage() { - printf("imagesTcpServer [options]\n" + printf("\ntcpImagesServer [options] port\n" " Options:\n" - " -hz #.# Image rate (default 10 Hz).\n" - " -p # Set manually a port to which the clients will connect.\n" - " -path \"\" Set a path of a directory of images or a video file.\n"); + " --hz #.# Image rate (default 10 Hz).\n" + " --host #.#.#.# Set host address.\n" + " --path \"\" Set a path of a directory of images or a video file.\n"); exit(-1); } @@ -23,15 +23,19 @@ int main(int argc, char * argv[]) { QString ipAddress; float hz = 10.0f; - quint16 port = 0; QString path; - for(int i=1; i #include -TcpClient::TcpClient(const QString & hostname, quint16 port, QObject *parent) : +TcpClient::TcpClient(QObject *parent) : QTcpSocket(parent), blockSize_(0) { connect(this, SIGNAL(readyRead()), this, SLOT(readReceivedData())); connect(this, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(displayError(QAbstractSocket::SocketError))); connect(this, SIGNAL(disconnected()), this, SLOT(connectionLost())); - - this->connectToHost(hostname, port); } void TcpClient::readReceivedData() diff --git a/tools/tcpObjectsClient/TcpClient.h b/tools/tcpObjectsClient/TcpClient.h index 72adce16..55069ee8 100644 --- a/tools/tcpObjectsClient/TcpClient.h +++ b/tools/tcpObjectsClient/TcpClient.h @@ -14,7 +14,7 @@ class TcpClient : public QTcpSocket { Q_OBJECT; public: - TcpClient(const QString & hostname, quint16 port, QObject * parent = 0); + TcpClient(QObject * parent = 0); private Q_SLOTS: void readReceivedData(); diff --git a/tools/tcpObjectsClient/main.cpp b/tools/tcpObjectsClient/main.cpp index 836873c5..80fe5f80 100644 --- a/tools/tcpObjectsClient/main.cpp +++ b/tools/tcpObjectsClient/main.cpp @@ -11,7 +11,7 @@ void showUsage() { - printf("tcpClient [hostname] port\n"); + printf("\ntcpObjectsClient [hostname] port\n"); exit(-1); } @@ -37,30 +37,16 @@ int main(int argc, char * argv[]) if(ipAddress.isEmpty()) { - // find out which IP to connect to - QList ipAddressesList = QNetworkInterface::allAddresses(); - // use the first non-localhost IPv4 address - for (int i = 0; i < ipAddressesList.size(); ++i) - { - if (ipAddressesList.at(i) != QHostAddress::LocalHost && - ipAddressesList.at(i).toIPv4Address()) - { - ipAddress = ipAddressesList.at(i).toString(); - break; - } - } - // if we did not find one, use IPv4 localhost - if (ipAddress.isEmpty()) - { - ipAddress = QHostAddress(QHostAddress::LocalHost).toString(); - } + ipAddress = QHostAddress(QHostAddress::LocalHost).toString(); } QCoreApplication app(argc, argv); printf("Connecting to \"%s:%d\"...\n", ipAddress.toStdString().c_str(), port); - TcpClient client(ipAddress, port); + TcpClient client; + + client.connectToHost(ipAddress, port); if(client.waitForConnected()) {