2.12.2021, 9:00 - 11:00: Due to updates GitLab may be unavailable for some minutes between 09:00 and 11:00.

openigtlinkclient.cpp 20.2 KB
Newer Older
CAMP C++ Builder's avatar
CAMP C++ Builder committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// ================================================================================================
// 
// This file is part of the CAMPVis Software Framework.
// 
// If not explicitly stated otherwise: Copyright (C) 2012-2014, all rights reserved,
//      Christian Schulte zu Berge <christian.szb@in.tum.de>
//      Chair for Computer Aided Medical Procedures
//      Technische Universitaet Muenchen
//      Boltzmannstr. 3, 85748 Garching b. Muenchen, Germany
// 
// For a full list of authors and contributors, please refer to the file "AUTHORS.txt".
// 
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file 
// except in compliance with the License. You may obtain a copy of the License at
// 
// http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software distributed under the 
// License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 
// either express or implied. See the License for the specific language governing permissions 
// and limitations under the License.
// 
// ================================================================================================

#include "openigtlinkclient.h"

27
28
#include "core/datastructures/transformdata.h"
#include "core/datastructures/positiondata.h"
CAMP C++ Builder's avatar
CAMP C++ Builder committed
29
30
31
32
33
34
35
36
37
38
39
40
41

#include <igtlTransformMessage.h>
#include <igtlPositionMessage.h>

#include "core/datastructures/imagedata.h"
#include "core/datastructures/genericimagerepresentationlocal.h"
#include "core/tools/stringutils.h"

namespace campvis {
    const std::string OpenIGTLinkClient::loggerCat_ = "CAMPVis.modules.openigtlink.client";

    OpenIGTLinkClient::OpenIGTLinkClient() 
        : AbstractProcessor()
42
        , p_address("ServerAddress", "Server Address", "127.0.0.1")
CAMP C++ Builder's avatar
CAMP C++ Builder committed
43
44
45
        , p_port("ServerPort", "Server Port", 18944, 1, 65535, 1)
        , p_deviceName("ServerDeviceName", "Device Name (empty to accept all)")
        , p_connect("Connect", "Connect to Server")
46
        , p_disconnect("Disconnect", "Disconnect from Server")
CAMP C++ Builder's avatar
CAMP C++ Builder committed
47
        , p_receiveImages("ReceiveImages", "Receive IMAGE Messages", false)
48
        , p_targetImagePrefix("targetImageName", "Target Image Prefix", "IGTL.image.")
CAMP C++ Builder's avatar
CAMP C++ Builder committed
49
        , p_receiveTransforms("ReceiveTransforms", "Receive TRANSFORM Messages", true)
50
        , p_targetTransformPrefix("targetTransformPrefix", "Target Transform Prefix", "IGTL.transform.")
51
52
        , p_imageOffset("ImageOffset", "Image Offset in mm", cgt::vec3(0.f), cgt::vec3(-10000.f), cgt::vec3(10000.f), cgt::vec3(0.1f))
        , p_voxelSize("VoxelSize", "Voxel Size in mm", cgt::vec3(1.f), cgt::vec3(-100.f), cgt::vec3(100.f), cgt::vec3(0.1f))
CAMP C++ Builder's avatar
CAMP C++ Builder committed
53
        , p_receivePositions("ReceivePositions", "Receive POSITION Messages", true)
54
        , p_targetPositionPrefix("targetPositionsPrefix", "Target Position Prefix", "IGTL.position.")
55
56
57
        , _stopExecution()
        , _receiverThread(nullptr)
        , _receiverRunning()
CAMP C++ Builder's avatar
CAMP C++ Builder committed
58
    {
59
60
61
        _stopExecution = false;
        _receiverRunning = false;

CAMP C++ Builder's avatar
CAMP C++ Builder committed
62
63
64
        addProperty(p_address, VALID);
        addProperty(p_port, VALID);
        addProperty(p_deviceName, VALID);
CAMP C++ Builder's avatar
CAMP C++ Builder committed
65
66

        addProperty(p_connect, VALID);
67
        addProperty(p_disconnect, VALID);
CAMP C++ Builder's avatar
CAMP C++ Builder committed
68

69
70
        addProperty(p_receiveTransforms, INVALID_PROPERTIES);
        addProperty(p_receiveImages, INVALID_PROPERTIES);
71
72
        addProperty(p_targetTransformPrefix, VALID);
        addProperty(p_targetImagePrefix, VALID);
CAMP C++ Builder's avatar
CAMP C++ Builder committed
73
74
        addProperty(p_imageOffset, VALID);
        addProperty(p_voxelSize, VALID);
75
        addProperty(p_receivePositions, INVALID_PROPERTIES);
76
        addProperty(p_targetPositionPrefix, VALID);
77

78
        invalidate(INVALID_PROPERTIES);
79
80


CAMP C++ Builder's avatar
CAMP C++ Builder committed
81
82
83
    }

    OpenIGTLinkClient::~OpenIGTLinkClient() {
84
85
        if (_receiverRunning)
            stopReceiver();
CAMP C++ Builder's avatar
CAMP C++ Builder committed
86
87
88
    }

    void OpenIGTLinkClient::init() {
89
90
        p_connect.s_clicked.connect(this, &OpenIGTLinkClient::connect);
        p_disconnect.s_clicked.connect(this, &OpenIGTLinkClient::disconnect);
91
        p_disconnect.setVisible(false);
CAMP C++ Builder's avatar
CAMP C++ Builder committed
92
93
94
    }

    void OpenIGTLinkClient::deinit() {
95
        stopReceiver();
CAMP C++ Builder's avatar
CAMP C++ Builder committed
96
        p_connect.s_clicked.disconnect(this);
97
        p_disconnect.s_clicked.disconnect(this);
CAMP C++ Builder's avatar
CAMP C++ Builder committed
98
99
100
101
102
103
    }

    void OpenIGTLinkClient::updateResult(DataContainer& data) {

        if(p_receiveTransforms.getValue()) 
        {
104
105
106
            _transformMutex.lock();
            for(auto it = _receivedTransforms.begin(), end = _receivedTransforms.end(); it != end; ++it) { 
                TransformData * td = new TransformData(it->second);
CAMP C++ Builder's avatar
CAMP C++ Builder committed
107
        
108
                data.addData(p_targetTransformPrefix.getValue() + it->first, td);
109
#ifdef IGTL_CLIENT_DEBUGGING
CAMP C++ Builder's avatar
CAMP C++ Builder committed
110
                LDEBUG("Transform data put into container. ");
111
#endif
CAMP C++ Builder's avatar
CAMP C++ Builder committed
112
            }
113
114
            _receivedTransforms.clear();
            _transformMutex.unlock();
CAMP C++ Builder's avatar
CAMP C++ Builder committed
115
116
117
118
        }

        if(p_receiveImages.getValue()) 
        {
119
120
            _imageMutex.lock();
            for(auto it = _receivedImages.begin(), end = _receivedImages.end(); it != end; ++it)
CAMP C++ Builder's avatar
CAMP C++ Builder committed
121
            {
122
                igtl::ImageMessage::Pointer imageMessage = it->second;    
CAMP C++ Builder's avatar
CAMP C++ Builder committed
123
124
                WeaklyTypedPointer wtp;
                wtp._pointer = new uint8_t[imageMessage->GetImageSize()];
125
#ifdef IGTL_CLIENT_DEBUGGING
CAMP C++ Builder's avatar
CAMP C++ Builder committed
126
                LDEBUG("Image has " << imageMessage->GetNumComponents() << " components and is of size " << imageMessage->GetImageSize());
127
#endif
CAMP C++ Builder's avatar
CAMP C++ Builder committed
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
                memcpy(wtp._pointer, imageMessage->GetScalarPointer(), imageMessage->GetImageSize());
                wtp._numChannels = imageMessage->GetNumComponents();

                switch (imageMessage->GetScalarType()) {
                case igtl::ImageMessage::TYPE_INT8:
                    wtp._baseType = WeaklyTypedPointer::INT8; break;
                case igtl::ImageMessage::TYPE_UINT8:
                    wtp._baseType = WeaklyTypedPointer::UINT8; break;
                case igtl::ImageMessage::TYPE_INT16:
                    wtp._baseType = WeaklyTypedPointer::INT16; break;
                case igtl::ImageMessage::TYPE_UINT16:
                    wtp._baseType = WeaklyTypedPointer::UINT16; break;
                case igtl::ImageMessage::TYPE_INT32:
                    wtp._baseType = WeaklyTypedPointer::INT32; break;
                case igtl::ImageMessage::TYPE_UINT32:
                    wtp._baseType = WeaklyTypedPointer::UINT32; break;
                case igtl::ImageMessage::TYPE_FLOAT32:
                    wtp._baseType = WeaklyTypedPointer::FLOAT; break;
                default:
                    LERROR("Error while receiving IGTL IMAGE message: unsupported type: " << imageMessage->GetScalarType());
                    return;
                }

151
152
153
                cgt::vec3 imageOffset(0.f);
                cgt::vec3 voxelSize(1.f);
                cgt::ivec3 size_i(1);
154
155

                imageMessage->GetSpacing(voxelSize.elem);
CAMP C++ Builder's avatar
CAMP C++ Builder committed
156
                imageMessage->GetDimensions(size_i.elem);
Declara Denis's avatar
Declara Denis committed
157
                cgt::svec3 size(size_i);
158
                imageMessage->GetOrigin(imageOffset.elem);
CAMP C++ Builder's avatar
CAMP C++ Builder committed
159

Declara Denis's avatar
Declara Denis committed
160
161
162
                // If the voxel size boundled with the packet is practically 0.0f, make it 1.0f
                // this makes sure we don't get invalid mapping informations (non invertable matrix)
                if (minElem(voxelSize) <= 1e-10f) {
163
                    voxelSize = cgt::vec3(1.0f);
Declara Denis's avatar
Declara Denis committed
164
165
                }

CAMP C++ Builder's avatar
CAMP C++ Builder committed
166
167
168
                size_t dimensionality = (size_i[2] == 1) ? ((size_i[1] == 1) ? 1 : 2) : 3;
                ImageData* image = new ImageData(dimensionality, size, wtp._numChannels);
                ImageRepresentationLocal::create(image, wtp);
169

CAMP C++ Builder's avatar
CAMP C++ Builder committed
170
                image->setMappingInformation(ImageMappingInformation(size, p_imageOffset.getValue(), voxelSize * p_voxelSize.getValue()));
171
                data.addData(p_targetImagePrefix.getValue() + it->first, image);
CAMP C++ Builder's avatar
CAMP C++ Builder committed
172
            }
173
174
            _receivedImages.clear();
            _imageMutex.unlock();
CAMP C++ Builder's avatar
CAMP C++ Builder committed
175
176
        }

CAMP C++ Builder's avatar
CAMP C++ Builder committed
177
178
        if(p_receivePositions.getValue())
        {
179
180
181
182
183
184
185
186
            _positionMutex.lock();
            for(auto it = _receivedPositions.begin(), end = _receivedPositions.end(); it != end; ++it) 
            {
                PositionData * pd = new PositionData(it->second._position, it->second._quaternion);
                data.addData(p_targetPositionPrefix.getValue() + it->first, pd);
            }
            _receivedPositions.clear();
            _positionMutex.unlock();
CAMP C++ Builder's avatar
CAMP C++ Builder committed
187
188
        }

CAMP C++ Builder's avatar
CAMP C++ Builder committed
189
190
191
192
        validate(INVALID_RESULT);
    }

    void OpenIGTLinkClient::updateProperties(DataContainer& dataContainer) {
193
        p_targetImagePrefix.setVisible(p_receiveImages.getValue());
CAMP C++ Builder's avatar
CAMP C++ Builder committed
194
195
196

        p_imageOffset.setVisible(p_receiveImages.getValue());
        p_voxelSize.setVisible(p_receiveImages.getValue());
197
        p_targetTransformPrefix.setVisible(p_receiveImages.getValue() || p_receiveTransforms.getValue());
198
        p_targetPositionPrefix.setVisible(p_receivePositions.getValue());
199
200

        validate(INVALID_PROPERTIES);
CAMP C++ Builder's avatar
CAMP C++ Builder committed
201
202
    }

203
    void OpenIGTLinkClient::connect() {
CAMP C++ Builder's avatar
CAMP C++ Builder committed
204
205
206
207
208
209
210
211
212
213
214

        if(_socket && _socket->GetConnected()) {
            LWARNING("Already connected!");
            return;
        }

        _socket = igtl::ClientSocket::New();
        int r = _socket->ConnectToServer(p_address.getValue().c_str(), p_port.getValue());

        if (r != 0)
        {
215
216
            LERROR("Cannot connect to the server " << p_address.getValue() << ":" << p_port.getValue());
            _socket = nullptr;
CAMP C++ Builder's avatar
CAMP C++ Builder committed
217
218
219
            return;
        }

220
        LINFO("Connected to server " << p_address.getValue() << ":" << p_port.getValue());
CAMP C++ Builder's avatar
CAMP C++ Builder committed
221

222
        startReceiver(); //start receiving data in a new thread
CAMP C++ Builder's avatar
CAMP C++ Builder committed
223
224
225
226

        validate(INVALID_RESULT);
    }

227
    void OpenIGTLinkClient::disconnect() {
228
        stopReceiver(); //sends the stop message to the receiver thread
229
230
231
        LINFO("Disconnected.");
    }

CAMP C++ Builder's avatar
CAMP C++ Builder committed
232
233
    int OpenIGTLinkClient::ReceiveTransform(igtl::Socket * socket, igtl::MessageHeader::Pointer& header)
    {
234
#ifdef IGTL_CLIENT_DEBUGGING
CAMP C++ Builder's avatar
CAMP C++ Builder committed
235
        LDEBUG("Receiving TRANSFORM data type.");
236
#endif
CAMP C++ Builder's avatar
CAMP C++ Builder committed
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
        // 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
        socket->Receive(transMsg->GetPackBodyPointer(), transMsg->GetPackBodySize());

        // 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
        {
252
            cgt::mat4 mtx;
253
254
            // Retrieve the transform data (this cast is a bit dubious but should be ok judging from the respective class internals)
            transMsg->GetMatrix(*reinterpret_cast<igtl::Matrix4x4*>(mtx.elem));
255
#ifdef IGTL_CLIENT_DEBUGGING
256
            igtl::PrintMatrix(*reinterpret_cast<igtl::Matrix4x4*>(mtx.elem));
CAMP C++ Builder's avatar
CAMP C++ Builder committed
257
            std::cerr << std::endl;
258
#endif
CAMP C++ Builder's avatar
CAMP C++ Builder committed
259

260
261
262
            _transformMutex.lock();
            _receivedTransforms[transMsg->GetDeviceName()] = mtx;
            _transformMutex.unlock();
CAMP C++ Builder's avatar
CAMP C++ Builder committed
263
264
265
266
267
268
269
270
271
272

            invalidate(INVALID_RESULT);
            return 1;
        }

        return 0;
    }

    int OpenIGTLinkClient::ReceivePosition(igtl::Socket * socket, igtl::MessageHeader::Pointer& header)
    {
273
#ifdef IGTL_CLIENT_DEBUGGING
CAMP C++ Builder's avatar
CAMP C++ Builder committed
274
        LDEBUG("Receiving POSITION data type.");
275
#endif
CAMP C++ Builder's avatar
CAMP C++ Builder committed
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291

        // Create a message buffer to receive position data
        igtl::PositionMessage::Pointer positionMsg;
        positionMsg = igtl::PositionMessage::New();
        positionMsg->SetMessageHeader(header);
        positionMsg->AllocatePack();

        // Receive position position data from the socket
        socket->Receive(positionMsg->GetPackBodyPointer(), positionMsg->GetPackBodySize());

        // Deserialize the transform data
        // If you want to skip CRC check, call Unpack() without argument.
        int c = positionMsg->Unpack(1);

        if (c & igtl::MessageHeader::UNPACK_BODY) // if CRC check is OK
        {
292
293
294
295
296
            PositionMessageData pmd;

            positionMsg->GetPosition(pmd._position.elem);
            positionMsg->GetQuaternion(pmd._quaternion.elem);
            
CAMP C++ Builder's avatar
CAMP C++ Builder committed
297

298
299
300
301
            _positionMutex.lock();
            _receivedPositions[positionMsg->GetDeviceName()] = pmd;
            _positionMutex.unlock();

302
303

#ifdef IGTL_CLIENT_DEBUGGING
304
305
306
            std::cerr << "position   = (" << pmd._position[0] << ", " << pmd._position[1] << ", " << pmd._position[2] << ")" << std::endl;
            std::cerr << "quaternion = (" << pmd._quaternion[0] << ", " << pmd._quaternion[1] << ", "
                << pmd._quaternion[2] << ", " << pmd._quaternion[3] << ")" << std::endl << std::endl;
307
#endif
CAMP C++ Builder's avatar
CAMP C++ Builder committed
308

CAMP C++ Builder's avatar
CAMP C++ Builder committed
309
            invalidate(INVALID_RESULT);
CAMP C++ Builder's avatar
CAMP C++ Builder committed
310
311
312
313
314
315
316
317
            return 1;
        }

        return 0;
    }

    int OpenIGTLinkClient::ReceiveImage(igtl::Socket * socket, igtl::MessageHeader::Pointer& header)
    {
318
#ifdef IGTL_CLIENT_DEBUGGING
CAMP C++ Builder's avatar
CAMP C++ Builder committed
319
        LDEBUG("Receiving IMAGE data type.");
320
#endif
CAMP C++ Builder's avatar
CAMP C++ Builder committed
321
322
323
324
325
326
327
328
329
330

        // Create a message buffer to receive transform data
        igtl::ImageMessage::Pointer imgMsg;
        imgMsg = igtl::ImageMessage::New();
        imgMsg->SetMessageHeader(header);
        imgMsg->AllocatePack();

        // Receive image data from the socket
        socket->Receive(imgMsg->GetPackBodyPointer(), imgMsg->GetPackBodySize());

331
        // Deserialize the data
CAMP C++ Builder's avatar
CAMP C++ Builder committed
332
333
334
335
336
337
        // If you want to skip CRC check, call Unpack() without argument.
        int c = imgMsg->Unpack(1);

        if (c & igtl::MessageHeader::UNPACK_BODY) // if CRC check is OK
        {
            // put the message pointer into our locked buffer
338
339
340
            _imageMutex.lock();
            _receivedImages[imgMsg->GetDeviceName()] = imgMsg;
            _imageMutex.unlock();
CAMP C++ Builder's avatar
CAMP C++ Builder committed
341
342
343
344
345
346

            // Retrieve the image data
            int   size[3];          // image dimension
            float spacing[3];       // spacing (mm/pixel)
            int   svsize[3];        // sub-volume size
            int   svoffset[3];      // sub-volume offset
347
        
CAMP C++ Builder's avatar
CAMP C++ Builder committed
348
349
350
351
            imgMsg->GetDimensions(size);
            imgMsg->GetSpacing(spacing);
            imgMsg->GetSubVolume(svsize, svoffset);

352
            cgt::mat4 mtx;
CAMP C++ Builder's avatar
CAMP C++ Builder committed
353
            // Retrieve the transform data (this cast is a bit dubious but should be ok judging from the class internals)
354
355
356
357
358
            imgMsg->GetMatrix(*reinterpret_cast<igtl::Matrix4x4*>(mtx.elem));
            
            _transformMutex.lock();
            _receivedTransforms[imgMsg->GetDeviceName()] = mtx;
            _transformMutex.unlock();
CAMP C++ Builder's avatar
CAMP C++ Builder committed
359

360
#ifdef IGTL_CLIENT_DEBUGGING
CAMP C++ Builder's avatar
CAMP C++ Builder committed
361
362
363
364
365
366
367
368
369
370
371
            std::cerr << "Device Name           : " << imgMsg->GetDeviceName() << std::endl;
            std::cerr << "Scalar Type           : " << scalarType << std::endl;
            std::cerr << "Dimensions            : ("
                << size[0] << ", " << size[1] << ", " << size[2] << ")" << std::endl;
            std::cerr << "Spacing               : ("
                << spacing[0] << ", " << spacing[1] << ", " << spacing[2] << ")" << std::endl;
            std::cerr << "Sub-Volume dimensions : ("
                << svsize[0] << ", " << svsize[1] << ", " << svsize[2] << ")" << std::endl;
            std::cerr << "Sub-Volume offset     : ("
                << svoffset[0] << ", " << svoffset[1] << ", " << svoffset[2] << ")" << std::endl << std::endl;

372

373
374
            igtl::PrintMatrix(*reinterpret_cast<igtl::Matrix4x4*>(mtx.elem));
            std::cout << std::endl;
375
#endif
CAMP C++ Builder's avatar
CAMP C++ Builder committed
376
377
378
379
380
381
382
383
384

            invalidate(INVALID_RESULT);
            return 1;
        }

        return 0;

    }

385
    void OpenIGTLinkClient::runReceiverThread()
CAMP C++ Builder's avatar
CAMP C++ Builder committed
386
387
388
389
390
391
392
    {
        igtl::MessageHeader::Pointer headerMsg;
        igtl::TimeStamp::Pointer ts;

        headerMsg = igtl::MessageHeader::New();
        ts = igtl::TimeStamp::New();

393
394
395
        p_connect.setVisible(false);
        p_disconnect.setVisible(true);

396
        while (!_stopExecution && _socket && _socket->GetConnected())
CAMP C++ Builder's avatar
CAMP C++ Builder committed
397
398
399
400
401
402
403
404
405
        {
            // Initialize receive buffer
            headerMsg->InitPack();

            // Receive generic header from the socket
            int r = _socket->Receive(headerMsg->GetPackPointer(), headerMsg->GetPackSize());
            if (r == 0)
            {
                _socket->CloseSocket();
406
                _socket = nullptr;
CAMP C++ Builder's avatar
CAMP C++ Builder committed
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
                LINFO("Socket Connection closed.");
                break;
            }
            if (r != headerMsg->GetPackSize())
            {
                continue;
            }

            // Deserialize the header
            headerMsg->Unpack();

            // Get time stamp
            igtlUint32 sec;
            igtlUint32 nanosec;

            headerMsg->GetTimeStamp(ts);
            ts->GetTimeStamp(&sec, &nanosec);

            /*std::cerr << "Time stamp: "
                << sec << "." << std::setw(9) << std::setfill('0') 
                << nanosec << std::endl;*/

            std::string acceptedName = p_deviceName.getValue();
            
            if (!acceptedName.empty() && strcmp(acceptedName.c_str(), headerMsg->GetDeviceName()) ) 
            {
                _socket->Skip(headerMsg->GetBodySizeToRead(), 0);
                LDEBUG("Ignoring Message from device " << headerMsg->GetDeviceName() << ". Does not match " << acceptedName);
            }
            // Check data type and receive data body
            else if (strcmp(headerMsg->GetDeviceType(), "TRANSFORM") == 0)
            {
                if(p_receiveTransforms.getValue())
                    ReceiveTransform(_socket, headerMsg);
                else
                    _socket->Skip(headerMsg->GetBodySizeToRead(), 0);
            }
CAMP C++ Builder's avatar
CAMP C++ Builder committed
444
            else if (strcmp(headerMsg->GetDeviceType(), "POSITION") == 0)
CAMP C++ Builder's avatar
CAMP C++ Builder committed
445
            {
CAMP C++ Builder's avatar
CAMP C++ Builder committed
446
447
448
449
450
                if(p_receivePositions.getValue())
                    ReceivePosition(_socket, headerMsg);
                else
                    _socket->Skip(headerMsg->GetBodySizeToRead(), 0);
            }
CAMP C++ Builder's avatar
CAMP C++ Builder committed
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
            else if (strcmp(headerMsg->GetDeviceType(), "IMAGE") == 0)
            {
                if(p_receiveImages.getValue())
                    ReceiveImage(_socket, headerMsg);
                else
                    _socket->Skip(headerMsg->GetBodySizeToRead(), 0);
            }
//            else if (strcmp(headerMsg->GetDeviceType(), "STATUS") == 0)
//            {
//                ReceiveStatus(socket, headerMsg);
//            }
//#if OpenIGTLink_PROTOCOL_VERSION >= 2
//            else if (strcmp(headerMsg->GetDeviceType(), "POINT") == 0)
//            {
//                ReceivePoint(socket, headerMsg);
//            }
//            else if (strcmp(headerMsg->GetDeviceType(), "TRAJ") == 0)
//            {
//                ReceiveTrajectory(socket, headerMsg);
//            }
//            else if (strcmp(headerMsg->GetDeviceType(), "STRING") == 0)
//            {
//                ReceiveString(socket, headerMsg);
//            }
//            else if (strcmp(headerMsg->GetDeviceType(), "TDATA") == 0)
//            {
//                ReceiveTrackingData(socket, headerMsg);
//            }
//            else if (strcmp(headerMsg->GetDeviceType(), "QTDATA") == 0)
//            {
//                ReceiveQuaternionTrackingData(socket, headerMsg);
//            }
//            else if (strcmp(headerMsg->GetDeviceType(), "CAPABILITY") == 0)
//            {
//                ReceiveCapability(socket, headerMsg);;
//            }
//#endif //OpenIGTLink_PROTOCOL_VERSION >= 2
            else
            {
490
                LDEBUG("Received IGTL Message Type " << headerMsg->GetDeviceType() << " which is not Handled!");
CAMP C++ Builder's avatar
CAMP C++ Builder committed
491
492
493
                _socket->Skip(headerMsg->GetBodySizeToRead(), 0);
            }
        }
494
495
496
        if(_socket)       
            _socket->CloseSocket();
        _socket = nullptr;
497
498
        p_disconnect.setVisible(false);
        p_connect.setVisible(true);
CAMP C++ Builder's avatar
CAMP C++ Builder committed
499
    }
500
501
502
503
504
505
506
507
508
509
510
511


    void OpenIGTLinkClient::stopReceiver() {
        if (!_receiverRunning || _receiverThread == 0)
            return;

        _stopExecution = true;
        try {
            if (_receiverThread->joinable())
                _receiverThread->join();

            _receiverRunning = false;
512
            delete _receiverThread;
513
            _receiverThread = nullptr;
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
        }
        catch (std::exception& e) {
            LERRORC("CAMPVis.modules.base.MatrixProcessor", "Caught exception during _thread.join: " << e.what());
        }
    }

    void OpenIGTLinkClient::startReceiver() {
        stopReceiver(); //make sure we are stopped and reset
        _stopExecution = false;

        _receiverThread = new std::thread([this]() {
            runReceiverThread();
        });
        _receiverRunning = true;
    }
CAMP C++ Builder's avatar
CAMP C++ Builder committed
529
}