CustusX  15.8
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  reportError("IGTLinkClientStreamer: Failed to start streaming");
92  mSocket.reset();
93  return;
94  }
95 
96  // Create a message buffer to receive header
97  mHeaderMsg = igtl::MessageHeader::New();
98 }
99 
100 bool IGTLinkClientStreamer::multipleTryConnectToHost()
101 {
102  // hold here until all attempts are finished
103  int numberOfConnectionAttempts = 5;
104  int baseSleep = 300;
105  for (int i=0; i<numberOfConnectionAttempts; ++i)
106  {
107  if (i>0)
108  report(QString("[%2] Attempt %1 to connect to host").arg(i+1).arg(this->hostDescription()));
109  if (this->tryConnectToHost())
110  return true;
111  sleep_ms(baseSleep*(i+1));
112  }
113  reportError(QString("[%1] Timeout connecting to host").arg(this->hostDescription()));
114  return false;
115 }
116 
117 bool IGTLinkClientStreamer::tryConnectToHost()
118 {
119  mSocket->connectToHost(mAddress, mPort);
120 
121  int timeout = 5000;
122  if (!mSocket->waitForConnected(timeout))
123  {
124  mSocket->disconnectFromHost();
125  return false;
126  }
127  return true;
128 }
129 
131 {
132  if (mSocket)
133  {
134  mSocket->disconnectFromHost();
135  mSocket.reset();
136  }
137  mSender.reset();
138 }
139 
141 {
142  return (mSocket && mSocket->isValid());
143 }
144 
145 QString IGTLinkClientStreamer::hostDescription() const
146 {
147  return mAddress + ":" + qstring_cast(mPort);
148 }
149 
150 void IGTLinkClientStreamer::hostFoundSlot()
151 {
152  report(QString("[%1] Found host").arg(this->hostDescription()));
153 // report("Host found: " + this->hostDescription());
154 }
155 void IGTLinkClientStreamer::connectedSlot()
156 {
157  reportSuccess(QString("[%1] Connected to host").arg(this->hostDescription()));
158 }
159 void IGTLinkClientStreamer::disconnectedSlot()
160 {
161  report(QString("[%1] Disconnected from host").arg(this->hostDescription()));
162 // report("Disconnected from host " + this->hostDescription());
163 }
164 void IGTLinkClientStreamer::errorSlot(QAbstractSocket::SocketError socketError)
165 {
166  report(QString("[%1] Socket error [code=%2]: %3")
167  .arg(this->hostDescription())
168  .arg(QString::number(socketError))
169  .arg(mSocket->errorString()));
170 }
171 
172 void IGTLinkClientStreamer::readyReadSlot()
173 {
174  // read messages until one fails
175  while (this->readOneMessage());
176 }
177 
182 bool IGTLinkClientStreamer::readOneMessage()
183 {
184 
185 // std::cout << "tick " << std::endl;
186 
187  if (!mHeadingReceived)
188  {
189 // std::cout << "client::tick: received: " << mSocket->bytesAvailable() << ", head needed: " << mHeaderMsg->GetPackSize() << std::endl;
190  // Initialize receive buffer
191  mHeaderMsg->InitPack();
192 
193  // ignore if not enough data (yet)
194  if (mSocket->bytesAvailable() < mHeaderMsg->GetPackSize())
195  {
196  //std::cout << "Incomplete heading received, ignoring. " << std::endl;
197  //std::cout << "available: " << mSocket->bytesAvailable() << ", needed " << mHeaderMsg->GetPackSize() << std::endl;
198  return false;
199  }
200 
201  // after peek: read to increase pos
202  mSocket->read(reinterpret_cast<char*>(mHeaderMsg->GetPackPointer()), mHeaderMsg->GetPackSize());
203  mHeadingReceived = true;
204 
205  // Deserialize the header
206  mHeaderMsg->Unpack();
207  }
208 
209  if (mHeadingReceived)
210  {
211 // std::cout << "client::tick: received: " << mSocket->bytesAvailable() << ", body needed: " << mHeaderMsg->GetBodySizeToRead() << std::endl;
212  bool success = false;
213  // Check data type and receive data body
214 // if (QString(mHeaderMsg->GetDeviceType()) == "TRANSFORM")
215 // {
216 // ReceiveTransform(mSocket, mHeaderMsg);
217 // }
218 // else if (QString(mHeaderMsg->GetDeviceType() == "POSITION")
219 // {
220 // ReceivePosition(mSocket, mHeaderMsg);
221 // }
222  if (QString(mHeaderMsg->GetDeviceType()) == "IMAGE")
223  {
224  success = this->ReceiveImage(mSocket.get(), mHeaderMsg);
225  }
226  else if (QString(mHeaderMsg->GetDeviceType()) == "CX_US_ST")
227  {
228  success = this->ReceiveSonixStatus(mSocket.get(), mHeaderMsg);
229  }
230 // else if (QString(mHeaderMsg->GetDeviceType() == "STATUS")
231 // {
232 // ReceiveStatus(mSocket, mHeaderMsg);
233 // }
234  else
235  {
236  std::cerr << "Receiving : " << mHeaderMsg->GetDeviceType() << std::endl;
237  mSocket->read(mHeaderMsg->GetBodySizeToRead());
238  }
239 
240  if (success)
241  mHeadingReceived = false; // restart
242  else
243  return false;
244  }
245 // std::cout << " tock " << std::endl;
246  return true;
247 }
248 
249 bool IGTLinkClientStreamer::ReceiveSonixStatus(QTcpSocket* socket, igtl::MessageHeader::Pointer& header)
250 {
252  msg = IGTLinkUSStatusMessage::New();
253  msg->SetMessageHeader(header);
254  msg->AllocatePack();
255 
256  if (socket->bytesAvailable() < msg->GetPackBodySize())
257  {
258  //std::cout << "Incomplete body received, ignoring. " << std::endl;
259  return false;
260  }
261  socket->read(reinterpret_cast<char*>(msg->GetPackBodyPointer()), msg->GetPackBodySize());
262  // Deserialize the transform data
263  // If you want to do a CRC check, call Unpack(1).
264  // If you want to skip CRC check, call Unpack() without argument.
265  int c = msg->Unpack();
266  if (c & (igtl::MessageHeader::UNPACK_BODY | igtl::MessageHeader::UNPACK_UNDEF)) // if CRC check is OK or skipped
267  {
268  this->addToQueue(msg);
269 
270  return true;
271  }
272 
273  std::cout << "body crc failed!" << std::endl;
274  return true;
275 }
276 
277 bool IGTLinkClientStreamer::ReceiveImage(QTcpSocket* socket, igtl::MessageHeader::Pointer& header)
278 {
279  // Create a message buffer to receive transform data
281  imgMsg = IGTLinkImageMessage::New();
282  imgMsg->SetMessageHeader(header);
283  imgMsg->AllocatePack();
284 
285  // Receive transform data from the socket
286  // ignore if not enough data (yet)
287  if (socket->bytesAvailable() < imgMsg->GetPackBodySize())
288  {
289  //std::cout << "Incomplete body received, ignoring. " << std::endl;
290  return false;
291  }
292 
293  socket->read(reinterpret_cast<char*>(imgMsg->GetPackBodyPointer()), imgMsg->GetPackBodySize());
294  // Deserialize the transform data
295  // If you want to do a CRC check, call Unpack(1).
296  // If you want to skip CRC check, call Unpack() without argument.
297  int c = imgMsg->Unpack();
298 
299  if (c & (igtl::MessageHeader::UNPACK_BODY | igtl::MessageHeader::UNPACK_UNDEF)) // if CRC check is OK or skipped
300  {
301  this->addToQueue(imgMsg);
302  return true;
303  }
304 
305  std::cout << "body crc failed!" << std::endl;
306  return true;
307 }
308 
309 void IGTLinkClientStreamer::addToQueue(IGTLinkUSStatusMessage::Pointer msg)
310 {
311  // set temporary, then assume the image adder will pass this message on.
312  mUnsentUSStatusMessage = msg;
313 }
314 
315 void IGTLinkClientStreamer::addToQueue(IGTLinkImageMessage::Pointer msg)
316 {
317  IGTLinkConversion converter;
318 
319  PackagePtr package(new Package());
320  package->mIgtLinkImageMessage = msg;
321 
322  // if us status not sent, do it here
323  if (mUnsentUSStatusMessage)
324  {
325  package->mIgtLinkUSStatusMessage = mUnsentUSStatusMessage;
326  mUnsentUSStatusMessage = IGTLinkUSStatusMessage::Pointer();
327  }
328 
329  mSender->send(package);
330 }
331 
332 
333 } // namespace cx
334 
335 
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)