Project

General

Profile

Statistics
| Revision:

root / trunk / code / projects / colonet / server / ColonetServer.cpp @ 1390

History | View | Annotate | Download (9.31 KB)

1 161 emarinel
/**
2 29 jknichel
 * @file ColonetServer.cpp
3 11 emarinel
 *
4
 * @brief colonet_server - primary server application for Colonet
5
 *
6
 * @author Jason Knichel
7
 * @author Eugene Marinelli
8
 * @date 10/31/06
9
 */
10
11 118 emarinel
#include <arpa/inet.h>
12
#include <fcntl.h>
13
#include <errno.h>
14
#include <netinet/in.h>
15
#include <string.h>
16 409 emarinel
#include <unistd.h>
17 11 emarinel
#include <sys/select.h>
18
#include <sys/socket.h>
19
20 20 jknichel
#include <colonet_wireless.h>
21
22 391 emarinel
#include <ColonetServer.h>
23
#include <ConnectionPool.h>
24
#include <options.h>
25
#include <Log.h>
26 11 emarinel
27
#define LISTEN_BACKLOG 5
28
#define LOG_BUFFER_LENGTH 128
29 424 emarinel
#define MAX_MSG_BUFFER_LENGTH 128
30 661 jknichel
#define REFRESH_VIRTUAL_WALL_PERIOD 400
31 11 emarinel
32 347 emarinel
#define u_int32_t unsigned
33
34 29 jknichel
/**
35
 * @brief Default constructor for ColonetServer
36
 */
37 426 emarinel
ColonetServer::ColonetServer() {
38 24 jknichel
  listen_socket = 0;
39 453 emarinel
  connection_pool = new ConnectionPool(this);
40 20 jknichel
}
41
42 29 jknichel
/**
43
 * @brief Destructor for ColonetServer
44
 */
45 20 jknichel
ColonetServer::~ColonetServer() {
46
}
47
48 29 jknichel
/**
49
 * @brief Initializes the various elements needed for the server to run
50
 *
51
 * @param argc The number of command line arguments passed to the program
52
 * @param argv The command line arguments passed to the program
53
 *
54
 * @return 0 on success, negative error code on failure
55
 */
56 20 jknichel
int ColonetServer::initialize_server(int argc, char * argv[]) {
57 426 emarinel
  options_parseCmdLine(argc, argv);
58 20 jknichel
59 426 emarinel
  if (optionsG.logging_enabled) {
60
    logger = new Log("colonet_server_log.txt");
61
  }
62
63 27 jknichel
  if (initialize_connection(optionsG.listen_port) < 0) {
64 20 jknichel
    return -1;
65 27 jknichel
  }
66 20 jknichel
67 22 jknichel
  if (initialize_wireless() < 0) {
68 20 jknichel
    fprintf(stderr, "%s: initWireless failed\n", __FUNCTION__);
69 939 rcahoon
    //TODO: Can we continue safely without wireless?
70
    //return -1;
71 20 jknichel
  }
72
73
  return 0;
74
}
75
76 29 jknichel
/**
77
 * @brief Starts the server listening on the socket that was opened for listening
78
 *
79
 * @return 0 on success, negative error code on failure
80
 */
81 25 jknichel
int ColonetServer::start_listening() {
82
  if (listen(listen_socket, LISTEN_BACKLOG) < 0) {
83 426 emarinel
    if (optionsG.logging_enabled) {
84
      logger->log_error("\t\nThere was an error telling the socket to listen for connections from clients.  "
85
                        "Terminating Server...\n");
86
    }
87 25 jknichel
    return -1;
88
  }
89 433 emarinel
90 25 jknichel
  return 0;
91
}
92 22 jknichel
93 618 jknichel
/**
94
 * @brief The function that is run in the new pthread in order to do the position monitoring
95
 *
96
 * @param arg the argument to give to the new thread
97
 */
98 938 rcahoon
void* loop_position_monitor(void* arg) {
99 508 emarinel
  PositionMonitor* p = (PositionMonitor*) arg;
100
  p->run();
101
  return NULL;
102
}
103
104 618 jknichel
/**
105
 * @brief This function spawns a new thread to do the position monitoring based off data
106
 *  retrieved from the library that parses the image from the camera
107
 */
108 508 emarinel
int ColonetServer::run_position_monitor() {
109
  pthread_t posmon_thread;
110 938 rcahoon
  pthread_create(&posmon_thread, NULL, loop_position_monitor, &position_monitor);
111 508 emarinel
112
  return 0;
113
}
114
115 939 rcahoon
/**
116
 * @brief The function that is run in the new pthread in order to do the client processing
117
 */
118 938 rcahoon
void ColonetServer::loop_server() {
119 618 jknichel
  //add the socket that you will listen to connections on to the connection pool
120 453 emarinel
  connection_pool->add_new_socket_to_pool(listen_socket);
121 20 jknichel
122 143 jknichel
  int accept_socket = 0;
123
  struct sockaddr_in client_addr;
124
  socklen_t client_addr_size = sizeof(client_addr);
125 20 jknichel
126 426 emarinel
  if (optionsG.logging_enabled) {
127
    logger->log_message("Server initialized.  About to start listening for connections");
128
  }
129 11 emarinel
130 143 jknichel
  while(1) {
131 618 jknichel
    //sleep for a little bit so this program doesn't hog cpu
132 469 emarinel
    usleep(10000);
133
134 618 jknichel
    //tell the connection pool to look at the file descriptors and see which ones are ready
135 453 emarinel
    connection_pool->perform_select(listen_socket);
136 409 emarinel
137 143 jknichel
    //either no descriptors are ready or there was an error
138 453 emarinel
    if (connection_pool->get_number_clients_ready() <= 0) {
139 143 jknichel
      continue;
140
    }
141 11 emarinel
142 618 jknichel
    //check to see if a new client is trying to connect
143 453 emarinel
    if (connection_pool->is_socket_ready_to_read(listen_socket)) {
144 143 jknichel
      printf("Something is trying to connect...\n");
145 618 jknichel
      //accept the connection
146 143 jknichel
      if ((accept_socket = accept(listen_socket, (struct sockaddr*) &client_addr, &client_addr_size)) < 0) {
147 424 emarinel
        if (errno == EMFILE) {
148
          printf("\tWhen attempting to accept a connection, reached the per process limit of file descriptors."
149 618 jknichel
                 "  Dropping the new connection.\n");
150 424 emarinel
          continue;
151
        } else {
152
          printf("\tThere was an error when attempting to accept a connection");
153
        }
154
        continue;
155 11 emarinel
      }
156
157 426 emarinel
      if (optionsG.logging_enabled) {
158 433 emarinel
        char log_buffer[LOG_BUFFER_LENGTH];
159
        snprintf(log_buffer, LOG_BUFFER_LENGTH, "Client at address %s attempting to connect.",
160 648 emarinel
                                                                 inet_ntoa(client_addr.sin_addr));
161 433 emarinel
        logger->log_string(LOG_TYPE_CONNECT, log_buffer);
162 426 emarinel
      }
163 11 emarinel
164 618 jknichel
      //add the new client to the connection pool
165 453 emarinel
      if (connection_pool->add_client(accept_socket) < 0) {
166 424 emarinel
        printf("\tThere was an error when trying to add a client to the connection pool.");
167
        continue;
168 11 emarinel
      }
169
170 426 emarinel
      if (optionsG.logging_enabled) {
171 433 emarinel
        char log_buffer[LOG_BUFFER_LENGTH];
172 426 emarinel
        snprintf(log_buffer, LOG_BUFFER_LENGTH, "Client at address %s successfully added to connection pool.",
173
                 inet_ntoa(client_addr.sin_addr));
174
        logger->log_string(LOG_TYPE_CONNECT, log_buffer);
175
      }
176 11 emarinel
    }
177 143 jknichel
178 618 jknichel
    //check all the clients in the connection pool
179 453 emarinel
    if (connection_pool->check_clients() < 0) {
180 143 jknichel
      printf("\tThere was an error trying to update the clients.");
181
    }
182 11 emarinel
  }
183 938 rcahoon
}
184 11 emarinel
185 939 rcahoon
/**
186
 * @brief Launchpad function to start loop_server() since callbacks don't support member functions
187
 *
188
 * @param arg the argument to give to the new thread
189
 */
190 938 rcahoon
void * launch_loop_server(void *arg) {
191
  ColonetServer *object = (ColonetServer*) arg;
192
  object->loop_server();
193
194
  return NULL;
195
}
196
197
/**
198
 * @brief Starts the server running (starts an infinite loop)
199
 */
200
int ColonetServer::run_server() {
201
  pthread_t server_thread;
202
  pthread_create(&server_thread, NULL, launch_loop_server, this);
203
204 20 jknichel
  return 0;
205 11 emarinel
}
206 20 jknichel
207 939 rcahoon
/**
208
 * @brief Main loop of the server, runs periodic tasks
209
 *
210
 * @return 0 on success, negative error code on failure
211
 */
212 938 rcahoon
int ColonetServer::run_loop() {
213
214
  int refresh_virtual_wall_count = 0;
215
216
  while(1) {
217
    //sleep for a little bit so this program doesn't hog cpu
218
    usleep(10000);
219
220
    /* Refresh virtual wall. */
221
    if (refresh_virtual_wall_count++ == REFRESH_VIRTUAL_WALL_PERIOD) {
222
      fprintf(stderr, "Sending virtual wall info to robots.\n");
223
      refresh_virtual_wall_count = 0;
224
      virtual_wall.send_to_robots();
225
    }
226
  }
227
228
  return 0;
229
}
230
231 424 emarinel
/**
232 618 jknichel
 * @brief when the server receives a new wireless message, it calls this function to process it
233
 *
234
 * @param source - ID of robot that message is from.
235
 * @param dest - ID of internet client to send message to.
236
 * @param data - Data to send to internet client.
237
 * @param len - Length of the data param.
238
 */
239 424 emarinel
int ColonetServer::process_received_wireless_message(int dest, char* data, int len) {
240 618 jknichel
  //try to pass the robot's response onto the client it wanted to respond to
241 453 emarinel
  if (connection_pool->write_to_client(dest, data, len) == ERROR_INVALID_CLIENT_ID) {
242 424 emarinel
    printf("The robot wanted to pass the data to a client not in the pool.\n");
243 140 jknichel
    return -1;
244
  }
245 574 gtress
  printf("Processing data from robot: %s\n", data);
246 140 jknichel
  return 0;
247 20 jknichel
}
248 22 jknichel
249 29 jknichel
/**
250
 * @brief Initializes the wireless
251
 *
252
 * @return 0 on success, negative error code on error
253
 */
254 27 jknichel
int ColonetServer::initialize_wireless() {
255 23 jknichel
  char* log_filename = NULL;
256 22 jknichel
257 23 jknichel
  if (optionsG.logging_enabled) {
258 348 emarinel
    printf("Logging enabled. Log filename: %s\n", optionsG.log_filename);
259 23 jknichel
    log_filename = optionsG.log_filename;
260 347 emarinel
  } else {
261
    printf("Logging disabled.\n");
262 23 jknichel
  }
263
264 618 jknichel
  //initialize the wireless library giving it the port and the log file name
265 424 emarinel
  if (colonet_wl_init(optionsG.wireless_port, log_filename) != 0) {
266 397 emarinel
    fprintf(stderr, "ERROR - colonet_wl_init failed.\n");
267
    return -1;
268
  }
269 347 emarinel
270 618 jknichel
  //call the function that will start the thread that will listen for wireless messages
271 164 emarinel
  if (colonet_wl_run_listener_thread()) {
272 348 emarinel
    fprintf(stderr, "%s: colonet_wl_run_listener_thread failed.\n", __FUNCTION__);
273 34 emarinel
    return -1;
274 161 emarinel
  }
275 23 jknichel
276 34 emarinel
  return 0;
277 23 jknichel
}
278
279 29 jknichel
/**
280
 * @brief Initialize a connection to listen on
281
 *
282
 * @port The port to try to open to listen on
283
 *
284
 * @return 0 on success, negative error code on error
285
 */
286 27 jknichel
int ColonetServer::initialize_connection(int port) {
287 348 emarinel
  printf("Initializing connection that will be used to listen for clients...\n");
288 27 jknichel
  int options = 1;
289
  struct sockaddr_in my_address;
290 23 jknichel
291
  //get a socket fd
292 24 jknichel
  if ((listen_socket = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
293 408 emarinel
    printf("\tThere was an error creating socket\n");
294 23 jknichel
    return -1;
295
  }
296
297
  //set up the address struct
298 27 jknichel
  memset(&my_address,'\0',sizeof(my_address));
299
  my_address.sin_family = AF_INET;
300
  my_address.sin_addr.s_addr = htonl(INADDR_ANY);
301
  my_address.sin_port = htons(port);
302 161 emarinel
303 27 jknichel
  setsockopt(listen_socket, SOL_SOCKET, SO_REUSEADDR, &options, sizeof(options));
304 23 jknichel
305
  //get the current socket options
306 27 jknichel
  if ((options = fcntl(listen_socket, F_GETFL)) < 0) {
307 23 jknichel
    printf("\tThere was an error getting the socket options.\n");
308
    return -1;
309
  }
310
311
  //set the socket to non blocking
312 27 jknichel
  options = (options | O_NONBLOCK);
313
  if (fcntl(listen_socket, F_SETFL, options) < 0) {
314 23 jknichel
    printf("\tThere was an error setting the socket to be non blocking.\n");
315
    return -1;
316
  }
317 161 emarinel
318 23 jknichel
  //bind the socket to listen on the specified port
319 27 jknichel
  if (bind(listen_socket, (struct sockaddr *) &my_address, sizeof(my_address)) < 0) {
320 23 jknichel
    printf("\tThere was an error binding the socket\n");
321
    return -1;
322
  }
323 161 emarinel
324 23 jknichel
  return 0;
325
}
326 443 emarinel
327 618 jknichel
/**
328
 * @brief returns the position monitor
329
 */
330 444 emarinel
PositionMonitor* ColonetServer::getPositionMonitor() {
331
  return &position_monitor;
332 443 emarinel
}
333 659 jknichel
334
VirtualWall* ColonetServer::getVirtualWall() {
335
  return &virtual_wall;
336
}