File: network.cpp

package info (click to toggle)
sight 25.2.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 42,180 kB
  • sloc: cpp: 289,476; xml: 17,257; ansic: 9,878; python: 1,379; sh: 144; makefile: 33
file content (377 lines) | stat: -rw-r--r-- 10,398 bytes parent folder | download | duplicates (2)
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
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
151
152
153
154
155
156
157
158
159
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
249
250
251
252
253
254
255
256
257
258
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
/************************************************************************
 *
 * Copyright (C) 2014-2023 IRCAD France
 * Copyright (C) 2014-2018 IHU Strasbourg
 *
 * This file is part of Sight.
 *
 * Sight is free software: you can redistribute it and/or modify it under
 * the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Sight is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with Sight. If not, see <https://www.gnu.org/licenses/>.
 *
 ***********************************************************************/

#include "network.hpp"

#include "io/igtl/exception.hpp"

#include <io/igtl/detail/data_converter.hpp>
#include <io/igtl/detail/message_factory.hpp>

#include <cmath>

#if defined(_WIN32)
  #include <windows.h>
  #include <winsock2.h>
#else
  #include <sys/types.h>
  #include <sys/socket.h>
  #include <netinet/in.h>
  #include <netinet/tcp.h>
  #include <arpa/inet.h>
  #include <netdb.h>
  #include <unistd.h>
  #include <sys/time.h>
#endif

namespace sight::io::igtl
{

//------------------------------------------------------------------------------

network::network() :

    m_device_name_out("Sight")
{
}

//------------------------------------------------------------------------------

network::~network()
= default;

//------------------------------------------------------------------------------

bool network::send_object(const data::object::csptr& _obj)
{
    ::igtl::MessageBase::Pointer msg;

    detail::data_converter::sptr converter = detail::data_converter::get_instance();
    msg = converter->from_fw_object(_obj);
    msg->SetDeviceName(m_device_name_out.c_str());
    msg->Pack();
    return m_socket->Send(msg->GetPackPointer(), msg->GetPackSize()) == 1;
}

//------------------------------------------------------------------------------

bool network::send_msg(::igtl::MessageBase::Pointer _msg)
{
    _msg->SetDeviceName(m_device_name_out.c_str());
    _msg->Pack();
    return m_socket->Send(_msg->GetPackPointer(), _msg->GetPackSize()) == 1;
}

//------------------------------------------------------------------------------

data::object::sptr network::receive_object(std::string& _device_name)
{
    data::object::sptr obj;
    ::igtl::MessageHeader::Pointer header_msg = this->receive_header();
    if(header_msg.IsNotNull())
    {
        ::igtl::MessageBase::Pointer msg = this->receive_body(header_msg);
        if(msg.IsNotNull())
        {
            detail::data_converter::sptr converter = detail::data_converter::get_instance();
            obj          = converter->from_igtl_message(msg);
            _device_name = header_msg->GetDeviceName();
        }
    }

    return obj;
}

//------------------------------------------------------------------------------

data::object::sptr network::receive_object(std::string& _device_name, double& _timestamp)
{
    data::object::sptr obj;
    ::igtl::MessageHeader::Pointer header_msg = this->receive_header();
    if(header_msg.IsNotNull())
    {
        ::igtl::MessageBase::Pointer msg = this->receive_body(header_msg);
        if(msg.IsNotNull())
        {
            // get message timestamp
            unsigned int sec  = 0;
            unsigned int frac = 0;
            msg->GetTimeStamp(&sec, &frac);
            double sec_d  = NAN;
            double frac_d = NAN;
            sec_d  = static_cast<double>(sec);
            frac_d = static_cast<double>(frac);

            // convert into milliseconds
            frac_d    /= 1000000.;
            sec_d     *= 1000.;
            _timestamp = frac_d + sec_d;

            detail::data_converter::sptr converter = detail::data_converter::get_instance();
            obj          = converter->from_igtl_message(msg);
            _device_name = header_msg->GetDeviceName();
        }
    }

    return obj;
}

//------------------------------------------------------------------------------

::igtl::MessageHeader::Pointer network::receive_header()
{
    ::igtl::MessageHeader::Pointer header_msg = ::igtl::MessageHeader::New();
    header_msg->InitPack();
    const int size_receive = m_socket->Receive(header_msg->GetPackPointer(), header_msg->GetPackSize());

    if(size_receive == -1)
    {
        // Case 1: Timeout
        throw sight::io::igtl::exception("Network timeout");
    }

    if(size_receive == 0)
    {
        // Case 2: Error
        throw sight::io::igtl::exception("Network Error");
    }

    if(size_receive != header_msg->GetPackSize())
    {
        // Case 3: mismatch of size
        throw sight::io::igtl::exception("Received size error");
    }

    if(header_msg->Unpack() == ::igtl::MessageBase::UNPACK_HEADER)
    {
        const std::string device_name = header_msg->GetDeviceName();

        if(m_filtering_by_device_name)
        {
            if(m_device_names_in.find(device_name) != m_device_names_in.end())
            {
                return header_msg;
            }

            return {};
        }

        return header_msg;
    }

    return {};
}

//------------------------------------------------------------------------------

::igtl::MessageBase::Pointer network::receive_body(::igtl::MessageHeader::Pointer const _header_msg)
{
    int unpack_result = 0;
    int result        = 0;
    ::igtl::MessageBase::Pointer msg;

    if(_header_msg == nullptr)
    {
        throw sight::io::igtl::exception("Invalid header message");
    }

    msg = io::igtl::detail::message_factory::create(_header_msg->GetDeviceType());
    msg->SetMessageHeader(_header_msg);
    msg->AllocatePack();
    result = m_socket->Receive(msg->GetPackBodyPointer(), msg->GetPackBodySize());

    if(result == -1) // Timeout
    {
        throw sight::io::igtl::exception("Network timeout");
    }

    if(result == 0) // Error
    {
        throw sight::io::igtl::exception("Network Error");
    }

    unpack_result = msg->Unpack();
    if(unpack_result == ::igtl::MessageHeader::UNPACK_UNDEF)
    {
        throw sight::io::igtl::exception("Network Error");
    }

    if(unpack_result == ::igtl::MessageHeader::UNPACK_BODY)
    {
        return msg;
    }

    throw exception("Body pack is not valid");
}

//------------------------------------------------------------------------------

::igtl::Socket::Pointer network::get_socket() const
{
    return m_socket;
}

//------------------------------------------------------------------------------

void network::add_authorized_device(const std::string& _device_name)
{
    auto it = m_device_names_in.find(_device_name);

    if(it == m_device_names_in.end())
    {
        m_device_names_in.insert(_device_name);
    }
}

//------------------------------------------------------------------------------

bool network::get_filtering_by_device_name() const
{
    return m_filtering_by_device_name;
}

//------------------------------------------------------------------------------

void network::set_filtering_by_device_name(bool _filtering)
{
    if(m_device_names_in.empty())
    {
        m_filtering_by_device_name = false;
    }
    else
    {
        m_filtering_by_device_name = _filtering;
    }
}

//------------------------------------------------------------------------------

void network::set_device_name_out(const std::string& _device_name)
{
    m_device_name_out = _device_name;
}

//------------------------------------------------------------------------------

std::string network::get_device_name_out() const
{
    return m_device_name_out;
}

//------------------------------------------------------------------------------

void network::close_socket(int _socket_descriptor)
{
    // NOTE: Patched version of original CloseSocket() from igtlSocket.h, adding close() after shutdown() on Linux.
    // This can be removed on recent version of IGTL (Debian version is pretty old).

    if(_socket_descriptor == -1)
    {
        return;
    }

#if defined(_WIN32)
#define WSA_VERSION MAKEWORD(1, 1)
    closesocket(_socket_descriptor);
#else
    shutdown(_socket_descriptor, 2);
    close(_socket_descriptor); // closing socket for latter reuse.
#endif
}

//------------------------------------------------------------------------------

int network::create_socket()
{
#if defined(_WIN32)
    // Declare variables
    WSADATA wsaData;
    //SOCKET ListenSocket;
    //sockaddr_in service;

    //---------------------------------------
    // Initialize Winsock
    int iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
    if(iResult != NO_ERROR)
    {
        std::cerr << "Error at WSAStartup" << std::endl;
        return -1;
    }
#endif

    int sock = socket(AF_INET, SOCK_STREAM, 0);
    // Elimate windows 0.2 second delay sending (buffering) data.
    int on = 1;
    if(setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, reinterpret_cast<char*>(&on), sizeof(on)) != 0)
    {
#if defined(_WIN32)
        closesocket(sock);
#else
        close(sock);
#endif
        return -1;
    }

    return sock;
}

//------------------------------------------------------------------------------

int network::listen_socket(int _socket_descriptor)
{
    if(_socket_descriptor < 0)
    {
        return -1;
    }

    return listen(_socket_descriptor, 1);
}

//------------------------------------------------------------------------------

int network::bind_socket(int _socket_descriptor, std::uint16_t _port)
{
    struct sockaddr_in server {};

    server.sin_family      = AF_INET;
    server.sin_addr.s_addr = INADDR_ANY;
    server.sin_port        = htons(_port);
    // Allow the socket to be bound to an address that is already in use
#ifdef _WIN32
    int opt = 1;
    setsockopt(_socket_descriptor, SOL_SOCKET, SO_REUSEADDR, (char*) &opt, sizeof(int));
#else
    int opt = 1;
    setsockopt(_socket_descriptor, SOL_SOCKET, SO_REUSEADDR, (void*) &opt, sizeof(int));
#endif

    if(bind(_socket_descriptor, reinterpret_cast<sockaddr*>(&server), sizeof(server)) != 0)
    {
        return -1;
    }

    return 0;
}

//------------------------------------------------------------------------------

} // namespace sight::io::igtl