optitrack_packet_receiver.py 1.97 KB
Newer Older
Kamal Nasser's avatar
Kamal Nasser committed
1
2
import threading
#from eventlet.green import threading
Kamal Nasser's avatar
Kamal Nasser committed
3
4
5
6
7
8
9
import optirx as rx

DEFAULT_MULTICAST_ADDRESS = '239.255.42.99'
DEFAULT_DATA_PORT = 1511
DEFAULT_NATNETSDK_VERSION = (2, 8, 0, 0)


Kamal Nasser's avatar
Kamal Nasser committed
10
class OptitrackPacketReceiver(threading.Thread):
Kamal Nasser's avatar
Kamal Nasser committed
11
12
13
14
15
16
17
18
    """
    Responsible for constantly receiving UDP packets form the OptiTrack system, parsing them to optirx objects,
    and storing them locally to make them available when needed.
    The OptitrackPacketReceiver is a separate thread, so it continues receiving UDP packets regardless of the
    activity of the rest of the system.
    """
    def __init__(self, server_ip_addr, natnetsdk_version=DEFAULT_NATNETSDK_VERSION,
                 multicast_addr=DEFAULT_MULTICAST_ADDRESS, data_port=DEFAULT_DATA_PORT):
Kamal Nasser's avatar
Kamal Nasser committed
19
        super(OptitrackPacketReceiver, self).__init__()
Kamal Nasser's avatar
Kamal Nasser committed
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
        self._natnetsdk_version = natnetsdk_version
        self._last_packet = None
        self._is_shutdown_request = False
        # open UDP port to Optitrack server
        self._dsock = rx.mkdatasock(ip_address=server_ip_addr, multicast_address=multicast_addr, port=data_port)

    def run(self):
        while not self._is_shutdown_requested():
            # receive UDP data packet from Optitrack server
            data = self._dsock.recv(rx.MAX_PACKETSIZE)
            # parse packet and store it locally
            self._last_packet = rx.unpack(data, self._natnetsdk_version)
            # update natnet sdk version to what Optitrack software says it is
            if type(self._last_packet) is rx.SenderData:
                self._natnetsdk_version = self._last_packet.natnet_version

    def get_last_packet(self):
        """
        Returns the last packet recieved from the OptiTrack system as a optirx object
        """
        last_packet = self._last_packet
        return last_packet

    def _is_shutdown_requested(self):
        is_shutdown_request = self._is_shutdown_request
        return is_shutdown_request

    def shutdown(self):
        self._is_shutdown_request = True