diff --git a/groundStation/src/microcart_cli.c b/groundStation/src/microcart_cli.c index 52930cf27575840987f61b2251d04e08a28744be..0e8d5cc8b732e946e0cc225e1dd8ee37f84cf301 100644 --- a/groundStation/src/microcart_cli.c +++ b/groundStation/src/microcart_cli.c @@ -46,6 +46,10 @@ int safe_fd_clr(int , fd_set* , int* ); static void cb(struct ucart_vrpn_TrackerData *); static int new_client(int fd); +/* Return index of client, or -1 */ +static ssize_t get_client_index(int fd); +/* Returns pointer to client buffer, or -1 */ +static char * get_client_buffer(int fd); /* Thread-safe wrappers */ pthread_mutex_t quadSocketMutex; @@ -63,7 +67,6 @@ const char *logHeader = "";//"#\n#\tDefault log header\n#\tEverything after '#'` #define CLIENT_BUFFER_SIZE 1024 static char client_buffers[MAX_CLIENTS][CLIENT_BUFFER_SIZE]; static int client_fds[MAX_CLIENTS]; -static size_t num_clients = 0; pthread_mutex_t quadResponseMutex, cliInputMutex ; unsigned char *respBuf, *commandBuf; @@ -426,16 +429,41 @@ static ssize_t writeQuad(const char * buf, size_t count) { static int new_client(int fd) { - if (num_clients >= MAX_CLIENTS) { - close(fd); + ssize_t new_slot = -1; + for (ssize_t i = 0; i < MAX_CLIENTS; i++) { + if (client_fds[i] < 0) { + new_slot = i; + break; + } + } + if (new_slot == -1) { + warnx("Ran out of room! Consider increasing MAX_CLIENTS!"); return 0; } - num_clients++; - int new_slot; - for (size_t i = 0; i < MAX_CLIENTS; i++) { - if - } + client_fds[new_slot] = fd; + client_buffers[new_slot][0] = '\0'; return 1; } + +static ssize_t get_client_index(int fd) +{ + for (ssize_t i = 0; i < MAX_CLIENTS; i++) { + if (client_fds[i] == fd) { + return i; + } + } + + return -1; +} + +static char * get_client_buffer(int fd) +{ + ssize_t slot = get_client_index(fd); + if (slot == -1) { + return NULL; + } else { + return client_buffers[slot]; + } +}