openigtlinkclient.cpp 17.6 KB
Newer Older
Jakob Weiss's avatar
Jakob Weiss 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
27
// ================================================================================================
// 
// 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"

#include "transformdata.h"
Jakob Weiss's avatar
Jakob Weiss committed
28
#include "positiondata.h"
Jakob Weiss's avatar
Jakob Weiss committed
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51

#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()
        , p_address("ServerAddress", "Server Address", "127.0.0.1", StringProperty::BASIC_STRING)
        , p_port("ServerPort", "Server Port", 18944, 1, 65535, 1)
        , p_deviceName("ServerDeviceName", "Device Name (empty to accept all)")
        , p_connect("Connect", "Connect to Server")
        , p_receiveImages("ReceiveImages", "Receive IMAGE Messages", false)
        , p_targetImageID("targetImageName", "Target Image ID", "OpenIGTLinkClient.output", DataNameProperty::WRITE)
        , p_receiveTransforms("ReceiveTransforms", "Receive TRANSFORM Messages", true)
        , p_targetTransformID("targetTransformName", "Target Transform ID", "OpenIGTLinkClient.transform", DataNameProperty::WRITE)
        , p_imageOffset("ImageOffset", "Image Offset in mm", tgt::vec3(0.f), tgt::vec3(-10000.f), tgt::vec3(10000.f), tgt::vec3(0.1f))
        , p_voxelSize("VoxelSize", "Voxel Size in mm", tgt::vec3(1.f), tgt::vec3(-100.f), tgt::vec3(100.f), tgt::vec3(0.1f))
Jakob Weiss's avatar
Jakob Weiss committed
52
53
        , p_receivePositions("ReceivePositions", "Receive POSITION Messages", true)
        , p_targetPositionID("targetPositionsID", "Target Position ID", "OpenIGTLinkClient.position", DataNameProperty::WRITE)
Jakob Weiss's avatar
Jakob Weiss committed
54
55
56
57
58
59
60
    {
        _lastReceivedTransform = 0;
        _lastReceivedImageMessage = 0;

        addProperty(p_address, VALID);
        addProperty(p_port, VALID);
        addProperty(p_deviceName, VALID);
Jakob Weiss's avatar
Jakob Weiss committed
61
62
63

        addProperty(p_connect, VALID);

Jakob Weiss's avatar
Jakob Weiss committed
64
65
66
67
68
69
        addProperty(p_receiveTransforms, INVALID_RESULT | INVALID_PROPERTIES);
        addProperty(p_receiveImages, INVALID_RESULT | INVALID_PROPERTIES);
        addProperty(p_targetTransformID, VALID);
        addProperty(p_targetImageID, VALID);
        addProperty(p_imageOffset, VALID);
        addProperty(p_voxelSize, VALID);
Jakob Weiss's avatar
Jakob Weiss committed
70
71
        addProperty(p_receivePositions, INVALID_RESULT | INVALID_PROPERTIES);
        addProperty(p_targetPositionID, VALID);
Jakob Weiss's avatar
Jakob Weiss committed
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
    }

    OpenIGTLinkClient::~OpenIGTLinkClient() {

    }

    void OpenIGTLinkClient::init() {
        p_connect.s_clicked.connect(this, &OpenIGTLinkClient::onBtnConnectClicked);
    }

    void OpenIGTLinkClient::deinit() {
        p_connect.s_clicked.disconnect(this);
        stop(); //stop the receiving thread
    }

    void OpenIGTLinkClient::updateResult(DataContainer& data) {

        if(p_receiveTransforms.getValue()) 
        {
            tgt::mat4 * newTransform = _lastReceivedTransform.fetch_and_store(nullptr);
            if(newTransform) {
                TransformData * td = new TransformData(*newTransform);
        
                data.addData(p_targetTransformID.getValue(), td);
                delete newTransform; //was allocated in the receiver thread - not needed anymore

                LDEBUG("Transform data put into container. ");
            }
        }

        if(p_receiveImages.getValue()) 
        {
            _lastReceivedImageMessageMutex.lock();
            igtl::ImageMessage::Pointer imageMessage = _lastReceivedImageMessage;    
            _lastReceivedImageMessageMutex.unlock();

            if(imageMessage) 
            {
                WeaklyTypedPointer wtp;
                wtp._pointer = new uint8_t[imageMessage->GetImageSize()];
                LDEBUG("Image has " << imageMessage->GetNumComponents() << " components and is of size " << imageMessage->GetImageSize());
                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;
                }

                tgt::vec3 imageOffset(0.f);
                tgt::vec3 voxelSize(1.f);

                tgt::ivec3 size_i(1);
                imageMessage->GetDimensions(size_i.elem);
                tgt::svec3 size(size_i);

                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);
                image->setMappingInformation(ImageMappingInformation(size, p_imageOffset.getValue(), voxelSize * p_voxelSize.getValue()));
                data.addData(p_targetImageID.getValue(), image);
            }
        }

Jakob Weiss's avatar
Jakob Weiss committed
151
152
153
154
155
156
157
158
159
        if(p_receivePositions.getValue())
        {
            _lastReceivedPositionMutex.lock();
            PositionData * pd = new PositionData(_lastReceivedPosition, _lastReceivedQuaternion);
            _lastReceivedPositionMutex.unlock();

            data.addData(p_targetPositionID.getValue(), pd);
        }

Jakob Weiss's avatar
Jakob Weiss committed
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
        validate(INVALID_RESULT);
    }

    void OpenIGTLinkClient::updateProperties(DataContainer& dataContainer) {
        p_targetImageID.setVisible(p_receiveImages.getValue());

        p_imageOffset.setVisible(p_receiveImages.getValue());
        p_voxelSize.setVisible(p_receiveImages.getValue());
        p_targetTransformID.setVisible(p_receiveImages.getValue() || p_receiveTransforms.getValue());
    }

    void OpenIGTLinkClient::onBtnConnectClicked() {

        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)
        {
            LERROR("Cannot connect to the server " << p_address.getValue());
            return;
        }

        LINFO("Connected to server!");

        start(); //start receiving data in a new thread

        validate(INVALID_RESULT);
    }

    int OpenIGTLinkClient::ReceiveTransform(igtl::Socket * socket, igtl::MessageHeader::Pointer& header)
    {
        LDEBUG("Receiving TRANSFORM data type.");

        // 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
        {
            tgt::mat4 * mtx = new tgt::mat4;
            // Retrieve the transform data (this cast is a bit dubious but should be ok judging from the class internals)
            transMsg->GetMatrix(*reinterpret_cast<igtl::Matrix4x4*>(mtx->elem));
            igtl::PrintMatrix(*reinterpret_cast<igtl::Matrix4x4*>(mtx->elem));
            std::cerr << std::endl;

            tgt::mat4 * toDelete = _lastReceivedTransform.fetch_and_store(mtx);
            if(toDelete) delete toDelete;

            invalidate(INVALID_RESULT);
            return 1;
        }

        return 0;
    }

    int OpenIGTLinkClient::ReceivePosition(igtl::Socket * socket, igtl::MessageHeader::Pointer& header)
    {
        LDEBUG("Receiving POSITION data type.");

        // 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
        {
Jakob Weiss's avatar
Jakob Weiss committed
249
250
251
252
            _lastReceivedPositionMutex.lock();
            positionMsg->GetPosition(_lastReceivedPosition.elem);
            positionMsg->GetQuaternion(_lastReceivedQuaternion.elem);
            _lastReceivedPositionMutex.unlock();
Jakob Weiss's avatar
Jakob Weiss committed
253

Jakob Weiss's avatar
Jakob Weiss committed
254
255
256
            std::cerr << "position   = (" << _lastReceivedPosition[0] << ", " << _lastReceivedPosition[1] << ", " << _lastReceivedPosition[2] << ")" << std::endl;
            std::cerr << "quaternion = (" << _lastReceivedQuaternion[0] << ", " << _lastReceivedQuaternion[1] << ", "
                << _lastReceivedQuaternion[2] << ", " << _lastReceivedQuaternion[3] << ")" << std::endl << std::endl;
Jakob Weiss's avatar
Jakob Weiss committed
257

Jakob Weiss's avatar
Jakob Weiss committed
258
            invalidate(INVALID_RESULT);
Jakob Weiss's avatar
Jakob Weiss committed
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
            return 1;
        }

        return 0;
    }

    int OpenIGTLinkClient::ReceiveImage(igtl::Socket * socket, igtl::MessageHeader::Pointer& header)
    {
        LDEBUG("Receiving IMAGE data type.");

        // 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());

        // Deserialize the transform data
        // 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
            _lastReceivedImageMessageMutex.lock();
            _lastReceivedImageMessage = imgMsg;
            _lastReceivedImageMessageMutex.unlock();

            // 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
            int   scalarType;       // scalar type

            scalarType = imgMsg->GetScalarType();
            imgMsg->GetDimensions(size);
            imgMsg->GetSpacing(spacing);
            imgMsg->GetSubVolume(svsize, svoffset);

            tgt::mat4 * mtx = new tgt::mat4;
            // Retrieve the transform data (this cast is a bit dubious but should be ok judging from the class internals)
            imgMsg->GetMatrix(*reinterpret_cast<igtl::Matrix4x4*>(mtx->elem));
            std::cerr << std::endl;

            tgt::mat4 * toDelete = _lastReceivedTransform.fetch_and_store(mtx);
            if(toDelete) delete toDelete;

            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;

            igtl::PrintMatrix(*reinterpret_cast<igtl::Matrix4x4*>(mtx->elem));

            invalidate(INVALID_RESULT);
            return 1;
        }

        return 0;

    }

    void OpenIGTLinkClient::run()
    {
        igtl::MessageHeader::Pointer headerMsg;
        igtl::TimeStamp::Pointer ts;

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

        while (!_stopExecution)
        {
            // Initialize receive buffer
            headerMsg->InitPack();

            // Receive generic header from the socket
            int r = _socket->Receive(headerMsg->GetPackPointer(), headerMsg->GetPackSize());
            if (r == 0)
            {
                _socket->CloseSocket();
                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);
            }
Jakob Weiss's avatar
Jakob Weiss committed
385
            else if (strcmp(headerMsg->GetDeviceType(), "POSITION") == 0)
Jakob Weiss's avatar
Jakob Weiss committed
386
            {
Jakob Weiss's avatar
Jakob Weiss committed
387
388
389
390
391
                if(p_receivePositions.getValue())
                    ReceivePosition(_socket, headerMsg);
                else
                    _socket->Skip(headerMsg->GetBodySizeToRead(), 0);
            }
Jakob Weiss's avatar
Jakob Weiss committed
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
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
            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
            {
                LDEBUG("Receiving : " << headerMsg->GetDeviceType() << " which is not Handled!");
                _socket->Skip(headerMsg->GetBodySizeToRead(), 0);
            }
        }
        _socket->CloseSocket();
    }
}