RoveComm C++ 3.0.0
Welcome to the RoveComm C++ repository of the Mars Rover Design Team (MRDT) at Missouri University of Science and Technology (Missouri S&T)! API reference contains the source code and other resources for the development of RoveComm C++. The RoveComm C++ project is the RoveComm interface for high level systems and should not be used for microcontrollers.
Loading...
Searching...
No Matches
rovecomm::RoveCommTCP Class Reference

The RoveCommTCP class is used to send and receive data over a TCP connection. More...

#include <RoveCommTCP.h>

Inheritance diagram for rovecomm::RoveCommTCP:
Collaboration diagram for rovecomm::RoveCommTCP:

Classes

struct  CallbackEntry

Public Member Functions

 RoveCommTCP ()
 Construct a new RoveCommTCP::RoveCommTCP object.
 ~RoveCommTCP ()
 Destroy the RoveCommTCP::RoveCommTCP object.
bool Init (const manifest::AddressEntry &stIPAddress={0, 0, 0, 0}, int nPort=manifest::General::ETHERNET_TCP_PORT)
 Initializes a TCP socket and binds it to the specified IP address and port. And then starts the threaded continuous code in AutonomyThread.
template<typename T>
ssize_t WriteTo (const RoveCommPacket< T > &stPacket, const manifest::AddressEntry &stIPAddress, int nPort=manifest::General::ETHERNET_UDP_PORT)
 Sends a TCP packet to the specified client IP address and port. The data is packed into a RoveCommData struct and sent over the TCP socket.
template<typename manifest::ManifestEntry Entry>
ssize_t WriteTo (std::span< const EntryType< Entry > > spData, const manifest::AddressEntry &stIPAddress=manifest::Helpers::FindBoardById(Entry.DATA_ID).ADDRESS, int nPort=manifest::General::ETHERNET_UDP_PORT)
template<typename manifest::ManifestEntry Entry>
ssize_t WriteTo (std::initializer_list< EntryType< Entry > > ilData, const manifest::AddressEntry &stIPAddress=manifest::Helpers::FindBoardById(Entry.DATA_ID).ADDRESS, int nPort=manifest::General::ETHERNET_UDP_PORT)
template<typename T>
CallbackHandle On (const uint16_t unDataId, std::function< void(const RoveCommPacket< T > &)> fnCallback)
 Register a callback for TCP packets with the given data ID. The callback belongs to this node: packets received by any other node never invoke it.
template<typename manifest::ManifestEntry Entry>
CallbackHandle On (std::function< void(const RoveCommPacket< EntryType< Entry > > &)> fnCallback)
void Clear (const CallbackHandle &stHandle)
 Remove the one callback identified by a handle from On(). Other callbacks for the same data ID stay registered. Waits for a callback that is already running, so once this returns the removed callback can no longer run. An empty or already-removed handle is ignored.
void Close ()
 Closes the TCP socket.
IPS & GetIPS ()
 Accessor for the Frame I P S private member.

Private Types

template<typename T>
using CallbackMap = std::unordered_map<uint16_t, std::vector<CallbackEntry<T>>>
Private Types inherited from AutonomyThread< void >
enum  AutonomyThreadState
enum  AutonomyThreadPriority

Private Member Functions

template<typename T>
constexpr CallbackMap< T > & GetCallbackMap ()
template<typename T>
void RemoveCallback (const CallbackHandle &stHandle)
 Remove the one callback identified by a handle from this node's map for payload type T.
template<typename T>
void ProcessPacket (std::span< const uint8_t > stData)
 Processes a received packet and invokes the appropriate callback function from the vector of TCP callbacks for the specified data type. The data is unpacked into a RoveCommPacket and the appropriate callback function is invoked based on the data id.
void ReceiveAndCallback ()
 Receives a TCP packet from a client and invokes the appropriate callback function from the vector of TCP callbacks for the specified data type. The data is unpacked into a RoveCommPacket and the appropriate callback function is invoked based on the data id.
void ThreadedContinuousCode () override
 The threaded continuous code for the TCP class. This method calls the ReceiveTCPPacketAndCallback method to receive a TCP packet from a client and invoke the appropriate callback function.
void PooledLinearCode () override
 The pooled linear code for the TCP class. This method is not implemented and will do nothing.
Private Member Functions inherited from AutonomyThread< void >
 AutonomyThread ()
 Construct a new Autonomy Thread object.
virtual ~AutonomyThread ()
 Destroy the Autonomy Thread object. If the parent object or main thread is destroyed or exited while this thread is still running, a race condition will occur. Stopping and joining the thread here insures that the main program can't exit if the user forgot to stop and join the thread.
void Start ()
 When this method is called, it starts a new thread that runs the code within the ThreadedContinuousCode method. This is the users main code that will run the important and continuous code for the class.
void RequestStop ()
 Signals threads to stop executing user code, terminate. DOES NOT JOIN. This method will not force the thread to exit, if the user code is not written properly and contains WHILE statement or any other long-executing or blocking code, then the thread will not exit until the next iteration.
void Join ()
 Waits for thread to finish executing and then closes thread. This method will block the calling code until thread is finished.
bool Joinable () const
 Check if the code within the thread and all pools created by it are finished executing and the thread is ready to be closed.
AutonomyThreadState GetThreadState () const
 Accessor for the Threads State private member.
IPS & GetIPS ()
 Accessor for the Frame I P S private member.
void SetMainThreadPriority (AutonomyThreadPriority ePriority)
 Set the OS priority for the main continuous thread.
void SetPoolThreadPriority (AutonomyThreadPriority ePriority)
 Set the OS priority for the highly parallelized pool threads.
void RunPool (const unsigned int nNumTasksToQueue, const unsigned int nNumThreads=2, const bool bForceStopCurrentThreads=false)
 When this method is called, it starts/adds tasks to a thread pool that runs nNumTasksToQueue copies of the code within the PooledLinearCode() method using nNumThreads number of threads. This is meant to be used as an internal utility of the child class to further improve parallelization. Default value for nNumThreads is 2.
void RunDetachedPool (const unsigned int nNumTasksToQueue, const unsigned int nNumThreads=2, const bool bForceStopCurrentThreads=false)
 When this method is called, it starts a thread pool full of threads that don't return std::futures (like a placeholder for the thread return type). This means the thread will not have a return type and there is no way to determine if the thread has finished other than calling the Join() method. Only use this if you want to 'set and forget'. It will be faster as it doesn't return futures. Runs PooledLinearCode() method code. This is meant to be used as an internal utility of the child class to further improve parallelization.
void ParallelizeLoop (const int nNumThreads, const N tTotalIterations, F &&tLoopFunction)
 Given a ref-qualified looping function and an arbitrary number of iterations, this method will divide up the loop and run each section in a thread pool. This function must not return anything. This method will block until the loop has completed.
void ClearPoolQueue ()
 Clears any tasks waiting to be ran in the queue, tasks currently running will remain running.
void JoinPool ()
 Waits for pool to finish executing tasks. This method will block the calling code until thread is finished.
bool PoolJoinable () const
 Check if the internal pool threads are done executing code and the queue is empty.
void SetMainThreadIPSLimit (int nMaxIterationsPerSecond=0)
 Mutator for the Main Thread Max I P S private member.
int GetPoolNumOfThreads ()
 Accessor for the Pool Num Of Threads private member.
int GetPoolQueueLength ()
 Accessor for the Pool Queue Size private member.
std::vector< void > GetPoolResults ()
 Accessor for the Pool Results private member. The action of getting results will destroy and remove them from this object. This method blocks if the thread is not finished, so no need to call JoinPool() before getting results.
int GetMainThreadMaxIPS () const
 Accessor for the Main Thread Max I P S private member.

Private Attributes

std::tuple< CallbackMap< int8_t >, CallbackMap< uint8_t >, CallbackMap< int16_t >, CallbackMap< uint16_t >, CallbackMap< int32_t >, CallbackMap< uint32_t >, CallbackMap< float >, CallbackMap< double >, CallbackMap< char > > m_tpCallbackMaps
uint64_t m_ullNextCallbackID = 1
std::atomic_int m_nTCPSocket
struct sockaddr_in m_saTCPServerAddr
std::atomic_int m_nCurrentTCPClientSocket
struct sockaddr_in m_saClientAddr
std::shared_mutex m_muCallbackMutex
std::mutex m_muSocketSendMutex
Private Attributes inherited from AutonomyThread< void >
IPS m_IPS

Detailed Description

The RoveCommTCP class is used to send and receive data over a TCP connection.

Author
Eli Byrd (edbgk.nosp@m.k@ms.nosp@m.t.edu)
Date
2024-02-07

Member Typedef Documentation

◆ CallbackMap

template<typename T>
using rovecomm::RoveCommTCP::CallbackMap = std::unordered_map<uint16_t, std::vector<CallbackEntry<T>>>
private

Constructor & Destructor Documentation

◆ RoveCommTCP()

rovecomm::RoveCommTCP::RoveCommTCP ( )

Construct a new RoveCommTCP::RoveCommTCP object.

Author
clayjay3 (clayt.nosp@m.onra.nosp@m.ycowe.nosp@m.n@gm.nosp@m.ail.c.nosp@m.om)
Date
2024-03-07
42 {
43 // Initialize member variables.
44 m_nTCPSocket = -1;
46
47 // Set an IPS cap in the backend RoveComm thread.
49 }
void SetMainThreadIPSLimit(int nMaxIterationsPerSecond=0)
Definition AutonomyThread.hpp:515
std::atomic_int m_nTCPSocket
Definition RoveCommTCP.h:90
std::atomic_int m_nCurrentTCPClientSocket
Definition RoveCommTCP.h:92
const int ROVECOMM_THREAD_MAX_IPS
Definition RoveCommConsts.h:30
Here is the call graph for this function:

◆ ~RoveCommTCP()

rovecomm::RoveCommTCP::~RoveCommTCP ( )

Destroy the RoveCommTCP::RoveCommTCP object.

Author
Eli Byrd (edbgk.nosp@m.k@ms.nosp@m.t.edu)
Date
2024-02-07
58 {
59 Close();
60 }
void Close()
Closes the TCP socket.
Definition RoveCommTCP.cpp:459
Here is the call graph for this function:

Member Function Documentation

◆ Clear()

void rovecomm::RoveCommTCP::Clear ( const CallbackHandle & stHandle)

Remove the one callback identified by a handle from On(). Other callbacks for the same data ID stay registered. Waits for a callback that is already running, so once this returns the removed callback can no longer run. An empty or already-removed handle is ignored.

Parameters
stHandle- The handle On() returned for the callback.
Author
clayjay3 (clayt.nosp@m.onra.nosp@m.ycowe.nosp@m.n@gm.nosp@m.ail.c.nosp@m.om)
Date
2026-09-26
252 {
253 // An empty handle was never registered.
254 if (stHandle.ullID == 0)
255 {
256 return;
257 }
258
259 // Dispatch to the map for the handle's payload type.
260 switch (stHandle.eDataType)
261 {
270 case manifest::DataTypes::CHAR: RemoveCallback<char>(stHandle); break;
271 }
272 }
void RemoveCallback(const CallbackHandle &stHandle)
Remove the one callback identified by a handle from this node's map for payload type T.
Definition RoveCommTCP.cpp:285
@ INT32_T
Definition RoveCommManifest.h:39
@ INT16_T
Definition RoveCommManifest.h:37
@ UINT32_T
Definition RoveCommManifest.h:40
@ INT8_T
Definition RoveCommManifest.h:35
@ UINT8_T
Definition RoveCommManifest.h:36
@ FLOAT_T
Definition RoveCommManifest.h:41
@ UINT16_T
Definition RoveCommManifest.h:38
@ DOUBLE_T
Definition RoveCommManifest.h:42
@ CHAR
Definition RoveCommManifest.h:43
Here is the call graph for this function:
Here is the caller graph for this function:

◆ Close()

void rovecomm::RoveCommTCP::Close ( )

Closes the TCP socket.

Author
Eli Byrd (edbgk.nosp@m.k@ms.nosp@m.t.edu)
Date
2024-02-07
460 {
461 // Check if the TCP socket is open
462 if (m_nTCPSocket != -1)
463 {
464 // Stop the threaded continuous code
465 RequestStop();
466 Join();
467
468 // Close the TCP socket
470
471#if defined(__ROVECOMM_WINDOWS_MODE__) && __ROVECOMM_WINDOWS_MODE__ == 1
472 WSACleanup();
473#endif
474 }
475 }
#define CLOSE_SOCKET
Definition RoveCommTCP.cpp:20
void Join()
Definition AutonomyThread.hpp:198
void RequestStop()
Definition AutonomyThread.hpp:182
Here is the call graph for this function:
Here is the caller graph for this function:

◆ GetCallbackMap()

template<typename T>
CallbackMap< T > & rovecomm::RoveCommTCP::GetCallbackMap ( )
inlineconstexprprivate
82 {
83 return std::get<CallbackMap<T>>(m_tpCallbackMaps);
84 }
std::tuple< CallbackMap< int8_t >, CallbackMap< uint8_t >, CallbackMap< int16_t >, CallbackMap< uint16_t >, CallbackMap< int32_t >, CallbackMap< uint32_t >, CallbackMap< float >, CallbackMap< double >, CallbackMap< char > > m_tpCallbackMaps
Definition RoveCommTCP.h:77
Here is the caller graph for this function:

◆ GetIPS()

IPS & AutonomyThread< T >::GetIPS ( )
inline

Accessor for the Frame I P S private member.

Returns
IPS& - The iteration per second counter for the ThreadedContinuousCode()
Author
clayjay3 (clayt.nosp@m.onra.nosp@m.ycowe.nosp@m.n@gm.nosp@m.ail.c.nosp@m.om)
Date
2023-08-20
242{ return m_IPS; }
IPS m_IPS
Definition AutonomyThread.hpp:278

◆ Init()

bool rovecomm::RoveCommTCP::Init ( const manifest::AddressEntry & stIPAddress = {0, 0, 0, 0},
int nPort = manifest::General::ETHERNET_TCP_PORT )

Initializes a TCP socket and binds it to the specified IP address and port. And then starts the threaded continuous code in AutonomyThread.

Parameters
stIPAddress- The IP address to bind the socket to. If set to "", the socket will be bound to all available interfaces.
nPort- The port to bind the socket to. If set to 0, the OS will automatically assign an available port.
Returns
true - The TCP socket was successfully initialized and bound.
false - The TCP socket failed to initialize and bind.
Author
Eli Byrd (edbgk.nosp@m.k@ms.nosp@m.t.edu)
Date
2024-02-07
77 {
78#if defined(__ROVECOMM_WINDOWS_MODE__) && __ROVECOMM_WINDOWS_MODE__ == 1
79 WSADATA wsaData;
80 if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
81 {
82 std::cerr << "WSAStartup failed." << std::endl;
83 return 1;
84 }
85#endif
86
87 // Create a TCP socket
88 m_nTCPSocket = socket(AF_INET, SOCK_STREAM, 0);
89 if (m_nTCPSocket == -1)
90 {
91 perror("Failed to create TCP socket");
92 return false;
93 }
94 else
95 {
96#if defined(__ROVECOMM_WINDOWS_MODE__) && __ROVECOMM_WINDOWS_MODE__ == 1
97 u_long mode = 1; // 1 to enable non-blocking mode
98 if (ioctlsocket(m_nTCPSocket, FIONBIO, &mode) == SOCKET_ERROR)
99 {
100 // Handle and print error.
101 int err = WSAGetLastError();
102 fprintf(stderr, "Failed to set UDP socket to non-blocking mode. Error code: %d\n", err);
103 return false;
104 }
105#else
106 if (fcntl(m_nTCPSocket, F_SETFL, fcntl(m_nTCPSocket, F_GETFL) | O_NONBLOCK) == -1)
107 {
108 // Handle and print error.
109 perror("Failed to set UDP socket to non-blocking mode.");
110 return false;
111 }
112#endif
113 }
114
115 // Configure the server address
116 memset(&m_saTCPServerAddr, 0, sizeof(m_saTCPServerAddr));
117 m_saTCPServerAddr.sin_family = AF_INET;
118 m_saTCPServerAddr.sin_addr.s_addr =
119 htonl(stIPAddress.FIRST_OCTET << 24 | stIPAddress.SECOND_OCTET << 16 | stIPAddress.THIRD_OCTET << 8 | stIPAddress.FOURTH_OCTET);
120 m_saTCPServerAddr.sin_port = htons(nPort);
121
122 // Bind the socket to the server address
123 if (bind(m_nTCPSocket.load(), (struct sockaddr*) &m_saTCPServerAddr, sizeof(m_saTCPServerAddr)) == -1)
124 {
125 perror("Failed to bind TCP socket");
127 return false;
128 }
129
130 // Listen for incoming connections
131 if (listen(m_nTCPSocket, 5) == -1)
132 {
133 perror("Failed to listen on TCP socket");
135 return false;
136 }
137
138 // Start the threaded continuous code
139 Start();
140
141 return true;
142 }
void Start()
Definition AutonomyThread.hpp:129
struct sockaddr_in m_saTCPServerAddr
Definition RoveCommTCP.h:91
int THIRD_OCTET
Definition RoveCommManifest.h:67
int FOURTH_OCTET
Definition RoveCommManifest.h:68
int FIRST_OCTET
Definition RoveCommManifest.h:65
int SECOND_OCTET
Definition RoveCommManifest.h:66
Here is the call graph for this function:
Here is the caller graph for this function:

◆ On() [1/2]

template<typename T>
CallbackHandle rovecomm::RoveCommTCP::On ( const uint16_t unDataId,
std::function< void(const RoveCommPacket< T > &)> fnCallback )

Register a callback for TCP packets with the given data ID. The callback belongs to this node: packets received by any other node never invoke it.

Template Parameters
T- The payload type of the packets. Must be one of the manifest's types.
Parameters
unDataId- The data ID that invokes the callback.
fnCallback- The callback. It runs on this node's receive thread and must not call On() or Clear() on this node.
Returns
CallbackHandle - Pass it to Clear() to remove this callback, and only this one.
Author
Eli Byrd (edbgk.nosp@m.k@ms.nosp@m.t.edu)
Date
2024-02-07
228 {
229 // Acquire a write lock to protect the callback maps.
230 std::unique_lock lkCallbackLock(m_muCallbackMutex);
231
232 // Give the callback an ID so Clear() can remove exactly this one later.
233 const uint64_t ullID = m_ullNextCallbackID++;
234 // Note: C++ will default initialize a new vector if no entry is found.
235 GetCallbackMap<T>()[unDataId].push_back({ullID, std::move(fnCallback)});
236
237 return {.unDataId = unDataId, .eDataType = RoveCommPacket<T>::eDataType, .ullID = ullID};
238 }
constexpr CallbackMap< T > & GetCallbackMap()
Definition RoveCommTCP.h:81
std::shared_mutex m_muCallbackMutex
Definition RoveCommTCP.h:94
uint64_t m_ullNextCallbackID
Definition RoveCommTCP.h:78
static constexpr manifest::DataTypes eDataType
Definition RoveCommPacket.h:79
Here is the call graph for this function:
Here is the caller graph for this function:

◆ On() [2/2]

template<typename manifest::ManifestEntry Entry>
CallbackHandle rovecomm::RoveCommTCP::On ( std::function< void(const RoveCommPacket< EntryType< Entry > > &)> fnCallback)
inline
146 {
147 return On(Entry.DATA_ID, fnCallback);
148 }
CallbackHandle On(const uint16_t unDataId, std::function< void(const RoveCommPacket< T > &)> fnCallback)
Register a callback for TCP packets with the given data ID. The callback belongs to this node: packet...
Definition RoveCommTCP.cpp:227
Here is the call graph for this function:

◆ PooledLinearCode()

void rovecomm::RoveCommTCP::PooledLinearCode ( )
overrideprivatevirtual

The pooled linear code for the TCP class. This method is not implemented and will do nothing.

Note
This method is not intended to be called directly. It is called by the Start method to start the pooled linear code.
Author
Eli Byrd (edbgk.nosp@m.k@ms.nosp@m.t.edu)
Date
2024-02-07

Implements AutonomyThread< void >.

451{}

◆ ProcessPacket()

template<typename T>
void rovecomm::RoveCommTCP::ProcessPacket ( std::span< const uint8_t > spData)
private

Processes a received packet and invokes the appropriate callback function from the vector of TCP callbacks for the specified data type. The data is unpacked into a RoveCommPacket and the appropriate callback function is invoked based on the data id.

Template Parameters
T- The data type of the RoveCommPacket. Must be one of the following: uint8_t, int8_t, uint16_t, int16_t, uint32_t, int32_t, float, double, or char.
Parameters
stData- The received RoveCommData to process and invoke the appropriate callback function.
vCallbacks- The vector of TCP callbacks for the specified data type. The callback function will be invoked based on the data id of the received packet.
Note
This method is not intended to be called directly. It is called by the ReceiveTCPPacketAndCallback method to process a received packet and invoke the appropriate callback function.
Author
Eli Byrd (edbgk.nosp@m.k@ms.nosp@m.t.edu)
Date
2024-02-07
330 {
331 // Create instance variables.
332 RoveCommPacket<T> stPacket = UnpackData<T>(spData);
333
334 // Acquire a read lock to protect the callback vectors.
335 std::shared_lock lkCallbackLock(m_muCallbackMutex);
336
337 // Invoke the callbacks this node has for the packet's data ID.
338 const CallbackMap<T>& umCallbacks = GetCallbackMap<T>();
339 auto itEntry = umCallbacks.find(stPacket.unDataId);
340 if (itEntry != umCallbacks.end())
341 {
342 for (const CallbackEntry<T>& stEntry : itEntry->second)
343 {
344 stEntry.fnCallback(stPacket);
345 }
346 }
347 }
std::unordered_map< uint16_t, std::vector< CallbackEntry< T > > > CallbackMap
Definition RoveCommTCP.h:64
RoveCommPacket< T > UnpackData(std::span< const uint8_t > spBytes)
Create a RoveCommPacket structure from a RoveCommData structure.
Definition RoveCommPacket.cpp:144
Definition RoveCommTCP.h:57
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ReceiveAndCallback()

void rovecomm::RoveCommTCP::ReceiveAndCallback ( )
private

Receives a TCP packet from a client and invokes the appropriate callback function from the vector of TCP callbacks for the specified data type. The data is unpacked into a RoveCommPacket and the appropriate callback function is invoked based on the data id.

Note
This method is not intended to be called directly. It is called by the ThreadedContinuousCode method to receive a TCP packet from a client and invoke the appropriate callback function. This method will run indefinitely and will block the thread until a client connection is accepted and data is received.
Author
Eli Byrd (edbgk.nosp@m.k@ms.nosp@m.t.edu)
Date
2024-02-07
365 {
367 {
368 // Accept a client connection
369 struct sockaddr_in m_saClientAddr;
370 socklen_t sklClientAddrLen = sizeof(m_saClientAddr);
371 m_nCurrentTCPClientSocket = accept(m_nTCPSocket, (struct sockaddr*) &m_saClientAddr, &sklClientAddrLen);
372 }
373 else
374 {
375 // Receive data from the client
376 std::array<uint8_t, ROVECOMM_PACKET_MAX_DATA_SIZE> aData;
377#if defined(__ROVECOMM_WINDOWS_MODE__) && __ROVECOMM_WINDOWS_MODE__ == 1
378 ssize_t siBytesReceived = recv(m_nCurrentTCPClientSocket, reinterpret_cast<char*>(aData.data()), sizeof(aData), 0);
379#else
380 ssize_t siBytesReceived = recv(m_nCurrentTCPClientSocket, aData.data(), sizeof(aData), MSG_DONTWAIT);
381#endif
382
383 if (siBytesReceived < 0)
384 {
385 // Still waiting for data or connection return without error.
386 if (errno != EAGAIN && errno != EWOULDBLOCK)
387 {
388 perror("Failed to receive data from TCP socket using recv.");
389 }
390 return;
391 }
392 // Process the received packet and invoke the appropriate callback
393
394 if (siBytesReceived < ROVECOMM_PACKET_HEADER_SIZE)
395 {
396 throw std::runtime_error("Not enough data to parse RoveCommPacket header.");
397 }
398 // Extract the data id from the received data
399 uint16_t unDataId = (static_cast<uint16_t>(aData[1]) << 8) | static_cast<uint16_t>(aData[2]);
400
401 // Determine the data type from the received data
402 manifest::DataTypes eDataType = static_cast<manifest::DataTypes>(aData[5]);
403
404 // Convert RoveCommData to appropriate RoveCommPacket based on data type
405 switch (eDataType)
406 {
416 }
417
418 // Close the client socket
421 // TODO: Keep connections open after recv()
422 }
423 }
void ProcessPacket(std::span< const uint8_t > stData)
Processes a received packet and invokes the appropriate callback function from the vector of TCP call...
Definition RoveCommTCP.cpp:329
struct sockaddr_in m_saClientAddr
Definition RoveCommTCP.h:93
DataTypes
Enumeration of Data Types to be used in RoveComm.
Definition RoveCommManifest.h:34
const int ROVECOMM_PACKET_HEADER_SIZE
Definition RoveCommConsts.h:26
Here is the call graph for this function:
Here is the caller graph for this function:

◆ RemoveCallback()

template<typename T>
void rovecomm::RoveCommTCP::RemoveCallback ( const CallbackHandle & stHandle)
private

Remove the one callback identified by a handle from this node's map for payload type T.

Template Parameters
T- The payload type the handle was registered with.
Parameters
stHandle- The handle On() returned for the callback.
Author
clayjay3 (clayt.nosp@m.onra.nosp@m.ycowe.nosp@m.n@gm.nosp@m.ail.c.nosp@m.om)
Date
2026-09-26
286 {
287 // Acquire a write lock. This waits for a callback that is already running.
288 std::unique_lock lkCallbackLock(m_muCallbackMutex);
289
290 // Find the callbacks for the handle's data ID and drop the one with the handle's ID.
291 CallbackMap<T>& umCallbacks = GetCallbackMap<T>();
292 auto itEntry = umCallbacks.find(stHandle.unDataId);
293 if (itEntry == umCallbacks.end())
294 {
295 return;
296 }
297 std::erase_if(itEntry->second, [&stHandle](const CallbackEntry<T>& stEntry) { return stEntry.ullID == stHandle.ullID; });
298
299 // Drop the data ID entirely once its last callback is gone.
300 if (itEntry->second.empty())
301 {
302 umCallbacks.erase(itEntry);
303 }
304 }
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ThreadedContinuousCode()

void rovecomm::RoveCommTCP::ThreadedContinuousCode ( )
overrideprivatevirtual

The threaded continuous code for the TCP class. This method calls the ReceiveTCPPacketAndCallback method to receive a TCP packet from a client and invoke the appropriate callback function.

Note
This method is not intended to be called directly. It is called by the Start method to start the threaded continuous code.
Author
Eli Byrd (edbgk.nosp@m.k@ms.nosp@m.t.edu)
Date
2024-02-07

Implements AutonomyThread< void >.

437 {
439 }
void ReceiveAndCallback()
Receives a TCP packet from a client and invokes the appropriate callback function from the vector of ...
Definition RoveCommTCP.cpp:364
Here is the call graph for this function:

◆ WriteTo() [1/3]

template<typename T>
ssize_t rovecomm::RoveCommTCP::WriteTo ( const RoveCommPacket< T > & stPacket,
const manifest::AddressEntry & stClientIPAddress,
int nClientPort = manifest::General::ETHERNET_UDP_PORT )

Sends a TCP packet to the specified client IP address and port. The data is packed into a RoveCommData struct and sent over the TCP socket.

Template Parameters
T- The data type of the RoveCommPacket. Must be one of the following: uint8_t, int8_t, uint16_t, int16_t, uint32_t, int32_t, float, double, or char.
Parameters
stData- The RoveCommPacket to send over the TCP socket.
stClientIPAddress- The IP address of the client to send the packet to.
nClientPort- The port of the client to send the packet to.
Returns
ssize_t - The number of bytes sent over the TCP socket. Returns -1 if an error occurred.
Author
Eli Byrd (edbgk.nosp@m.k@ms.nosp@m.t.edu)
Date
2024-02-07
163 {
164 // Create a TCP socket
165 int nClientSocket = socket(AF_INET, SOCK_STREAM, 0);
166 if (nClientSocket == -1)
167 {
168 perror("Failed to create TCP client socket");
169 return -1;
170 }
171
172 // Configure the client address
173 struct sockaddr_in saClientAddr;
174 memset(&saClientAddr, 0, sizeof(saClientAddr));
175 saClientAddr.sin_family = AF_INET;
176 saClientAddr.sin_port = htons(nClientPort);
177 saClientAddr.sin_addr.s_addr =
178 htonl(stClientIPAddress.FIRST_OCTET << 24 | stClientIPAddress.SECOND_OCTET << 16 | stClientIPAddress.THIRD_OCTET << 8 | stClientIPAddress.FOURTH_OCTET);
179 // Connect to the client
180 if (connect(nClientSocket, (struct sockaddr*) &saClientAddr, sizeof(saClientAddr)) == -1)
181 {
182 perror("Connection failed");
183 CLOSE_SOCKET(nClientSocket);
184 return -1;
185 }
186
187 // Pack the data
188 std::vector<uint8_t> vData = PackPacket(stPacket);
189 // Get size of data not including the data not filled. (the null/zero data in RoveCommData)
190 size_t siDataSize = ROVECOMM_PACKET_HEADER_SIZE + stPacket.GetDataSize();
191
192 // Acquire a write lock on the socket send mutex to protect the socket, which is shared between threads, but not thread-safe.
193 std::unique_lock lkSocketSendLock(m_muSocketSendMutex);
194 // Send the data
195#if defined(__ROVECOMM_WINDOWS_MODE__) && __ROVECOMM_WINDOWS_MODE__ == 1
196 ssize_t siBytesSent = send(nClientSocket, reinterpret_cast<char*>(&stData), siDataSize, 0);
197#else
198 ssize_t siBytesSent = send(nClientSocket, vData.data(), siDataSize, 0);
199#endif
200 // Check if any bytes were sent.
201 if (siBytesSent == -1)
202 {
203 // Handle and print error message.
204 perror("Failed to send data to TCP client socket");
205 }
206
207 // Close the client socket
208 CLOSE_SOCKET(nClientSocket);
209
210 return siBytesSent;
211 }
std::mutex m_muSocketSendMutex
Definition RoveCommTCP.h:95
std::vector< uint8_t > PackPacket(const RoveCommPacket< T > &stPacket)
Create a RoveCommData structure from a RoveCommPacket structure.
Definition RoveCommPacket.cpp:44
Here is the call graph for this function:
Here is the caller graph for this function:

◆ WriteTo() [2/3]

template<typename manifest::ManifestEntry Entry>
ssize_t rovecomm::RoveCommTCP::WriteTo ( std::initializer_list< EntryType< Entry > > ilData,
const manifest::AddressEntry & stIPAddress = manifest::Helpers::FindBoardById(Entry.DATA_ID).ADDRESS,
int nPort = manifest::General::ETHERNET_UDP_PORT )
inline
136 {
137 return WriteTo(rovecomm::CreatePacket<Entry>(ilData), stIPAddress, nPort);
138 }
ssize_t WriteTo(const RoveCommPacket< T > &stPacket, const manifest::AddressEntry &stIPAddress, int nPort=manifest::General::ETHERNET_UDP_PORT)
Sends a TCP packet to the specified client IP address and port. The data is packed into a RoveCommDat...
Definition RoveCommTCP.cpp:162
RoveCommPacket< EntryType< Entry > > CreatePacket()
Definition RoveCommPacket.h:117
Here is the call graph for this function:

◆ WriteTo() [3/3]

template<typename manifest::ManifestEntry Entry>
ssize_t rovecomm::RoveCommTCP::WriteTo ( std::span< const EntryType< Entry > > spData,
const manifest::AddressEntry & stIPAddress = manifest::Helpers::FindBoardById(Entry.DATA_ID).ADDRESS,
int nPort = manifest::General::ETHERNET_UDP_PORT )
inline
128 {
129 return WriteTo(rovecomm::CreatePacket<Entry>(spData), stIPAddress, nPort);
130 }
Here is the call graph for this function:

Member Data Documentation

◆ m_muCallbackMutex

std::shared_mutex rovecomm::RoveCommTCP::m_muCallbackMutex
private

◆ m_muSocketSendMutex

std::mutex rovecomm::RoveCommTCP::m_muSocketSendMutex
private

◆ m_nCurrentTCPClientSocket

std::atomic_int rovecomm::RoveCommTCP::m_nCurrentTCPClientSocket
private

◆ m_nTCPSocket

std::atomic_int rovecomm::RoveCommTCP::m_nTCPSocket
private

◆ m_saClientAddr

struct sockaddr_in rovecomm::RoveCommTCP::m_saClientAddr
private

◆ m_saTCPServerAddr

struct sockaddr_in rovecomm::RoveCommTCP::m_saTCPServerAddr
private

◆ m_tpCallbackMaps

std::tuple<CallbackMap<int8_t>, CallbackMap<uint8_t>, CallbackMap<int16_t>, CallbackMap<uint16_t>, CallbackMap<int32_t>, CallbackMap<uint32_t>, CallbackMap<float>, CallbackMap<double>, CallbackMap<char> > rovecomm::RoveCommTCP::m_tpCallbackMaps
private

◆ m_ullNextCallbackID

uint64_t rovecomm::RoveCommTCP::m_ullNextCallbackID = 1
private

The documentation for this class was generated from the following files: