diff --git a/CMakeLists.txt b/CMakeLists.txt index aeea4c2..4881b53 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -44,13 +44,14 @@ set(OpenIGTLinkSimulator_SOURCES OpenIGTLinkSimulatorApp.cpp qDataGeneratorBase.cpp qDataGeneratorTracking.cpp + qDataReadingTracker.cpp igtlTCPConnectorBase.cxx igtlTCPConnectorServer.cxx igtlTCPConnectorClient.cxx igtlTCPConnectorServerOIGTL.cxx ) -set(OpenIGTLinkSimulator_HEADERS OpenIGTLinkSimulatorApp.h qDataGeneratorBase.h qDataGeneratorTracking.h) +set(OpenIGTLinkSimulator_HEADERS OpenIGTLinkSimulatorApp.h qDataGeneratorBase.h qDataGeneratorTracking.h qDataReadingTracker.h) set(OpenIGTLinkSimulator_FORMS OpenIGTLinkSimulatorWindow.ui) #set(OpenIGTLinkSimulator_RESOURCES images.qrc) diff --git a/OpenIGTLinkSimulatorApp.cpp b/OpenIGTLinkSimulatorApp.cpp index 9690ca7..091d678 100644 --- a/OpenIGTLinkSimulatorApp.cpp +++ b/OpenIGTLinkSimulatorApp.cpp @@ -1,22 +1,22 @@ /*========================================================================= - + Program: OpenIGTLink Simulator Language: C++ - + Copyright (c) Brigham and Women's Hospital. All rights reserved. - + This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. -=========================================================================*/ + =========================================================================*/ #include #include +#include #include "OpenIGTLinkSimulatorApp.h" - #include "igtlOSUtil.h" #include "igtlImageMessage.h" #include "igtlServerSocket.h" @@ -24,6 +24,7 @@ #include "igtlOSUtil.h" #include "igtlTCPConnectorServerOIGTL.h" #include "qDataGeneratorTracking.h" +#include "qDataReadingTracker.h" const int OpenIGTLinkSimulatorApp::StatusColorTable[][3] = { {100, 100, 100}, // STOP @@ -33,7 +34,7 @@ const int OpenIGTLinkSimulatorApp::StatusColorTable[][3] = { }; const int OpenIGTLinkSimulatorApp::DataIOColorTable[][3] = { - {50, 50, 50}, // None + {50, 50, 50}, // None {100, 200, 100}, // Received {200, 100, 100} // ERROR }; @@ -47,8 +48,12 @@ OpenIGTLinkSimulatorApp::OpenIGTLinkSimulatorApp(QWidget *NOTUSED(parent)) fClientActive = false; // Signals and Slots + connect(pbFilename, SIGNAL( clicked() ), this, SLOT( getPath() )); + connect(rbTrackingRandom, SIGNAL( clicked() ), this, SLOT( disable() )); + connect(rbTrackingFile, SIGNAL( clicked() ), this, SLOT( enable() )); connect(pbQuit, SIGNAL( clicked() ), this, SLOT( quit() )); connect(pbAbout, SIGNAL( clicked() ), this, SLOT( about() )); + connect(sbTrackingChannels, SIGNAL( valueChanged(int) ), this, SLOT( channel(int) )); //connect(pbScannerActivate, SIGNAL( clicked() ), this, SLOT( scannerActivateClicked() )); connect(pbClientActivate, SIGNAL( clicked() ), this, SLOT( clientActivateClicked() )); @@ -60,7 +65,7 @@ OpenIGTLinkSimulatorApp::OpenIGTLinkSimulatorApp(QWidget *NOTUSED(parent)) // this, SLOT( imagePortChanged( const QString & ) )); connect(leOpenIGTLinkPort, SIGNAL( textChanged( const QString & ) ), this, SLOT( igtlPortChanged( const QString & ) )); - + // Default values QString qs; //leScannerAddress->setText(DEFAULT_RMP_ADDR); @@ -70,39 +75,54 @@ OpenIGTLinkSimulatorApp::OpenIGTLinkSimulatorApp(QWidget *NOTUSED(parent)) timer = new QTimer(this); connect(timer, SIGNAL(timeout()), this, SLOT(updateStatus())); timer->start(200); - - // Data Generator - this->TrackingDataGenerator = new qDataGeneratorTracking(); + //Data Generator for Random + this->TrackingDataGenerator = new qDataGeneratorTracking(); + this->TrackingDataReader = new qDataReadingTracker(); + //// OpenIGTLink Server Socket oigtlConnector = igtl::TCPConnectorServerOIGTL::New(); oigtlConnector->SetPort(18944); - - this->TrackingDataGenerator->SetConnector(oigtlConnector); - this->TrackingDataGenerator->Start(); this->Threader = igtl::MultiThreader::New(); - this->Threader->SpawnThread((igtl::ThreadFunctionType) &igtl::TCPConnectorServerOIGTL::MonitorThreadFunction, - oigtlConnector); + this->Threader->SpawnThread((igtl::ThreadFunctionType) &igtl::TCPConnectorServerOIGTL::MonitorThreadFunction, oigtlConnector); +} +void OpenIGTLinkSimulatorApp::disable( ) +{ + pbFilename->setEnabled(false); } - - + +void OpenIGTLinkSimulatorApp::enable( ) +{ + pbFilename->setEnabled(true); +} + void OpenIGTLinkSimulatorApp::getPath() { - QString path; - - //path = QFileDialog::getOpenFileName( - // this, - // "Choose a file to open", - // QString::null, - // QString::null); - // - //lineEdit->setText( path ); + + QString path = QFileDialog::getOpenFileName(this, + tr("Open File"), "/Users", + tr("CSV Files (*.csv);;Text Files (*.txt)")); + if(path != " ") + { + QFile file(path); + if(!file.open(QIODevice::ReadOnly)) + { + QMessageBox::critical(this, tr("Error"), tr("Could not open file")); + return; + } + QTextStream in(&file); + leFilename->setText( path ); + file.close(); + } + this->PathString = path.toUtf8().constData(); + } void OpenIGTLinkSimulatorApp::about() { + QMessageBox::about(this, "About OpenIGTLinkSimulator", "OpenIGTLink Simulator\n\n" @@ -110,47 +130,95 @@ void OpenIGTLinkSimulatorApp::about() "Brigham and Women's Hospital.\n\n" "Copyright (C) 2011-2014\n" ); + } + void OpenIGTLinkSimulatorApp::scannerActivateClicked() { + if (fScannerActive) { - //pbScannerActivate->setText("Activate"); - //fScannerActive = false; + //pbScannerActivate->setText("Activate"); + //fScannerActive = false; } else { - //pbScannerActivate->setText("Deactivate"); - //fScannerActive = true; + //pbScannerActivate->setText("Deactivate"); + //fScannerActive = true; } + } void OpenIGTLinkSimulatorApp::clientActivateClicked() { + if (fClientActive) { - fClientActive = false; - if (oigtlConnector.IsNotNull()) - { - oigtlConnector->Deactivate(); - } + fClientActive = false; + if (oigtlConnector.IsNotNull()) + { + std::cerr << "Deactivating OpenIGTLink connector with:" << std::endl; + std::cerr << " Port: " << igtlPort.toInt() << std::endl; + oigtlConnector->Deactivate(); + } + + rbTrackingFile->setEnabled(true); + rbTrackingRandom->setEnabled(true); + if (rbTrackingFile->isChecked()) + pbFilename->setEnabled(true); } + + else if(!fClientActive && !rbTrackingFile->isChecked() && !rbTrackingRandom->isChecked()) + QMessageBox::critical(this, tr("Error"), tr("Data source not selected!")); + else if(rbTrackingFile->isChecked() && leFilename->text()=="") + QMessageBox::critical(this, tr("Error"), tr("File not selected!")); + else { - fClientActive = true; - if (oigtlConnector.IsNotNull()) - { - std::cerr << "Activating OpenIGTLink connector with:" << std::endl; - std::cerr << " Port: " << igtlPort.toInt() << std::endl; - oigtlConnector->SetPort(igtlPort.toInt()); - oigtlConnector->Activate(); - } + fClientActive = true; + + if (oigtlConnector.IsNotNull()) + { + std::cerr << "Activating OpenIGTLink connector with:" << std::endl; + std::cerr << " Port: " << igtlPort.toInt() << std::endl; + oigtlConnector->SetPort(igtlPort.toInt()); + oigtlConnector->Activate(); + } + else + { + oigtlConnector = igtl::TCPConnectorServerOIGTL::New(); + oigtlConnector->SetPort(18944); + if (oigtlConnector.IsNotNull()) + { + std::cerr << "Activating OpenIGTLink connector with:" << std::endl; + std::cerr << " Port: " << igtlPort.toInt() << std::endl; + oigtlConnector->SetPort(igtlPort.toInt()); + oigtlConnector->Activate(); + } + } + + rbTrackingFile->setEnabled(false); + rbTrackingRandom->setEnabled(false); + pbFilename->setEnabled(false); + + if (rbTrackingFile->isChecked()) + { + this->TrackingDataReader->SetConnector(oigtlConnector); + this->TrackingDataReader->SetFileName(this->PathString); + this->TrackingDataReader->Start(); + } + else + { + this->TrackingDataGenerator->SetConnector(oigtlConnector); + this->TrackingDataGenerator->Start(); + } + } + } - void OpenIGTLinkSimulatorApp::scannerAddressChanged( const QString & text ) { scannerAddress = text; @@ -175,12 +243,12 @@ void OpenIGTLinkSimulatorApp::changeStatusTextColor(QLineEdit* le, int status) { if (status < igtl::TCPConnectorBase::STATUS_NUM && status >= 0) { - QPalette p = le->palette(); - p.setColor( le->backgroundRole(), - QColor(StatusColorTable[status][0], - StatusColorTable[status][1], - StatusColorTable[status][2]) ); - le->setPalette(p); + QPalette p = le->palette(); + p.setColor( le->backgroundRole(), + QColor(StatusColorTable[status][0], + StatusColorTable[status][1], + StatusColorTable[status][2]) ); + le->setPalette(p); } } @@ -188,12 +256,12 @@ void OpenIGTLinkSimulatorApp::changeDataIOTextColor(QLineEdit* le, int status) { if (status < 3 && status >= 0) { - QPalette p = le->palette(); - p.setColor( le->backgroundRole(), - QColor(DataIOColorTable[status][0], - DataIOColorTable[status][1], - DataIOColorTable[status][2]) ); - le->setPalette(p); + QPalette p = le->palette(); + p.setColor( le->backgroundRole(), + QColor(DataIOColorTable[status][0], + DataIOColorTable[status][1], + DataIOColorTable[status][2]) ); + le->setPalette(p); } } @@ -202,23 +270,32 @@ void OpenIGTLinkSimulatorApp::updateStatus() bool editClientFlag = true; if (oigtlConnector.IsNotNull()) { - leStatusClient->setText(oigtlConnector->GetStatusString()); - changeStatusTextColor(leStatusClient, oigtlConnector->GetStatus()); - leOpenIGTLinkPort->setEnabled(oigtlConnector->GetStatus() == igtl::TCPConnectorBase::STATUS_STOP); - editClientFlag &= oigtlConnector->GetStatus() == igtl::TCPConnectorBase::STATUS_STOP; - if (oigtlConnector->GetStatus() == igtl::TCPConnectorBase::STATUS_STOP) - { - pbClientActivate->setText("Activate"); - } - else - { - pbClientActivate->setText("Deactivate"); - } + leStatusClient->setText(oigtlConnector->GetStatusString()); + changeStatusTextColor(leStatusClient, oigtlConnector->GetStatus()); + leOpenIGTLinkPort->setEnabled(oigtlConnector->GetStatus() == igtl::TCPConnectorBase::STATUS_STOP); + editClientFlag &= oigtlConnector->GetStatus() == igtl::TCPConnectorBase::STATUS_STOP; + if (oigtlConnector->GetStatus() == igtl::TCPConnectorBase::STATUS_STOP) + { + pbClientActivate->setText("Activate"); + } + else + { + pbClientActivate->setText("Deactivate"); + } } + else{ pbAbout->setEnabled(false);} //bool editScannerFlag = true; //leScannerAddress->setEnabled(editScannerFlag); //leControlPort->setEnabled(editScannerFlag); //leImagePort->setEnabled(editClientFlag); + +} + +void OpenIGTLinkSimulatorApp::channel(int i) +{ + std::cerr << "Channel changed to:" << i << std::endl; + this->TrackingDataReader->ChannelChanged(i); + this->TrackingDataGenerator->ChannelChanged(i); } void OpenIGTLinkSimulatorApp::quit() @@ -226,11 +303,10 @@ void OpenIGTLinkSimulatorApp::quit() if (oigtlConnector.IsNotNull()) { - oigtlConnector->CloseThread(); + oigtlConnector->CloseThread(); } - + timer->stop(); close(); -} - +} diff --git a/OpenIGTLinkSimulatorApp.h b/OpenIGTLinkSimulatorApp.h index ec46f30..4829742 100644 --- a/OpenIGTLinkSimulatorApp.h +++ b/OpenIGTLinkSimulatorApp.h @@ -1,15 +1,15 @@ /*========================================================================= - + Program: OpenIGTLink Simulator Language: C++ - + Copyright (c) Brigham and Women's Hospital. All rights reserved. - + This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. - -=========================================================================*/ + + =========================================================================*/ #ifndef OpenIGTLinkSimulatorApp_h #define OpenIGTLinkSimulatorApp_h @@ -20,6 +20,7 @@ #include "igtlMultiThreader.h" #include "igtlTCPConnectorServerOIGTL.h" #include "qDataGeneratorTracking.h" +#include "qDataReadingTracker.h" #define DEFAULT_OIGTL_PORT 18944 #define DEFAULT_SPICE_PORT 2000 @@ -27,56 +28,61 @@ #define DEFAULT_RMP_ADDR "192.168.2.1" - + class OpenIGTLinkSimulatorApp : public QMainWindow, private Ui::OpenIGTLinkSimulatorWindow { Q_OBJECT - -public: + + public: static const int StatusColorTable[][3]; static const int DataIOColorTable[][3]; - -public: + + public: OpenIGTLinkSimulatorApp(QWidget *parent = 0); - -public slots: - void getPath(); - void about(); - - void scannerActivateClicked(); - void clientActivateClicked(); - - void scannerAddressChanged( const QString & text ); - void imagePortChanged( const QString & text ); - void controlPortChanged( const QString & text ); - void igtlPortChanged( const QString & text ); + public slots: + void getPath(); + void about(); + void enable(); + void disable(); + void channel(int i); - void updateStatus(); - void quit(); - -private: + void scannerActivateClicked(); + void clientActivateClicked(); + + void scannerAddressChanged( const QString & text ); + void imagePortChanged( const QString & text ); + void controlPortChanged( const QString & text ); + void igtlPortChanged( const QString & text ); + + void updateStatus(); + void quit(); - void changeStatusTextColor(QLineEdit* le, int status); - void changeDataIOTextColor(QLineEdit* le, int status); + private: + + void changeStatusTextColor(QLineEdit* le, int status); + void changeDataIOTextColor(QLineEdit* le, int status); - QTimer *timer; - igtl::MultiThreader::Pointer Threader; - igtl::TCPConnectorServerOIGTL::Pointer oigtlConnector; + QTimer *timer; + igtl::MultiThreader::Pointer Threader; + igtl::TCPConnectorServerOIGTL::Pointer oigtlConnector; - qDataGeneratorTracking* TrackingDataGenerator; + qDataGeneratorTracking* TrackingDataGenerator; + qDataReadingTracker* TrackingDataReader; + + bool fScannerActive; + bool fClientActive; - bool fScannerActive; - bool fClientActive; + QString scannerAddress; + QString imagePort; + QString controlPort; + QString igtlPort; - QString scannerAddress; - QString imagePort; - QString controlPort; - QString igtlPort; + std::string PathString; }; - - + + #endif diff --git a/OpenIGTLinkSimulatorWindow.ui b/OpenIGTLinkSimulatorWindow.ui index 9726e5b..6599e4d 100644 --- a/OpenIGTLinkSimulatorWindow.ui +++ b/OpenIGTLinkSimulatorWindow.ui @@ -152,8 +152,11 @@ - Ramdom + Random + + rbgDataSource + @@ -161,6 +164,9 @@ From File + + rbgDataSource + @@ -194,7 +200,14 @@ - + + + 1 + + + 3 + + @@ -278,4 +291,7 @@ + + + diff --git a/igtlTCPConnectorBase.cxx b/igtlTCPConnectorBase.cxx index 4d83d89..f2992a8 100644 --- a/igtlTCPConnectorBase.cxx +++ b/igtlTCPConnectorBase.cxx @@ -9,7 +9,7 @@ the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. -=========================================================================*/ + =========================================================================*/ #include @@ -19,90 +19,90 @@ namespace igtl { -const char* TCPConnectorBase::StatusString[] = { - "OFF", - "WAITING", - "CONNECTED", - "ERROR" -}; + const char* TCPConnectorBase::StatusString[] = { + "OFF", + "WAITING", + "CONNECTED", + "ERROR" + }; -//----------------------------------------------------------------------------- -TCPConnectorBase::TCPConnectorBase() -{ - this->Hostname = "localhost"; - this->Port = 0; - this->Active = 0; - this->Status = STATUS_STOP; - - this->ConfigurationUpdated = true; - this->DataReceivedFlag = false; - this->DataSentFlag = false; -} + //----------------------------------------------------------------------------- + TCPConnectorBase::TCPConnectorBase() + { + this->Hostname = "localhost"; + this->Port = 0; + this->Active = 0; + this->Status = STATUS_STOP; -//----------------------------------------------------------------------------- -TCPConnectorBase::~TCPConnectorBase() -{ -} + this->ConfigurationUpdated = true; + this->DataReceivedFlag = false; + this->DataSentFlag = false; + } + //----------------------------------------------------------------------------- + TCPConnectorBase::~TCPConnectorBase() + { + } -//----------------------------------------------------------------------------- -void TCPConnectorBase::PrintSelf(std::ostream& os) const -{ - this->Superclass::PrintSelf(os); -} + //----------------------------------------------------------------------------- + void TCPConnectorBase::PrintSelf(std::ostream& os) const + { + this->Superclass::PrintSelf(os); + } -//----------------------------------------------------------------------------- -void TCPConnectorBase::MonitorThreadFunction(void * ptr) -{ - igtl::MultiThreader::ThreadInfo* info = - static_cast(ptr); - TCPConnectorBase * con = static_cast(info->UserData); + //----------------------------------------------------------------------------- + void TCPConnectorBase::MonitorThreadFunction(void * ptr) + { + igtl::MultiThreader::ThreadInfo* info = + static_cast(ptr); - con->Active = 0; - if (!con->Initialize()) - { - std::cerr << "TCPConnectorBase::MonitorThreadFunction(): Failed to initialize a server socket." << std::endl; - return; - } + TCPConnectorBase * con = static_cast(info->UserData); - while (con->Active >= 0) - { - if (con->ConfigurationUpdated) + con->Active = 0; + if (!con->Initialize()) { - con->ConfigurationUpdated = false; + std::cerr << "TCPConnectorBase::MonitorThreadFunction(): Failed to initialize a server socket." << std::endl; + con->Initialize(); + return; } - con->Status = STATUS_STOP; - while (con->Active) + + while (con->Active >= 0) { - con->Status = STATUS_WAITING; - if(con->WaitForConnection()) - { - con->Status = STATUS_CONNECTED; - while (con->Status == STATUS_CONNECTED) - { - if (con->ReceiveMessage() == 0) - { - // Disconnected - con->CloseConnection(); - con->Status = STATUS_WAITING; - break; - } - con->SetDataReceivedFlag(); - } - } - } - igtl::Sleep(500); - } - - con->Finalize(); + if (con->ConfigurationUpdated) + { + con->ConfigurationUpdated = false; + } + con->Status = STATUS_STOP; + while (con->Active) + { + con->Status = STATUS_WAITING; + if(con->WaitForConnection()) + { + con->Status = STATUS_CONNECTED; + while (con->Status == STATUS_CONNECTED) + { + if (con->ReceiveMessage() == 0) + { + // Disconnected + con->CloseConnection(); + con->Status = STATUS_WAITING; + break; + } + con->SetDataReceivedFlag(); + } + } + } + igtl::Sleep(500); + } + + con->Finalize(); + } + // End of igtl namespace } -} // End of igtl namespace - - diff --git a/igtlTCPConnectorBase.h b/igtlTCPConnectorBase.h index 6cadf11..6568741 100644 --- a/igtlTCPConnectorBase.h +++ b/igtlTCPConnectorBase.h @@ -9,7 +9,7 @@ the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. -=========================================================================*/ + =========================================================================*/ #ifndef __TCPConnectorBase_H #define __TCPConnectorBase_H @@ -52,105 +52,105 @@ namespace igtl #define NOTUSED(x) -class IGTLCommon_EXPORT TCPConnectorBase : public Object -{ -public: + class IGTLCommon_EXPORT TCPConnectorBase : public Object + { + public: - enum { - STATUS_STOP = 0, - STATUS_WAITING, - STATUS_CONNECTED, - STATUS_ERROR, - STATUS_NUM - }; + enum { + STATUS_STOP = 0, + STATUS_WAITING, + STATUS_CONNECTED, + STATUS_ERROR, + STATUS_NUM + }; - static const char* StatusString[]; + static const char* StatusString[]; - typedef TCPConnectorBase Self; - typedef Object Superclass; - typedef SmartPointer Pointer; - typedef SmartPointer ConstPointer; + typedef TCPConnectorBase Self; + typedef Object Superclass; + typedef SmartPointer Pointer; + typedef SmartPointer ConstPointer; - igtlTypeMacro(igtl::TCPConnectorBase, igtl::Object) - igtlNewMacro(igtl::TCPConnectorBase); + igtlTypeMacro(igtl::TCPConnectorBase, igtl::Object) + igtlNewMacro(igtl::TCPConnectorBase); -public: + public: - virtual const char * GetClassName() { return "Base"; }; + virtual const char * GetClassName() { return "Base"; }; - void SetHostname(const char * str) {this->Hostname = str; this->ConfigurationUpdated = true; }; - const char * GetHostname() { return this->Hostname.c_str(); }; - void SetPort(int p) { this->Port = p; this->ConfigurationUpdated = true; }; - int GetPort() { return this->Port; }; + void SetHostname(const char * str) {this->Hostname = str; this->ConfigurationUpdated = true; }; + const char * GetHostname() { return this->Hostname.c_str(); }; + void SetPort(int p) { this->Port = p; this->ConfigurationUpdated = true; }; + int GetPort() { return this->Port; }; - virtual int PushMessage(igtl::MessageBase * NOTUSED(message)) { return 0; }; + virtual int PushMessage(igtl::MessageBase * NOTUSED(message)) { return 0; }; - int SetOutputConnector(igtl::TCPConnectorBase * con) - { - this->OutputConnector = con; - } + int SetOutputConnector(igtl::TCPConnectorBase * con) + { + this->OutputConnector = con; + } - inline int GetStatus() { return this->Status; }; - inline const char* GetStatusString() { return this->StatusString[this->Status]; }; - - inline void Activate() { this->Active = 1; }; - inline void Deactivate() { this->Active = 0; }; - inline void CloseThread() { this->Active = -1; }; - - static void MonitorThreadFunction(void * ptr); - - // Description: - // DataReceivedFlag and DataSentFlag are used to check if there are any received/ - // sent messages through the connector. Those flags are turned ON when the connector - // receives/sents messages, and turned OFF when they are checked by using CheckDataReceived()/ - // CheckDataSent() functions. Those flags are used for data receive/sent indicators in a GUI. - - inline void SetDataReceivedFlag() { this->DataReceivedFlag = true; } - inline void SetDataSentFlag() { this->DataSentFlag = true; } - inline bool CheckDataReceived() - { - bool r = this->DataReceivedFlag; - this->DataReceivedFlag = false; - return r; - } - inline bool CheckDataSent() - { - bool r = this->DataSentFlag; - this->DataSentFlag = false; - return r; - } - - -protected: - - TCPConnectorBase(); - ~TCPConnectorBase(); - - void PrintSelf(std::ostream& os) const; - - // Description: - // Initialization() is called just after starting the - virtual int Initialize() { return 0; }; - virtual int WaitForConnection() { return 0; }; - virtual int ReceiveMessage() { return 0; }; - virtual int CloseConnection() { return 0; }; - virtual int Finalize() { return 0; }; + inline int GetStatus() { return this->Status; }; + inline const char* GetStatusString() { return this->StatusString[this->Status]; }; + + inline void Activate() { this->Active = 1; }; + inline void Deactivate() { this->Active = 0; }; + inline void CloseThread() { this->Active = -1; }; + + static void MonitorThreadFunction(void * ptr); + + // Description: + // DataReceivedFlag and DataSentFlag are used to check if there are any received/ + // sent messages through the connector. Those flags are turned ON when the connector + // receives/sents messages, and turned OFF when they are checked by using CheckDataReceived()/ + // CheckDataSent() functions. Those flags are used for data receive/sent indicators in a GUI. + + inline void SetDataReceivedFlag() { this->DataReceivedFlag = true; } + inline void SetDataSentFlag() { this->DataSentFlag = true; } + inline bool CheckDataReceived() + { + bool r = this->DataReceivedFlag; + this->DataReceivedFlag = false; + return r; + } + inline bool CheckDataSent() + { + bool r = this->DataSentFlag; + this->DataSentFlag = false; + return r; + } + + + protected: + + TCPConnectorBase(); + ~TCPConnectorBase(); + + void PrintSelf(std::ostream& os) const; + + // Description: + // Initialization() is called just after starting the + virtual int Initialize() { return 0; }; + virtual int WaitForConnection() { return 0; }; + virtual int ReceiveMessage() { return 0; }; + virtual int CloseConnection() { return 0; }; + virtual int Finalize() { return 0; }; -protected: + protected: - int Active; // 0: Deactive; 1: Active; -1: exiting - int Status; - std::string Hostname; - int Port; + int Active; // 0: Deactive; 1: Active; -1: exiting + int Status; + std::string Hostname; + int Port; - bool ConfigurationUpdated; + bool ConfigurationUpdated; - bool DataReceivedFlag; - bool DataSentFlag; + bool DataReceivedFlag; + bool DataSentFlag; - TCPConnectorBase::Pointer OutputConnector; + TCPConnectorBase::Pointer OutputConnector; -}; + }; } diff --git a/igtlTCPConnectorClient.cxx b/igtlTCPConnectorClient.cxx index d3490e3..b1feaa8 100644 --- a/igtlTCPConnectorClient.cxx +++ b/igtlTCPConnectorClient.cxx @@ -9,7 +9,7 @@ the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. -=========================================================================*/ + =========================================================================*/ #include "igtlSocket.h" @@ -21,79 +21,79 @@ namespace igtl { -//----------------------------------------------------------------------------- -TCPConnectorClient::TCPConnectorClient() -{ -} - - -//----------------------------------------------------------------------------- -TCPConnectorClient::~TCPConnectorClient() -{ -} + //----------------------------------------------------------------------------- + TCPConnectorClient::TCPConnectorClient() + { + } -//----------------------------------------------------------------------------- -void TCPConnectorClient::PrintSelf(std::ostream& os) const -{ - this->Superclass::PrintSelf(os); -} - + //----------------------------------------------------------------------------- + TCPConnectorClient::~TCPConnectorClient() + { + } -//----------------------------------------------------------------------------- -int TCPConnectorClient::Initialize() -{ - return 1; -} + //----------------------------------------------------------------------------- + void TCPConnectorClient::PrintSelf(std::ostream& os) const + { + this->Superclass::PrintSelf(os); + } -//----------------------------------------------------------------------------- -int TCPConnectorClient::WaitForConnection() -{ - //std::cerr << "TCPConnectorClient::WaitForConnection(): Connecting to server" << std::endl; - this->Socket = NULL; - this->Socket = igtl::ClientSocket::New(); - this->DebugOff(); - if (this->Hostname.length() == 0) - { - return 0; - } - //this->Socket->SetConnectTimeout(1000); - int r = this->Socket->ConnectToServer(this->Hostname.c_str(), this->Port); - this->Socket->SetReceiveTimeout(0); - if (r == 0) // if connected to server - { + //----------------------------------------------------------------------------- + int TCPConnectorClient::Initialize() + { return 1; - } - //igtl::Sleep(1000); - return 0; -} + } + + + //----------------------------------------------------------------------------- + int TCPConnectorClient::WaitForConnection() + { + //std::cerr << "TCPConnectorClient::WaitForConnection(): Connecting to server" << std::endl; + + this->Socket = NULL; + this->Socket = igtl::ClientSocket::New(); + this->DebugOff(); + if (this->Hostname.length() == 0) + { + return 0; + } + //this->Socket->SetConnectTimeout(1000); + int r = this->Socket->ConnectToServer(this->Hostname.c_str(), this->Port); + this->Socket->SetReceiveTimeout(0); + if (r == 0) // if connected to server + { + return 1; + } + //igtl::Sleep(1000); + return 0; + } -//----------------------------------------------------------------------------- -int TCPConnectorClient::ReceiveMessage() -{ - return 0; -} + //----------------------------------------------------------------------------- + int TCPConnectorClient::ReceiveMessage() + { + return 0; + } -//----------------------------------------------------------------------------- -int TCPConnectorClient::CloseConnection() -{ - if (this->Socket.IsNotNull()) - { - this->Socket->CloseSocket(); - } + //----------------------------------------------------------------------------- + int TCPConnectorClient::CloseConnection() + { + if (this->Socket.IsNotNull()) + { + this->Socket->CloseSocket(); + } - return 0; -} + return 0; + } -//----------------------------------------------------------------------------- -int TCPConnectorClient::Finalize() -{ - return 0; -} + //----------------------------------------------------------------------------- + int TCPConnectorClient::Finalize() + { + return 0; + } } // End of igtl namespace diff --git a/igtlTCPConnectorClient.h b/igtlTCPConnectorClient.h index a0dc7af..7ddd3f4 100644 --- a/igtlTCPConnectorClient.h +++ b/igtlTCPConnectorClient.h @@ -9,7 +9,7 @@ the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. -=========================================================================*/ + =========================================================================*/ #ifndef __TCPConnectorClient_H #define __TCPConnectorClient_H @@ -23,39 +23,39 @@ namespace igtl { -class IGTLCommon_EXPORT TCPConnectorClient : public TCPConnectorBase -{ -public: + class IGTLCommon_EXPORT TCPConnectorClient : public TCPConnectorBase + { + public: - typedef TCPConnectorClient Self; - typedef Object Superclass; - typedef SmartPointer Pointer; - typedef SmartPointer ConstPointer; + typedef TCPConnectorClient Self; + typedef Object Superclass; + typedef SmartPointer Pointer; + typedef SmartPointer ConstPointer; - igtlTypeMacro(igtl::TCPConnectorClient, igtl::TCPConnectorBase) - igtlNewMacro(igtl::TCPConnectorClient); + igtlTypeMacro(igtl::TCPConnectorClient, igtl::TCPConnectorBase) + igtlNewMacro(igtl::TCPConnectorClient); -public: + public: - virtual const char * GetClassName() { return "Client"; }; + virtual const char * GetClassName() { return "Client"; }; -protected: - TCPConnectorClient(); - ~TCPConnectorClient(); + protected: + TCPConnectorClient(); + ~TCPConnectorClient(); - void PrintSelf(std::ostream& os) const; + void PrintSelf(std::ostream& os) const; - virtual int Initialize(); - virtual int WaitForConnection(); - virtual int ReceiveMessage(); - virtual int CloseConnection(); - virtual int Finalize(); + virtual int Initialize(); + virtual int WaitForConnection(); + virtual int ReceiveMessage(); + virtual int CloseConnection(); + virtual int Finalize(); -protected: + protected: - igtl::ClientSocket::Pointer Socket; + igtl::ClientSocket::Pointer Socket; -}; + }; } diff --git a/igtlTCPConnectorServer.cxx b/igtlTCPConnectorServer.cxx index 90d4431..b2341b7 100644 --- a/igtlTCPConnectorServer.cxx +++ b/igtlTCPConnectorServer.cxx @@ -9,7 +9,7 @@ the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. -=========================================================================*/ + =========================================================================*/ #include "igtlSocket.h" @@ -20,78 +20,78 @@ namespace igtl { -//----------------------------------------------------------------------------- -TCPConnectorServer::TCPConnectorServer() -{ - this->ServerSocket = igtl::ServerSocket::New(); - this->ServerSocket->DebugOff(); -} - -//----------------------------------------------------------------------------- -TCPConnectorServer::~TCPConnectorServer() -{ -} + //----------------------------------------------------------------------------- + TCPConnectorServer::TCPConnectorServer() + { + this->ServerSocket = igtl::ServerSocket::New(); + this->ServerSocket->DebugOff(); + } + + //----------------------------------------------------------------------------- + TCPConnectorServer::~TCPConnectorServer() + { + } + + + //----------------------------------------------------------------------------- + void TCPConnectorServer::PrintSelf(std::ostream& os) const + { + this->Superclass::PrintSelf(os); + } + + + //----------------------------------------------------------------------------- + int TCPConnectorServer::Initialize() + { + if (this->ServerSocket->CreateServer(this->Port)) + { + return 0; + } + return 1; + } -//----------------------------------------------------------------------------- -void TCPConnectorServer::PrintSelf(std::ostream& os) const -{ - this->Superclass::PrintSelf(os); -} + //----------------------------------------------------------------------------- + int TCPConnectorServer::WaitForConnection() + { + this->Socket = NULL; + if (this->ServerSocket.IsNotNull()) + { + this->Socket = this->ServerSocket->WaitForConnection(1000); + } + if (this->Socket.IsNotNull() && this->Socket->GetConnected()) // if client connected + { + this->Socket->DebugOff(); + return 1; + } -//----------------------------------------------------------------------------- -int TCPConnectorServer::Initialize() -{ - if (this->ServerSocket->CreateServer(this->Port)) - { return 0; - } - return 1; -} + } -//----------------------------------------------------------------------------- -int TCPConnectorServer::WaitForConnection() -{ - this->Socket = NULL; - if (this->ServerSocket.IsNotNull()) - { - this->Socket = this->ServerSocket->WaitForConnection(1000); - } - - if (this->Socket.IsNotNull() && this->Socket->GetConnected()) // if client connected - { - this->Socket->DebugOff(); - return 1; - } - return 0; + //----------------------------------------------------------------------------- + int TCPConnectorServer::CloseConnection() + { + if (this->Socket.IsNotNull()) + { + this->Socket->CloseSocket(); + } -} - - -//----------------------------------------------------------------------------- -int TCPConnectorServer::CloseConnection() -{ - if (this->Socket.IsNotNull()) - { - this->Socket->CloseSocket(); - } - - return 0; -} + return 0; + } -//----------------------------------------------------------------------------- -int TCPConnectorServer::Finalize() -{ - if (this->ServerSocket.IsNotNull()) - { - this->ServerSocket->CloseSocket(); - } + //----------------------------------------------------------------------------- + int TCPConnectorServer::Finalize() + { + if (this->ServerSocket.IsNotNull()) + { + this->ServerSocket->CloseSocket(); + } - return 0; -} + return 0; + } } // End of igtl namespace diff --git a/igtlTCPConnectorServer.h b/igtlTCPConnectorServer.h index 5f186e3..2f5e3f0 100644 --- a/igtlTCPConnectorServer.h +++ b/igtlTCPConnectorServer.h @@ -9,7 +9,7 @@ the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. -=========================================================================*/ + =========================================================================*/ #ifndef __TCPConnectorServer_H @@ -24,42 +24,42 @@ namespace igtl { -class IGTLCommon_EXPORT TCPConnectorServer : public TCPConnectorBase -{ -public: + class IGTLCommon_EXPORT TCPConnectorServer : public TCPConnectorBase + { + public: - typedef TCPConnectorServer Self; - typedef Object Superclass; - typedef SmartPointer Pointer; - typedef SmartPointer ConstPointer; + typedef TCPConnectorServer Self; + typedef Object Superclass; + typedef SmartPointer Pointer; + typedef SmartPointer ConstPointer; - igtlTypeMacro(igtl::TCPConnectorServer, igtl::TCPConnectorBase) - igtlNewMacro(igtl::TCPConnectorServer); + igtlTypeMacro(igtl::TCPConnectorServer, igtl::TCPConnectorBase) + igtlNewMacro(igtl::TCPConnectorServer); -public: + public: - virtual const char * GetClassName() { return "Server"; }; + virtual const char * GetClassName() { return "Server"; }; - igtl::Socket::Pointer& GetSocket() { return this->Socket; }; + igtl::Socket::Pointer& GetSocket() { return this->Socket; }; -protected: - TCPConnectorServer(); - ~TCPConnectorServer(); + protected: + TCPConnectorServer(); + ~TCPConnectorServer(); - void PrintSelf(std::ostream& os) const; + void PrintSelf(std::ostream& os) const; - virtual int Initialize(); - virtual int WaitForConnection(); - virtual int ReceiveMessage() { return 0; }; - virtual int CloseConnection(); - virtual int Finalize(); + virtual int Initialize(); + virtual int WaitForConnection(); + virtual int ReceiveMessage() { return 0; }; + virtual int CloseConnection(); + virtual int Finalize(); -protected: - igtl::ServerSocket::Pointer ServerSocket; - igtl::Socket::Pointer Socket; + protected: + igtl::ServerSocket::Pointer ServerSocket; + igtl::Socket::Pointer Socket; -}; + }; } diff --git a/igtlTCPConnectorServerOIGTL.cxx b/igtlTCPConnectorServerOIGTL.cxx index 156bc8f..ccfa2e0 100644 --- a/igtlTCPConnectorServerOIGTL.cxx +++ b/igtlTCPConnectorServerOIGTL.cxx @@ -1,15 +1,15 @@ /*========================================================================= - + Program: OpenIGTLink Connector Class for OpenIGTLink Simulator Language: C++ - + Copyright (c) Brigham and Women's Hospital. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. - -=========================================================================*/ + + =========================================================================*/ #include "igtlSocket.h" @@ -24,266 +24,267 @@ namespace igtl { -//----------------------------------------------------------------------------- -TCPConnectorServerOIGTL::TCPConnectorServerOIGTL() -{ -} + //----------------------------------------------------------------------------- + TCPConnectorServerOIGTL::TCPConnectorServerOIGTL() + { + } -//----------------------------------------------------------------------------- -TCPConnectorServerOIGTL::~TCPConnectorServerOIGTL() -{ -} + //----------------------------------------------------------------------------- + TCPConnectorServerOIGTL::~TCPConnectorServerOIGTL() + { + } -//----------------------------------------------------------------------------- -void TCPConnectorServerOIGTL::PrintSelf(std::ostream& os) const -{ - this->Superclass::PrintSelf(os); -} + //----------------------------------------------------------------------------- + void TCPConnectorServerOIGTL::PrintSelf(std::ostream& os) const + { + this->Superclass::PrintSelf(os); + } -//----------------------------------------------------------------------------- -int TCPConnectorServerOIGTL::PushMessage(igtl::MessageBase * message) -{ - if (this->Status == STATUS_CONNECTED) - { - if (this->Socket.IsNull()) - { - // Do nothing. - return 1; - } - int r = this->Socket->Send(message->GetPackPointer(), message->GetPackSize()); - if (r) + //----------------------------------------------------------------------------- + int TCPConnectorServerOIGTL::PushMessage(igtl::MessageBase * message) + { + if (this->Status == STATUS_CONNECTED) { - this->SetDataSentFlag(); - return 1; + if (this->Socket.IsNull()) + { + std::cerr << "Socket is null (PushMessage)." << std::endl; + // Do nothing. + return 1; + } + int r = this->Socket->Send(message->GetPackPointer(), message->GetPackSize()); + if (r) + { + this->SetDataSentFlag(); + return 1; + } + else + { + //std::cerr << "TCPConnectorServerOIGTL::PushMessage() : Connection Lost." << std::endl; + return 0; + } } - else + + // TODO: Does ReceiveMessage() in MonitorThreadFunction() returns 0 in this case? + return 0; + } + + + //----------------------------------------------------------------------------- + int TCPConnectorServerOIGTL::Initialize() + { + if (TCPConnectorServer::Initialize()) { - //std::cerr << "TCPConnectorServerOIGTL::PushMessage() : Connection Lost." << std::endl; - return 0; + this->HeaderMsg = igtl::MessageHeader::New(); + return 1; } - } - - // TODO: Does ReceiveMessage() in MonitorThreadFunction() returns 0 in this case? - return 0; -} - - -//----------------------------------------------------------------------------- -int TCPConnectorServerOIGTL::Initialize() -{ - if (TCPConnectorServer::Initialize()) - { - this->HeaderMsg = igtl::MessageHeader::New(); - return 1; - } - - this->HeaderMsg = NULL; - return 0; - -} + + this->HeaderMsg = NULL; + return 0; -//----------------------------------------------------------------------------- -int TCPConnectorServerOIGTL::ReceiveMessage() -{ + } - // std::cerr << "TCPConnectorServerOIGTL::ReceiveMessage() : Waiting for messages." << std::endl; - - // Initialize receive buffer - //this->HeaderMsg->InitPack(); - - igtl::MessageHeader::Pointer header; - header = igtl::MessageHeader::New(); - header->InitPack(); - - if (this->Socket.IsNotNull() && this->Socket->GetConnected()) - { - int r = this->Socket->Receive(header->GetPackPointer(), - header->GetPackSize()); - if (r != header->GetPackSize()) + //----------------------------------------------------------------------------- + int TCPConnectorServerOIGTL::ReceiveMessage() + { + + // std::cerr << "TCPConnectorServerOIGTL::ReceiveMessage() : Waiting for messages." << std::endl; + + // Initialize receive buffer + //this->HeaderMsg->InitPack(); + + igtl::MessageHeader::Pointer header; + header = igtl::MessageHeader::New(); + header->InitPack(); + + if (this->Socket.IsNotNull() && this->Socket->GetConnected()) { - if (r == 0) - { - // Connection closed - return 0; - } - // Wrong message but continue to communicate - //std::cerr << "TCPConnectorServerOIGTL::ReceiveMessage() : Illegal message." << std::endl; - return 1; + int r = this->Socket->Receive(header->GetPackPointer(), + header->GetPackSize()); + if (r != header->GetPackSize()) + { + if (r == 0) + { + // Connection closed + return 0; + } + // Wrong message but continue to communicate + //std::cerr << "TCPConnectorServerOIGTL::ReceiveMessage() : Illegal message." << std::endl; + return 1; + } } - } - else - { - return 0; - } - - // Deserialize the header - header->Unpack(); - - // Check data type and receive data body - MessageHandlerTypeMapType::iterator iter; - iter = this->MessageHandlerTypeMap.find(header->GetDeviceType()); - - qDataGeneratorBase* handler = NULL; - - if (iter != this->MessageHandlerTypeMap.end()) - { - MessageHandlerNameMapType& nameMap = iter->second; - MessageHandlerNameMapType::iterator niter; - std::string key = std::string("+") + header->GetDeviceName(); - niter = nameMap.find(key); - if (niter != nameMap.end()) + else { - handler = niter->second; + return 0; } - else // No handler for this specific message name + + // Deserialize the header + header->Unpack(); + + // Check data type and receive data body + MessageHandlerTypeMapType::iterator iter; + iter = this->MessageHandlerTypeMap.find(header->GetDeviceType()); + + qDataGeneratorBase* handler = NULL; + + if (iter != this->MessageHandlerTypeMap.end()) { - niter = nameMap.find("*"); - if (niter != nameMap.end()) // There is a wild card handler - { - handler = niter->second; - } + MessageHandlerNameMapType& nameMap = iter->second; + MessageHandlerNameMapType::iterator niter; + std::string key = std::string("+") + header->GetDeviceName(); + niter = nameMap.find(key); + if (niter != nameMap.end()) + { + handler = niter->second; + } + else // No handler for this specific message name + { + niter = nameMap.find("*"); + if (niter != nameMap.end()) // There is a wild card handler + { + handler = niter->second; + } + } } - } - - if (handler) - { - handler->HandleReceivedMessage(this->Socket, header); - } - - else // No handler is available for this type of message. - { - if (this->Socket.IsNotNull() && this->Socket->GetConnected()) + + if (handler) { - this->Socket->Skip(header->GetBodySizeToRead(), 0); + handler->HandleReceivedMessage(this->Socket, header); + } + + else // No handler is available for this type of message. + { + if (this->Socket.IsNotNull() && this->Socket->GetConnected()) + { + this->Socket->Skip(header->GetBodySizeToRead(), 0); + } } - } - - - return 1; - -} - -//----------------------------------------------------------------------------- -int TCPConnectorServerOIGTL::Finalize() -{ - if (TCPConnectorServer::Finalize()) - { + return 1; - } - return 0; -} - - -//----------------------------------------------------------------------------- -void TCPConnectorServerOIGTL::RegisterMessageHandler(const char* type, qDataGeneratorBase* handler) -{ - - MessageHandlerTypeMapType::iterator iter; + + } - iter = this->MessageHandlerTypeMap.find(type); - if (iter == this->MessageHandlerTypeMap.end()) // the type has not been registered yet. - { - MessageHandlerNameMapType nameMap; - nameMap["*"] = handler; - this->MessageHandlerTypeMap[type] = nameMap; - } - else - { - MessageHandlerNameMapType& nameMap = iter->second; - nameMap.clear(); - nameMap["*"] = handler; - } - -} - - -//----------------------------------------------------------------------------- -void TCPConnectorServerOIGTL::RegisterMessageHandler(const char* type, const char* name, qDataGeneratorBase* handler) -{ + //----------------------------------------------------------------------------- + int TCPConnectorServerOIGTL::Finalize() + { + if (TCPConnectorServer::Finalize()) + { + return 1; + } + return 0; + } - MessageHandlerTypeMapType::iterator iter; - iter = this->MessageHandlerTypeMap.find(type); - - std::string nkey = std::string("+") + name; - if (iter == this->MessageHandlerTypeMap.end()) // the type has not been registered yet. - { - MessageHandlerNameMapType nameMap; - nameMap[nkey] = handler; - this->MessageHandlerTypeMap[type] = nameMap; - } - else - { - MessageHandlerNameMapType& nameMap = iter->second; - nameMap[nkey] = handler; - } -} - - -//----------------------------------------------------------------------------- -void TCPConnectorServerOIGTL::UnRegisterMessageHandler(const char* type) -{ - - MessageHandlerTypeMapType::iterator iter; + //----------------------------------------------------------------------------- + void TCPConnectorServerOIGTL::RegisterMessageHandler(const char* type, qDataGeneratorBase* handler) + { + + MessageHandlerTypeMapType::iterator iter; + + iter = this->MessageHandlerTypeMap.find(type); + + if (iter == this->MessageHandlerTypeMap.end()) // the type has not been registered yet. + { + MessageHandlerNameMapType nameMap; + nameMap["*"] = handler; + this->MessageHandlerTypeMap[type] = nameMap; + } + else + { + MessageHandlerNameMapType& nameMap = iter->second; + nameMap.clear(); + nameMap["*"] = handler; + } + + } - iter = this->MessageHandlerTypeMap.find(type); - if (iter != this->MessageHandlerTypeMap.end()) // the type is found in the map - { - this->MessageHandlerTypeMap.erase(iter); - } -} - - -//----------------------------------------------------------------------------- -int TCPConnectorServerOIGTL::ReceiveTransform(igtl::MessageHeader * header) -{ - - //std::cerr << "TCPConnectorServerOIGTL::ReceiveTransform() : Receiving TRANSFORM data type." << std::endl; + //----------------------------------------------------------------------------- + void TCPConnectorServerOIGTL::RegisterMessageHandler(const char* type, const char* name, qDataGeneratorBase* handler) + { + + MessageHandlerTypeMapType::iterator iter; + + iter = this->MessageHandlerTypeMap.find(type); + + std::string nkey = std::string("+") + name; + if (iter == this->MessageHandlerTypeMap.end()) // the type has not been registered yet. + { + MessageHandlerNameMapType nameMap; + nameMap[nkey] = handler; + this->MessageHandlerTypeMap[type] = nameMap; + } + else + { + MessageHandlerNameMapType& nameMap = iter->second; + nameMap[nkey] = handler; + } + } - // Create a message buffer to receive transform data - igtl::TransformMessage::Pointer transMsg; - transMsg = igtl::TransformMessage::New(); - transMsg->SetMessageHeader(header); - transMsg->AllocatePack(); - // Receive transform data from the socket - if (this->Socket.IsNotNull() && this->Socket->GetConnected()) - { - int r = this->Socket->Receive(transMsg->GetPackBodyPointer(), transMsg->GetPackBodySize()); - if (r == 0) + //----------------------------------------------------------------------------- + void TCPConnectorServerOIGTL::UnRegisterMessageHandler(const char* type) + { + + MessageHandlerTypeMapType::iterator iter; + + iter = this->MessageHandlerTypeMap.find(type); + + if (iter != this->MessageHandlerTypeMap.end()) // the type is found in the map { - // Connection closed. - return 0; + this->MessageHandlerTypeMap.erase(iter); } - } - else - { - return 0; - } + } - // Deserialize the transform data - // If you want to skip CRC check, call Unpack() without argument. - int c = transMsg->Unpack(1); - if (c & igtl::MessageHeader::UNPACK_BODY) // if CRC check is OK - { - if (this->OutputConnector.IsNotNull()) + //----------------------------------------------------------------------------- + int TCPConnectorServerOIGTL::ReceiveTransform(igtl::MessageHeader * header) + { + + //std::cerr << "TCPConnectorServerOIGTL::ReceiveTransform() : Receiving TRANSFORM data type." << std::endl; + + // Create a message buffer to receive transform data + igtl::TransformMessage::Pointer transMsg; + transMsg = igtl::TransformMessage::New(); + transMsg->SetMessageHeader(header); + transMsg->AllocatePack(); + + // Receive transform data from the socket + if (this->Socket.IsNotNull() && this->Socket->GetConnected()) { - this->OutputConnector->PushMessage(transMsg); + int r = this->Socket->Receive(transMsg->GetPackBodyPointer(), transMsg->GetPackBodySize()); + if (r == 0) + { + // Connection closed. + return 0; + } + } + else + { + return 0; } - return 1; - } - - return 1; -} - + // Deserialize the transform data + // If you want to skip CRC check, call Unpack() without argument. + int c = transMsg->Unpack(1); + + if (c & igtl::MessageHeader::UNPACK_BODY) // if CRC check is OK + { + if (this->OutputConnector.IsNotNull()) + { + this->OutputConnector->PushMessage(transMsg); + } + return 1; + } + + return 1; + } + + } // End of igtl namespace diff --git a/igtlTCPConnectorServerOIGTL.h b/igtlTCPConnectorServerOIGTL.h index dda8b3e..5fb246a 100644 --- a/igtlTCPConnectorServerOIGTL.h +++ b/igtlTCPConnectorServerOIGTL.h @@ -1,15 +1,15 @@ /*========================================================================= - + Program: OpenIGTLink Connector Class for OpenIGTLink Simulator Language: C++ Copyright (c) Brigham and Women's Hospital. All rights reserved. - + This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. -=========================================================================*/ + =========================================================================*/ #ifndef __TCPConnectorServerOIGTL_H @@ -22,108 +22,107 @@ #include "igtlTCPConnectorServer.h" - class qDataGeneratorBase; namespace igtl { -class IGTLCommon_EXPORT TCPConnectorServerOIGTL : public TCPConnectorServer -{ -public: + class IGTLCommon_EXPORT TCPConnectorServerOIGTL : public TCPConnectorServer + { + public: - typedef TCPConnectorServerOIGTL Self; - typedef Object Superclass; - typedef SmartPointer Pointer; - typedef SmartPointer ConstPointer; - - igtlTypeMacro(igtl::TCPConnectorServerOIGTL, igtl::TCPConnectorServer) - igtlNewMacro(igtl::TCPConnectorServerOIGTL); - -public: - - virtual const char * GetClassName() { return "OpenIGTLink"; }; - int SetMessageHandler(); - virtual int PushMessage(igtl::MessageBase * message); - - // Functions to register message handlers. RegisterMessageHandler(type, handler) registers - // a handler for any messages with the specified type, while RegisterMessageHandler(type, name, handler) - // registers handler for messages with the specified type and name. If the functions are called - // multiple times, RegisterMessageHandler(type, name, handler) will 'overwrite' - // the registered information. For example, if those functions are called as: - // - // RegisterMessageHandler("type1", handler1); - // RegisterMessageHandler("type1", "name1", handler2); - // RegisterMessageHandler("type1", "name2", handler3); - // - // the ConnectorServerOIGTL class will use handler2 and hander3 for "type1" messages with - // message names of "name1" and "name2" respectively, and use handler1 for other "type1" - // messages. This handler information is always "overwritten". For example, if the function is called as: - // - // RegisterMessageHandler("type1", "name1", handler2); - // RegisterMessageHandler("type1", "name1", handler3); - // - // "type1" messages with a name "name1" will be handled by handler3. Another example is, if the - // function is called as: - // - // RegisterMessageHandler("type1", "name1", handler2); - // RegisterMessageHandler("type1", "name2", handler3); - // RegisterMessageHandler("type1", handler1); - // - // the last call will overwrite the others, meaning that any type1 message will be handled by handler1. + typedef TCPConnectorServerOIGTL Self; + typedef Object Superclass; + typedef SmartPointer Pointer; + typedef SmartPointer ConstPointer; + + igtlTypeMacro(igtl::TCPConnectorServerOIGTL, igtl::TCPConnectorServer) + igtlNewMacro(igtl::TCPConnectorServerOIGTL); + + public: + + virtual const char * GetClassName() { return "OpenIGTLink"; }; + int SetMessageHandler(); + virtual int PushMessage(igtl::MessageBase * message); + + // Functions to register message handlers. RegisterMessageHandler(type, handler) registers + // a handler for any messages with the specified type, while RegisterMessageHandler(type, name, handler) + // registers handler for messages with the specified type and name. If the functions are called + // multiple times, RegisterMessageHandler(type, name, handler) will 'overwrite' + // the registered information. For example, if those functions are called as: + // + // RegisterMessageHandler("type1", handler1); + // RegisterMessageHandler("type1", "name1", handler2); + // RegisterMessageHandler("type1", "name2", handler3); + // + // the ConnectorServerOIGTL class will use handler2 and hander3 for "type1" messages with + // message names of "name1" and "name2" respectively, and use handler1 for other "type1" + // messages. This handler information is always "overwritten". For example, if the function is called as: + // + // RegisterMessageHandler("type1", "name1", handler2); + // RegisterMessageHandler("type1", "name1", handler3); + // + // "type1" messages with a name "name1" will be handled by handler3. Another example is, if the + // function is called as: + // + // RegisterMessageHandler("type1", "name1", handler2); + // RegisterMessageHandler("type1", "name2", handler3); + // RegisterMessageHandler("type1", handler1); + // + // the last call will overwrite the others, meaning that any type1 message will be handled by handler1. - void RegisterMessageHandler(const char* type, qDataGeneratorBase* handler); - void RegisterMessageHandler(const char* type, const char* name, qDataGeneratorBase* handler); - void UnRegisterMessageHandler(const char* type); - -protected: - - TCPConnectorServerOIGTL(); - ~TCPConnectorServerOIGTL(); - - void PrintSelf(std::ostream& os) const; - - virtual int Initialize(); - virtual int ReceiveMessage(); - virtual int Finalize(); - - int ReceiveTransform(igtl::MessageHeader * header); + void RegisterMessageHandler(const char* type, qDataGeneratorBase* handler); + void RegisterMessageHandler(const char* type, const char* name, qDataGeneratorBase* handler); + void UnRegisterMessageHandler(const char* type); + + protected: + + TCPConnectorServerOIGTL(); + ~TCPConnectorServerOIGTL(); + + void PrintSelf(std::ostream& os) const; + + virtual int Initialize(); + virtual int ReceiveMessage(); + virtual int Finalize(); + + int ReceiveTransform(igtl::MessageHeader * header); -private: + private: + + igtl::MessageHeader::Pointer HeaderMsg; + + // Templates to record message handlers + // The ConnectorServerOIGTL class manages message handlers (generators) based on + // message type string and message name string. The following pseudo code shows a process + // to identify the message handler after receiving a message, given message type TYPE + // and message name NAME + // + // MessageHandlerNameMapType map = MessageHandlerTypeMap[TYPE] + // if (map == Null) + // Skip() + // + // key = '+' + NAME + // qDataGeneratorBase handler = map[key] + // + // if (handler == Null) + // handler = map['*'] + // + // To differenciate the wild card "*" from message name "*", keys for MessageHandlerNameMapType + // is generated by adding '+' at the top of message name string. Therefore, + // + // - key for the wild card: "*" + // - key for string "*": "+*" + + + typedef std::map< std::string, qDataGeneratorBase* > MessageHandlerNameMapType; + typedef std::map< std::string, MessageHandlerNameMapType > MessageHandlerTypeMapType; + + MessageHandlerTypeMapType MessageHandlerTypeMap; + + }; - igtl::MessageHeader::Pointer HeaderMsg; - - // Templates to record message handlers - // The ConnectorServerOIGTL class manages message handlers (generators) based on - // message type string and message name string. The following pseudo code shows a process - // to identify the message handler after receiving a message, given message type TYPE - // and message name NAME - // - // MessageHandlerNameMapType map = MessageHandlerTypeMap[TYPE] - // if (map == Null) - // Skip() - // - // key = '+' + NAME - // qDataGeneratorBase handler = map[key] - // - // if (handler == Null) - // handler = map['*'] - // - // To differenciate the wild card "*" from message name "*", keys for MessageHandlerNameMapType - // is generated by adding '+' at the top of message name string. Therefore, - // - // - key for the wild card: "*" - // - key for string "*": "+*" - - - typedef std::map< std::string, qDataGeneratorBase* > MessageHandlerNameMapType; - typedef std::map< std::string, MessageHandlerNameMapType > MessageHandlerTypeMapType; - - MessageHandlerTypeMapType MessageHandlerTypeMap; - -}; - } #endif //__THREAD_H diff --git a/main.cpp b/main.cpp index 50bf12d..73c4122 100644 --- a/main.cpp +++ b/main.cpp @@ -9,7 +9,7 @@ the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. -=========================================================================*/ + =========================================================================*/ #include diff --git a/qDataGeneratorBase.cpp b/qDataGeneratorBase.cpp index c080584..8da85a5 100644 --- a/qDataGeneratorBase.cpp +++ b/qDataGeneratorBase.cpp @@ -1,15 +1,15 @@ /*========================================================================= - + Program: Data Generator Base Class for OpenIGTLink Simulator Language: C++ - + Copyright (c) Brigham and Women's Hospital. All rights reserved. - + This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. - -=========================================================================*/ + + =========================================================================*/ #include #include "qDataGeneratorBase.h" @@ -18,7 +18,7 @@ //----------------------------------------------------------------------------- qDataGeneratorBase::qDataGeneratorBase() { - this->TimerInterval = 100; // default is 100 ms + this->TimerInterval = 200; // default is 100 ms this->Timer = NULL; } @@ -31,58 +31,53 @@ qDataGeneratorBase::~qDataGeneratorBase() //----------------------------------------------------------------------------- void qDataGeneratorBase::SetConnector(igtl::TCPConnectorServerOIGTL * connector) { - this->Connector = connector; this->RegisterHandlers(connector); - } //----------------------------------------------------------------------------- void qDataGeneratorBase::Start() { + this->Timer = new QTimer(this); connect(this->Timer, SIGNAL(timeout()), this, SLOT(ProcessTimer())); this->Timer->start(this->TimerInterval); + } - //----------------------------------------------------------------------------- void qDataGeneratorBase::Stop() { + if (this->Timer != NULL) { - if (this->Timer->isActive() == true) - { - this->Timer->stop(); - } - - delete this->Timer; - this->Timer = NULL; + if (this->Timer->isActive() == true) + { + this->Timer->stop(); + } + + delete this->Timer; + this->Timer = NULL; } + } //----------------------------------------------------------------------------- void qDataGeneratorBase::ProcessTimer() { - + if (this->Connector.IsNotNull() && this->Connector->GetStatus() == igtl::TCPConnectorBase::STATUS_CONNECTED) { - igtl::MessageBase::Pointer message; - this->GenerateData(message); - if (message.IsNotNull()) - { - this->Connector->PushMessage(message); - } + igtl::MessageBase::Pointer message; + this->GenerateData(message); + this->ReadData(message); + if (message.IsNotNull()) + { + this->Connector->PushMessage(message); + } } + } - - - - - - - - diff --git a/qDataGeneratorBase.h b/qDataGeneratorBase.h index 5dfcf56..69f75db 100644 --- a/qDataGeneratorBase.h +++ b/qDataGeneratorBase.h @@ -1,15 +1,15 @@ /*========================================================================= - + Program: Data Generator Base Class for OpenIGTLink Simulator Language: C++ - + Copyright (c) Brigham and Women's Hospital. All rights reserved. - + This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. - -=========================================================================*/ + + =========================================================================*/ #ifndef __qDataGeneratorBase_H #define __qDataGeneratorBase_H @@ -28,40 +28,42 @@ class IGTLCommon_EXPORT qDataGeneratorBase : public QObject { - + Q_OBJECT - -public: - + + public: + qDataGeneratorBase(); virtual ~qDataGeneratorBase(); - + virtual const char * GetClassName() { return "qDataGeneratorBase"; }; - + void SetInterval(int ms) { this->TimerInterval = ms; }; int GetInterval() { return this->TimerInterval; } void SetConnector(igtl::TCPConnectorServerOIGTL * connector); - + std::string PathString; virtual int HandleReceivedMessage(igtl::Socket *socket, igtl::MessageHeader * header) {}; - + void Start(); void Stop(); - -protected slots: - - void ProcessTimer(); - -protected: -virtual void RegisterHandlers(igtl::TCPConnectorServerOIGTL * NOTUSED(connector)) {}; -virtual void GenerateData(igtl::MessageBase::Pointer& NOTUSED(data)) {}; - -protected: - - QTimer* Timer; - int TimerInterval; - igtl::TCPConnectorServerOIGTL::Pointer Connector; - + + protected slots: + + void ProcessTimer(); + + protected: + + virtual void RegisterHandlers(igtl::TCPConnectorServerOIGTL * NOTUSED(connector)) {}; + virtual void GenerateData(igtl::MessageBase::Pointer& NOTUSED(data)) {}; + virtual void ReadData(igtl::MessageBase::Pointer& NOTUSED(data)) {}; + + protected: + + QTimer* Timer; + int TimerInterval; + igtl::TCPConnectorServerOIGTL::Pointer Connector; + }; diff --git a/qDataGeneratorTracking.cpp b/qDataGeneratorTracking.cpp index 723aa39..8582a33 100644 --- a/qDataGeneratorTracking.cpp +++ b/qDataGeneratorTracking.cpp @@ -1,15 +1,15 @@ /*========================================================================= - + Program: Data Generator Tracking Class for OpenIGTLink Simulator Language: C++ - + Copyright (c) Brigham and Women's Hospital. All rights reserved. - + This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. - -=========================================================================*/ + + =========================================================================*/ #include @@ -21,36 +21,37 @@ //----------------------------------------------------------------------------- qDataGeneratorTracking::qDataGeneratorTracking(): qDataGeneratorBase() { - + //------------------------------------------------------------ // Allocate TrackingData Message Class // // NOTE: TrackingDataElement class instances are allocated // before the loop starts to avoid reallocation // in each image transfer. - + this->TrackingMsg = igtl::TrackingDataMessage::New(); this->TrackingMsg->SetDeviceName("Tracker"); - + this->NumberOfChannels = 3; this->TrackingElement.resize(this->NumberOfChannels); this->Phi.resize(this->NumberOfChannels); this->Theta.resize(this->NumberOfChannels); - + this->fTracking = 0; - - for (int i = 0; i < this->NumberOfChannels; i ++) + + for (int i = 0; i NumberOfChannels; i ++) { - std::stringstream ss; - ss << "Channel " << i; - this->TrackingElement[i] = igtl::TrackingDataElement::New(); - this->TrackingElement[i]->SetName(ss.str().c_str()); - this->TrackingElement[i]->SetType(igtl::TrackingDataElement::TYPE_TRACKER); - this->TrackingMsg->AddTrackingDataElement(this->TrackingElement[i]); - this->Phi[i] = 0.0; - this->Theta[i] = 0.0; + std::stringstream ss; + ss << "Channel " << i; + this->TrackingElement[i] = igtl::TrackingDataElement::New(); + this->TrackingElement[i]->SetName(ss.str().c_str()); + this->TrackingElement[i]->SetType(igtl::TrackingDataElement::TYPE_TRACKER); + this->TrackingMsg->AddTrackingDataElement(this->TrackingElement[i]); + this->Phi[i] = 0.0; + this->Theta[i] = 0.0; } + } @@ -71,23 +72,23 @@ void qDataGeneratorTracking::RegisterHandlers(igtl::TCPConnectorServerOIGTL * co //----------------------------------------------------------------------------- void qDataGeneratorTracking::GenerateData(igtl::MessageBase::Pointer& data) { - + if (this->fTracking) { - igtl::Matrix4x4 matrix; - igtl::TrackingDataElement::Pointer ptr; - - for (int i = 0; i < this->NumberOfChannels; i ++) - { - this->TrackingMsg->GetTrackingDataElement(i, ptr); - GetRandomTestMatrix(matrix, this->Phi[i], this->Theta[i]); - ptr->SetMatrix(matrix); - this->Phi[i] += 0.1*(float)(i+1); - this->Theta[i] += 0.05*(float)(i+1); - } - - this->TrackingMsg->Pack(); - data = this->TrackingMsg; + igtl::Matrix4x4 matrix; + igtl::TrackingDataElement::Pointer ptr; + for (int i = 0; i < this->NumberOfChannels; i ++) + { + this->TrackingMsg->GetTrackingDataElement(i, ptr); + GetRandomTestMatrix(matrix, this->Phi[i], this->Theta[i]); + ptr->SetMatrix(matrix); + + this->Phi[i] += 0.1*(float)(i+1); + this->Theta[i] += 0.05*(float)(i+1); + } + + this->TrackingMsg->Pack(); + data = this->TrackingMsg; } } @@ -95,106 +96,127 @@ void qDataGeneratorTracking::GenerateData(igtl::MessageBase::Pointer& data) //------------------------------------------------------------ int qDataGeneratorTracking::HandleReceivedMessage(igtl::Socket *socket, igtl::MessageHeader * header) { - + std::cerr << "qDataGeneratorTracking::HandleReceivedMessage() : " << header->GetDeviceType() << std::endl; if (strcmp(header->GetDeviceType(), "STT_TDATA") == 0) { - igtl::StartTrackingDataMessage::Pointer sttMsg; - sttMsg = igtl::StartTrackingDataMessage::New(); - sttMsg->SetMessageHeader(header); - sttMsg->AllocatePack(); - - if (socket && socket->GetConnected()) - { - int r = socket->Receive(sttMsg->GetPackBodyPointer(), sttMsg->GetPackBodySize()); - if (r == 0) - { - // Connection closed. - return 0; - } - } - else - { - return 0; - } - - int c = sttMsg->Unpack(1); - - if (c & igtl::MessageHeader::UNPACK_BODY) // if CRC check is OK - { - int interval = sttMsg->GetResolution(); - if (interval > 100) - this->SetInterval(interval); - this->fTracking = 1; - return 1; - } + igtl::StartTrackingDataMessage::Pointer sttMsg; + sttMsg = igtl::StartTrackingDataMessage::New(); + sttMsg->SetMessageHeader(header); + sttMsg->AllocatePack(); + + if (socket && socket->GetConnected()) + { + int r = socket->Receive(sttMsg->GetPackBodyPointer(), sttMsg->GetPackBodySize()); + if (r == 0) + { + // Connection closed. + return 0; + } + } + else + { + return 0; + } + + int c = sttMsg->Unpack(1); + + if (c & igtl::MessageHeader::UNPACK_BODY) // if CRC check is OK + { + int interval = sttMsg->GetResolution(); + if (interval > 100) + this->SetInterval(interval); + this->fTracking = 1; + return 1; + } } else if (strcmp(header->GetDeviceType(), "STP_TDATA") == 0) { - igtl::StopTrackingDataMessage::Pointer stpMsg; - stpMsg = igtl::StopTrackingDataMessage::New(); - stpMsg->SetMessageHeader(header); - stpMsg->AllocatePack(); - //if (socket && socket->GetConnected()) - // { - // //int r = socket->Receive(stpMsg->GetPackBodyPointer(), stpMsg->GetPackBodySize()); - // //if (r == 0) - // // { - // // // Connection closed. - // // return 0; - // // } - // } - //else - // { - // return 0; - // } - // - //int c = stpMsg->Unpack(1); - //if (c & igtl::MessageHeader::UNPACK_BODY) // if CRC check is OK - // { - this->fTracking = 0; - return 1; - //} + igtl::StopTrackingDataMessage::Pointer stpMsg; + stpMsg = igtl::StopTrackingDataMessage::New(); + stpMsg->SetMessageHeader(header); + stpMsg->AllocatePack(); + //if (socket && socket->GetConnected()) + // { + // //int r = socket->Receive(stpMsg->GetPackBodyPointer(), stpMsg->GetPackBodySize()); + // //if (r == 0) + // // { + // // // Connection closed. + // // return 0; + // // } + // } + //else + // { + // return 0; + // } + // + //int c = stpMsg->Unpack(1); + //if (c & igtl::MessageHeader::UNPACK_BODY) // if CRC check is OK + // { + this->fTracking = 0; + return 1; + //} } return 1; - + } //------------------------------------------------------------ void qDataGeneratorTracking::GetRandomTestMatrix(igtl::Matrix4x4& matrix, float phi, float theta) { - + float position[3]; float orientation[4]; - + // random position position[0] = 50.0 * cos(phi); position[1] = 50.0 * sin(phi); position[2] = 50.0 * cos(phi); phi = phi + 0.2; - + // random orientation orientation[0]=0.0; orientation[1]=0.6666666666*cos(theta); orientation[2]=0.577350269189626; orientation[3]=0.6666666666*sin(theta); theta = theta + 0.1; - + //igtl::Matrix4x4 matrix; igtl::QuaternionToMatrix(orientation, matrix); - + matrix[0][3] = position[0]; matrix[1][3] = position[1]; matrix[2][3] = position[2]; - //igtl::PrintMatrix(matrix); + igtl::PrintMatrix(matrix); } +//----------------------------------------------------------------------------- +void qDataGeneratorTracking::ChannelChanged(int i) +{ + this->TrackingMsg = igtl::TrackingDataMessage::New(); + this->TrackingMsg->SetDeviceName("Tracker"); + this->NumberOfChannels = i; + + this->TrackingElement.resize(this->NumberOfChannels); + this->Phi.resize(this->NumberOfChannels); + this->Theta.resize(this->NumberOfChannels); + + this->fTracking = 0; + + for (int i = 0; i < this->NumberOfChannels; i ++) + { + std::stringstream ss; + ss << "Channel " << i; + this->TrackingElement[i] = igtl::TrackingDataElement::New(); + this->TrackingElement[i]->SetName(ss.str().c_str()); + this->TrackingElement[i]->SetType(igtl::TrackingDataElement::TYPE_TRACKER); + this->TrackingMsg->AddTrackingDataElement(this->TrackingElement[i]); + this->Phi[i] = 0.0; + this->Theta[i] = 0.0; + } - - - - +} diff --git a/qDataGeneratorTracking.h b/qDataGeneratorTracking.h index 214a5cb..f33b963 100644 --- a/qDataGeneratorTracking.h +++ b/qDataGeneratorTracking.h @@ -1,19 +1,18 @@ /*========================================================================= - + Program: Data Generator Tracking Class for OpenIGTLink Simulator Language: C++ - + Copyright (c) Brigham and Women's Hospital. All rights reserved. - + This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. - -=========================================================================*/ + + =========================================================================*/ #ifndef __qDataGeneratorTracking_H #define __qDataGeneratorTracking_H - #include "qDataGeneratorBase.h" #include "igtlTrackingDataMessage.h" @@ -21,37 +20,35 @@ class IGTLCommon_EXPORT qDataGeneratorTracking : public qDataGeneratorBase { Q_OBJECT -public: - + public: + qDataGeneratorTracking(); - virtual ~qDataGeneratorTracking(); - + virtual ~qDataGeneratorTracking(); virtual const char * GetClassName() { return "qDataGeneratorTracking"; }; + virtual void ChannelChanged(int i); - -protected: - + protected: + virtual void RegisterHandlers(igtl::TCPConnectorServerOIGTL * connector); virtual void GenerateData(igtl::MessageBase::Pointer& data); - virtual int HandleReceivedMessage(igtl::Socket *socket, igtl::MessageHeader * header); // Function to generate random matrix. void GetRandomTestMatrix(igtl::Matrix4x4& matrix, float phi, float theta); - - -protected: - + + + protected: + igtl::TrackingDataMessage::Pointer TrackingMsg; std::vector TrackingElement; - + std::vector< float > Phi; std::vector< float > Theta; - + int NumberOfChannels; - + int fTracking; - + }; #endif diff --git a/qDataReadingTracker.cpp b/qDataReadingTracker.cpp new file mode 100644 index 0000000..35e34c5 --- /dev/null +++ b/qDataReadingTracker.cpp @@ -0,0 +1,218 @@ +/*========================================================================= + + Program: Data Reading Tracking Class for OpenIGTLink Simulator + Language: C++ + + Copyright (c) Brigham and Women's Hospital. All rights reserved. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + + =========================================================================*/ +#include +#include "qDataReadingTracker.h" + + +//----------------------------------------------------------------------------- +qDataReadingTracker::qDataReadingTracker(): qDataGeneratorBase() +{ + //------------------------------------------------------------ + // Allocate TrackingData Message Class + // + // NOTE: TrackingDataElement class instances are allocated + // before the loop starts to avoid reallocation + // in each image transfer. + + this->TrackingMsg = igtl::TrackingDataMessage::New(); + this->TrackingMsg->SetDeviceName("Tracker"); + + this->NumberOfChannels = 3; + + this->TrackingElement.resize(this->NumberOfChannels); + this->Phi.resize(this->NumberOfChannels); + this->Theta.resize(this->NumberOfChannels); + + this->fTracking = 0; + + for (int i = 0; i NumberOfChannels; i ++) + { + std::stringstream ss; + ss << "Channel " << i; + this->TrackingElement[i] = igtl::TrackingDataElement::New(); + this->TrackingElement[i]->SetName(ss.str().c_str()); + this->TrackingElement[i]->SetType(igtl::TrackingDataElement::TYPE_TRACKER); + this->TrackingMsg->AddTrackingDataElement(this->TrackingElement[i]); + this->Phi[i] = 0.0; + this->Theta[i] = 0.0; + } + +} + + +//----------------------------------------------------------------------------- +qDataReadingTracker::~qDataReadingTracker() +{ +} + + +//----------------------------------------------------------------------------- +void qDataReadingTracker::RegisterHandlers(igtl::TCPConnectorServerOIGTL * connector) +{ + connector->RegisterMessageHandler("STT_TDATA", this); + connector->RegisterMessageHandler("STP_TDATA", this); +} + + +//---------------------------------------------------------------------------- +void qDataReadingTracker::ReadData(igtl::MessageBase::Pointer& data) +{ + if(this->fTracking && FileName!="") + { + float temp; + igtl::Matrix4x4 matrix; + this->count++; + + const char * ccpFileName = FileName.c_str(); + FILE *myfile = std::fopen(ccpFileName, "r"); + + igtl::TrackingDataElement::Pointer ptr; + + for(int k = 0; k < this->NumberOfChannels; k ++) + { + this->TrackingMsg->GetTrackingDataElement(k, ptr); + int counter=0; + while(counterSetMatrix(matrix); + } + fclose(myfile); + this->TrackingMsg->Pack(); + data = this->TrackingMsg; + } + else + { + } + +} + + +//------------------------------------------------------------ +int qDataReadingTracker::HandleReceivedMessage(igtl::Socket *socket, igtl::MessageHeader * header) +{ + + std::cerr << "qDataReadingTracker::HandleReceivedMessage() : " << header->GetDeviceType() << std::endl; + + if (strcmp(header->GetDeviceType(), "STT_TDATA") == 0) + { + igtl::StartTrackingDataMessage::Pointer sttMsg; + sttMsg = igtl::StartTrackingDataMessage::New(); + sttMsg->SetMessageHeader(header); + sttMsg->AllocatePack(); + + if (socket && socket->GetConnected()) + { + int r = socket->Receive(sttMsg->GetPackBodyPointer(), sttMsg->GetPackBodySize()); + if (r == 0) + { + // Connection closed. + return 0; + } + } + else + { + return 0; + } + + int c = sttMsg->Unpack(1); + + if (c & igtl::MessageHeader::UNPACK_BODY) // if CRC check is OK + { + int interval = sttMsg->GetResolution(); + if (interval > 100) + this->SetInterval(interval); + this->fTracking = 1; + return 1; + } + } + else if (strcmp(header->GetDeviceType(), "STP_TDATA") == 0) + { + igtl::StopTrackingDataMessage::Pointer stpMsg; + stpMsg = igtl::StopTrackingDataMessage::New(); + stpMsg->SetMessageHeader(header); + stpMsg->AllocatePack(); + // if (socket && socket->GetConnected()) + //{ + // int r = socket->Receive(stpMsg->GetPackBodyPointer(), stpMsg->GetPackBodySize()); + // if (r == 0) + // { + // // Connection closed. + // return 0; + // } + //} + //else + //{ + // return 0; + //} + // + //int c = stpMsg->Unpack(1); + //if (c & igtl::MessageHeader::UNPACK_BODY) // if CRC check is OK + //{ //up to here + this->fTracking = 0; + return 1; + // } + } + return 1; + +} + + +//------------------------------------------------------------ +void qDataReadingTracker::ChannelChanged(int i) +{ + this->TrackingMsg = igtl::TrackingDataMessage::New(); + this->TrackingMsg->SetDeviceName("Tracker"); + + this->NumberOfChannels = i; + + this->TrackingElement.resize(this->NumberOfChannels); + this->Phi.resize(this->NumberOfChannels); + this->Theta.resize(this->NumberOfChannels); + + this->fTracking = 0; + + for (int i = 0; i < this->NumberOfChannels; i ++) + { + std::stringstream ss; + ss << "Channel " << i; + this->TrackingElement[i] = igtl::TrackingDataElement::New(); + this->TrackingElement[i]->SetName(ss.str().c_str()); + this->TrackingElement[i]->SetType(igtl::TrackingDataElement::TYPE_TRACKER); + this->TrackingMsg->AddTrackingDataElement(this->TrackingElement[i]); + this->Phi[i] = 0.0; + this->Theta[i] = 0.0; + } + +} diff --git a/qDataReadingTracker.h b/qDataReadingTracker.h new file mode 100644 index 0000000..563b03d --- /dev/null +++ b/qDataReadingTracker.h @@ -0,0 +1,60 @@ +/*========================================================================= + + Program: Data Reading Tracking Class for OpenIGTLink Simulator + Language: C++ + + Copyright (c) Brigham and Women's Hospital. All rights reserved. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + + =========================================================================*/ + +#ifndef __qDataReadingTracking_H +#define __qDataReadingTracking_H + +#include + +#include "qDataGeneratorBase.h" +#include "igtlTrackingDataMessage.h" + +class IGTLCommon_EXPORT qDataReadingTracker : public qDataGeneratorBase +{ + Q_OBJECT + + public: + + qDataReadingTracker(); + virtual ~qDataReadingTracker(); + virtual const char * GetClassName() { return "qDataReadingTracking"; }; + + void SetFileName(std::string name) { this->FileName = name; }; + virtual void ChannelChanged(int i); + + protected: + + virtual void RegisterHandlers(igtl::TCPConnectorServerOIGTL * connector); + virtual void ReadData(igtl::MessageBase::Pointer& data); + virtual int HandleReceivedMessage(igtl::Socket *socket, igtl::MessageHeader * header); + + protected: + + igtl::TrackingDataMessage::Pointer TrackingMsg; + std::vector TrackingElement; + + std::vector< float > Phi; + std::vector< float > Theta; + + int NumberOfChannels; + + int fTracking; + + std::string FileName; + int count; +}; + +#endif + + +