CustusX  15.3.4-beta
An IGT application
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
cxIGTLinkClientStreamer.cpp
Go to the documentation of this file.
1 /*=========================================================================
2 This file is part of CustusX, an Image Guided Therapy Application.
3 
4 Copyright (c) 2008-2014, SINTEF Department of Medical Technology
5 All rights reserved.
6 
7 Redistribution and use in source and binary forms, with or without
8 modification, are permitted provided that the following conditions are met:
9 
10 1. Redistributions of source code must retain the above copyright notice,
11  this list of conditions and the following disclaimer.
12 
13 2. Redistributions in binary form must reproduce the above copyright notice,
14  this list of conditions and the following disclaimer in the documentation
15  and/or other materials provided with the distribution.
16 
17 3. Neither the name of the copyright holder nor the names of its contributors
18  may be used to endorse or promote products derived from this software
19  without specific prior written permission.
20 
21 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
22 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
24 DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
25 FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
27 SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
28 CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
29 OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30 OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31 =========================================================================*/
33 
34 #include <QTcpSocket>
35 #include "igtlOSUtil.h"
36 #include "igtlMessageHeader.h"
37 #include "igtlTransformMessage.h"
38 #include "igtlPositionMessage.h"
39 #include "igtlImageMessage.h"
40 #include "igtlClientSocket.h"
41 #include "igtlStatusMessage.h"
42 
43 #include "cxTypeConversions.h"
44 #include "cxLogger.h"
45 #include "cxIGTLinkConversion.h"
46 #include "cxCyclicActionLogger.h"
47 #include "cxUtilHelpers.h"
48 #include "cxSender.h"
49 
50 namespace cx
51 {
52 
54  mHeadingReceived(false),
55  mAddress(""),
56  mPort(0)
57 {
58 }
59 
61 {
62 
63 }
64 
65 void IGTLinkClientStreamer::setAddress(QString address, int port)
66 {
67  mAddress = address;
68  mPort = port;
69 }
70 
71 
73 {
74  mSender = sender;
75 // this->createSendTimer();
76 // mTestTimer = new QTimer(this);
77 // connect(mTestTimer, SIGNAL(timeout()), this, SLOT(myStreamSlot()));
78 // std::cout << "IGTLinkClientStreamer::startStreaming " << std::endl;
79 
80  // Establish Connection
81  mSocket.reset(new QTcpSocket());
82  connect(mSocket.get(), SIGNAL(readyRead()), this, SLOT(readyReadSlot()), Qt::DirectConnection);
83  connect(mSocket.get(), SIGNAL(hostFound()), this, SLOT(hostFoundSlot()), Qt::DirectConnection);
84  connect(mSocket.get(), SIGNAL(connected()), this, SLOT(connectedSlot()), Qt::DirectConnection);
85  connect(mSocket.get(), SIGNAL(disconnected()), this, SLOT(disconnectedSlot()), Qt::DirectConnection);
86  connect(mSocket.get(), SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(errorSlot(QAbstractSocket::SocketError)),
87  Qt::DirectConnection);
88 
89  if (!this->multipleTryConnectToHost())
90  {
91  mSocket.reset();
92  return false;
93  }
94 
95  // Create a message buffer to receive header
96  mHeaderMsg = igtl::MessageHeader::New();
97 
98 
99  return true;
100 }
101 
102 bool IGTLinkClientStreamer::multipleTryConnectToHost()
103 {
104  // hold here until all attempts are finished
105  int numberOfConnectionAttempts = 5;
106  int baseSleep = 300;
107  for (int i=0; i<numberOfConnectionAttempts; ++i)
108  {
109  if (i>0)
110  report(QString("[%2] Attempt %1 to connect to host").arg(i+1).arg(this->hostDescription()));
111  if (this->tryConnectToHost())
112  return true;
113  sleep_ms(baseSleep*(i+1));
114  }
115  reportError(QString("[%1] Timeout connecting to host").arg(this->hostDescription()));
116  return false;
117 }
118 
119 bool IGTLinkClientStreamer::tryConnectToHost()
120 {
121  mSocket->connectToHost(mAddress, mPort);
122 
123  int timeout = 5000;
124  if (!mSocket->waitForConnected(timeout))
125  {
126  mSocket->disconnectFromHost();
127  return false;
128  }
129  return true;
130 }
131 
133 {
134  if (mSocket)
135  {
136  mSocket->disconnectFromHost();
137  mSocket.reset();
138  }
139  mSender.reset();
140 }
141 
143 {
144  return "IGTLinkClient";
145 }
146 
147 QString IGTLinkClientStreamer::hostDescription() const
148 {
149  return mAddress + ":" + qstring_cast(mPort);
150 }
151 
152 void IGTLinkClientStreamer::hostFoundSlot()
153 {
154  report(QString("[%1] Found host").arg(this->hostDescription()));
155 // report("Host found: " + this->hostDescription());
156 }
157 void IGTLinkClientStreamer::connectedSlot()
158 {
159  reportSuccess(QString("[%1] Connected to host").arg(this->hostDescription()));
160 }
161 void IGTLinkClientStreamer::disconnectedSlot()
162 {
163  report(QString("[%1] Disconnected from host").arg(this->hostDescription()));
164 // report("Disconnected from host " + this->hostDescription());
165 }
166 void IGTLinkClientStreamer::errorSlot(QAbstractSocket::SocketError socketError)
167 {
168  report(QString("[%1] Socket error [code=%2]: %3")
169  .arg(this->hostDescription())
170  .arg(QString::number(socketError))
171  .arg(mSocket->errorString()));
172 }
173 
174 void IGTLinkClientStreamer::readyReadSlot()
175 {
176  // read messages until one fails
177  while (this->readOneMessage());
178 }
179 
184 bool IGTLinkClientStreamer::readOneMessage()
185 {
186 
187 // std::cout << "tick " << std::endl;
188 
189  if (!mHeadingReceived)
190  {
191 // std::cout << "client::tick: received: " << mSocket->bytesAvailable() << ", head needed: " << mHeaderMsg->GetPackSize() << std::endl;
192  // Initialize receive buffer
193  mHeaderMsg->InitPack();
194 
195  // ignore if not enough data (yet)
196  if (mSocket->bytesAvailable() < mHeaderMsg->GetPackSize())
197  {
198  //std::cout << "Incomplete heading received, ignoring. " << std::endl;
199  //std::cout << "available: " << mSocket->bytesAvailable() << ", needed " << mHeaderMsg->GetPackSize() << std::endl;
200  return false;
201  }
202 
203  // after peek: read to increase pos
204  mSocket->read(reinterpret_cast<char*>(mHeaderMsg->GetPackPointer()), mHeaderMsg->GetPackSize());
205  mHeadingReceived = true;
206 
207  // Deserialize the header
208  mHeaderMsg->Unpack();
209  }
210 
211  if (mHeadingReceived)
212  {
213 // std::cout << "client::tick: received: " << mSocket->bytesAvailable() << ", body needed: " << mHeaderMsg->GetBodySizeToRead() << std::endl;
214  bool success = false;
215  // Check data type and receive data body
216 // if (QString(mHeaderMsg->GetDeviceType()) == "TRANSFORM")
217 // {
218 // ReceiveTransform(mSocket, mHeaderMsg);
219 // }
220 // else if (QString(mHeaderMsg->GetDeviceType() == "POSITION")
221 // {
222 // ReceivePosition(mSocket, mHeaderMsg);
223 // }
224  if (QString(mHeaderMsg->GetDeviceType()) == "IMAGE")
225  {
226  success = this->ReceiveImage(mSocket.get(), mHeaderMsg);
227  }
228  else if (QString(mHeaderMsg->GetDeviceType()) == "CX_US_ST")
229  {
230  success = this->ReceiveSonixStatus(mSocket.get(), mHeaderMsg);
231  }
232 // else if (QString(mHeaderMsg->GetDeviceType() == "STATUS")
233 // {
234 // ReceiveStatus(mSocket, mHeaderMsg);
235 // }
236  else
237  {
238  std::cerr << "Receiving : " << mHeaderMsg->GetDeviceType() << std::endl;
239  mSocket->read(mHeaderMsg->GetBodySizeToRead());
240  }
241 
242  if (success)
243  mHeadingReceived = false; // restart
244  else
245  return false;
246  }
247 // std::cout << " tock " << std::endl;
248  return true;
249 }
250 
251 bool IGTLinkClientStreamer::ReceiveSonixStatus(QTcpSocket* socket, igtl::MessageHeader::Pointer& header)
252 {
254  msg = IGTLinkUSStatusMessage::New();
255  msg->SetMessageHeader(header);
256  msg->AllocatePack();
257 
258  if (socket->bytesAvailable() < msg->GetPackBodySize())
259  {
260  //std::cout << "Incomplete body received, ignoring. " << std::endl;
261  return false;
262  }
263  socket->read(reinterpret_cast<char*>(msg->GetPackBodyPointer()), msg->GetPackBodySize());
264  // Deserialize the transform data
265  // If you want to do a CRC check, call Unpack(1).
266  // If you want to skip CRC check, call Unpack() without argument.
267  int c = msg->Unpack();
268  if (c & (igtl::MessageHeader::UNPACK_BODY | igtl::MessageHeader::UNPACK_UNDEF)) // if CRC check is OK or skipped
269  {
270  this->addToQueue(msg);
271 
272  return true;
273  }
274 
275  std::cout << "body crc failed!" << std::endl;
276  return true;
277 }
278 
279 bool IGTLinkClientStreamer::ReceiveImage(QTcpSocket* socket, igtl::MessageHeader::Pointer& header)
280 {
281  // Create a message buffer to receive transform data
283  imgMsg = IGTLinkImageMessage::New();
284  imgMsg->SetMessageHeader(header);
285  imgMsg->AllocatePack();
286 
287  // Receive transform data from the socket
288  // ignore if not enough data (yet)
289  if (socket->bytesAvailable() < imgMsg->GetPackBodySize())
290  {
291  //std::cout << "Incomplete body received, ignoring. " << std::endl;
292  return false;
293  }
294 
295  socket->read(reinterpret_cast<char*>(imgMsg->GetPackBodyPointer()), imgMsg->GetPackBodySize());
296  // Deserialize the transform data
297  // If you want to do a CRC check, call Unpack(1).
298  // If you want to skip CRC check, call Unpack() without argument.
299  int c = imgMsg->Unpack();
300 
301  if (c & (igtl::MessageHeader::UNPACK_BODY | igtl::MessageHeader::UNPACK_UNDEF)) // if CRC check is OK or skipped
302  {
303  this->addToQueue(imgMsg);
304  return true;
305  }
306 
307  std::cout << "body crc failed!" << std::endl;
308  return true;
309 }
310 
311 void IGTLinkClientStreamer::addToQueue(IGTLinkUSStatusMessage::Pointer msg)
312 {
313  // set temporary, then assume the image adder will pass this message on.
314  mUnsentUSStatusMessage = msg;
315 }
316 
317 void IGTLinkClientStreamer::addToQueue(IGTLinkImageMessage::Pointer msg)
318 {
319  IGTLinkConversion converter;
320 
321  PackagePtr package(new Package());
322  package->mIgtLinkImageMessage = msg;
323 
324  // if us status not sent, do it here
325  if (mUnsentUSStatusMessage)
326  {
327  package->mIgtLinkUSStatusMessage = mUnsentUSStatusMessage;
328  mUnsentUSStatusMessage = IGTLinkUSStatusMessage::Pointer();
329  }
330 
331  mSender->send(package);
332 }
333 
334 
335 } // namespace cx
336 
337 
QString qstring_cast(const T &val)
void reportError(QString msg)
Definition: cxLogger.cpp:92
void reportSuccess(QString msg)
Definition: cxLogger.cpp:93
boost::shared_ptr< struct Package > PackagePtr
void report(QString msg)
Definition: cxLogger.cpp:90
boost::shared_ptr< Sender > SenderPtr
Definition: cxSender.h:88
void sleep_ms(int ms)