140 lines
3.8 KiB
C++

//======================================================================================================
// Copyright 2025, Rokoko Glove OptiTrack Integration
//======================================================================================================
/**
* RokokoUDPReceiver class provides UDP communication functionality for receiving Rokoko glove data.
* This receiver handles UDP socket communication and data reception from Rokoko Studio.
*/
#pragma once
#include <winsock2.h>
#include <ws2tcpip.h>
#include <functional>
#include <thread>
#include <vector>
#include <atomic>
#include <mutex>
namespace RokokoIntegration
{
class RokokoUDPReceiver
{
public:
/**
* Constructor
*/
RokokoUDPReceiver();
/**
* Destructor
*/
~RokokoUDPReceiver();
/**
* Initializes UDP receiver
* @param port UDP port to listen on (default: 14043)
* @return true if initialization successful
*/
bool Initialize(int port = 14043);
/**
* Starts listening for UDP data
* @return true if started successfully
*/
bool StartListening();
/**
* Stops listening for UDP data
*/
void StopListening();
/**
* Sets callback function for received data
* @param callback Function to call when data is received
*/
void SetDataCallback(std::function<void(const std::vector<uint8_t>&, const std::string&)> callback);
/**
* Checks if receiver is currently listening
* @return true if listening
*/
bool IsListening() const;
/**
* Gets the current connection status
* @return true if connected and receiving data
*/
bool IsConnected() const;
/**
* Gets the last error message
* @return Error message string
*/
std::string GetLastError() const;
/**
* Gets connection statistics
* @param packetsReceived Number of packets received
* @param bytesReceived Total bytes received
* @param lastPacketTime Timestamp of last packet
*/
void GetStatistics(uint64_t& packetsReceived, uint64_t& bytesReceived, double& lastPacketTime) const;
private:
// UDP socket
SOCKET mSocket;
// Thread management
std::thread mReceiveThread;
std::atomic<bool> mIsRunning;
std::atomic<bool> mIsListening;
// Data callback
std::function<void(const std::vector<uint8_t>&, const std::string&)> mDataCallback;
// Statistics
mutable std::mutex mStatsMutex;
uint64_t mPacketsReceived;
uint64_t mBytesReceived;
double mLastPacketTime;
// Error handling
mutable std::mutex mErrorMutex;
std::string mLastError;
// Configuration
int mPort;
int mBufferSize;
/**
* Main receive thread function
*/
void ReceiveThread();
/**
* Processes incoming UDP data
* @param data Received data
* @param size Size of received data
* @param senderIP IP address of sender
*/
void ProcessIncomingData(const uint8_t* data, int size, const std::string& senderIP);
/**
* Sets error message
* @param error Error message
*/
void SetError(const std::string& error);
/**
* Updates statistics
* @param packetSize Size of received packet
*/
void UpdateStatistics(int packetSize);
/**
* Closes UDP socket
*/
void CloseSocket();
};
}