Project

General

Profile

Statistics
| Revision:

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

History | View | Annotate | Download (8.59 KB)

1
/**
2
 * @file ColonetServer.cpp
3
 *
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
#include <arpa/inet.h>
12
#include <fcntl.h>
13
#include <errno.h>
14
#include <netinet/in.h>
15
#include <string.h>
16
#include <unistd.h>
17
#include <sys/select.h>
18
#include <sys/socket.h>
19

    
20
#include <colonet_wireless.h>
21

    
22
#include <ColonetServer.h>
23
#include <ConnectionPool.h>
24
#include <options.h>
25
#include <Log.h>
26

    
27
#define LISTEN_BACKLOG 5
28
#define LOG_BUFFER_LENGTH 128
29
#define MAX_MSG_BUFFER_LENGTH 128
30
#define REFRESH_VIRTUAL_WALL_PERIOD 400
31

    
32
#define u_int32_t unsigned
33

    
34
//TODO: is this needed anymore?  it still compiles when i comment it out
35
//static ConnectionPool* connection_pool;
36

    
37
/**
38
 * @brief Default constructor for ColonetServer
39
 */
40
ColonetServer::ColonetServer() {
41
  listen_socket = 0;
42
  connection_pool = new ConnectionPool(this);
43
}
44

    
45
/**
46
 * @brief Destructor for ColonetServer
47
 */
48
ColonetServer::~ColonetServer() {
49
}
50

    
51
/**
52
 * @brief Initializes the various elements needed for the server to run
53
 *
54
 * @param argc The number of command line arguments passed to the program
55
 * @param argv The command line arguments passed to the program
56
 *
57
 * @return 0 on success, negative error code on failure
58
 */
59
int ColonetServer::initialize_server(int argc, char * argv[]) {
60
  options_parseCmdLine(argc, argv);
61

    
62
  if (optionsG.logging_enabled) {
63
    logger = new Log("colonet_server_log.txt");
64
  }
65

    
66
  if (initialize_connection(optionsG.listen_port) < 0) {
67
    return -1;
68
  }
69

    
70
  if (initialize_wireless() < 0) {
71
    fprintf(stderr, "%s: initWireless failed\n", __FUNCTION__);
72
    return -1;
73
  }
74

    
75
  return 0;
76
}
77

    
78
/**
79
 * @brief Starts the server listening on the socket that was opened for listening
80
 *
81
 * @return 0 on success, negative error code on failure
82
 */
83
int ColonetServer::start_listening() {
84
  if (listen(listen_socket, LISTEN_BACKLOG) < 0) {
85
    if (optionsG.logging_enabled) {
86
      logger->log_error("\t\nThere was an error telling the socket to listen for connections from clients.  "
87
                        "Terminating Server...\n");
88
    }
89
    return -1;
90
  }
91

    
92
  return 0;
93
}
94

    
95
/**
96
 * @brief The function that is run in the new pthread in order to do the position monitoring
97
 *
98
 * @param arg the argument to give to the new thread
99
 */
100
void* run_thread(void* arg) {
101
  PositionMonitor* p = (PositionMonitor*) arg;
102
  p->run();
103
  return NULL;
104
}
105

    
106
/**
107
 * @brief This function spawns a new thread to do the position monitoring based off data 
108
 *  retrieved from the library that parses the image from the camera
109
 */
110
int ColonetServer::run_position_monitor() {
111
  pthread_t posmon_thread;
112
  pthread_create(&posmon_thread, NULL, run_thread, &position_monitor);
113

    
114
  return 0;
115
}
116

    
117
/**
118
 * @brief Starts the server running (starts an infinite loop)
119
 */
120
int ColonetServer::run_server() {
121
  //add the socket that you will listen to connections on to the connection pool
122
  connection_pool->add_new_socket_to_pool(listen_socket);
123

    
124
  int accept_socket = 0;
125
  struct sockaddr_in client_addr;
126
  socklen_t client_addr_size = sizeof(client_addr);
127

    
128
  if (optionsG.logging_enabled) {
129
    logger->log_message("Server initialized.  About to start listening for connections");
130
  }
131

    
132
  int refresh_virtual_wall_count = 0;
133

    
134
  while(1) {
135
    //sleep for a little bit so this program doesn't hog cpu
136
    usleep(10000);
137

    
138
    /* Refresh virtual wall. */
139
    if (refresh_virtual_wall_count == REFRESH_VIRTUAL_WALL_PERIOD) {
140
      fprintf(stderr, "Sending virtual wall info to robots.\n");
141
      refresh_virtual_wall_count = 0;
142
      virtual_wall.send_to_robots();
143
    }
144
    refresh_virtual_wall_count++;
145

    
146
    //tell the connection pool to look at the file descriptors and see which ones are ready
147
    connection_pool->perform_select(listen_socket);
148

    
149
    //either no descriptors are ready or there was an error
150
    if (connection_pool->get_number_clients_ready() <= 0) {
151
      continue;
152
    }
153

    
154
    //check to see if a new client is trying to connect
155
    if (connection_pool->is_socket_ready_to_read(listen_socket)) {
156
      printf("Something is trying to connect...\n");
157
      //accept the connection
158
      if ((accept_socket = accept(listen_socket, (struct sockaddr*) &client_addr, &client_addr_size)) < 0) {
159
        if (errno == EMFILE) {
160
          printf("\tWhen attempting to accept a connection, reached the per process limit of file descriptors."
161
                 "  Dropping the new connection.\n");
162
          continue;
163
        } else {
164
          printf("\tThere was an error when attempting to accept a connection");
165
        }
166
        continue;
167
      }
168

    
169
      if (optionsG.logging_enabled) {
170
        char log_buffer[LOG_BUFFER_LENGTH];
171
        snprintf(log_buffer, LOG_BUFFER_LENGTH, "Client at address %s attempting to connect.",
172
                                                                 inet_ntoa(client_addr.sin_addr));
173
        logger->log_string(LOG_TYPE_CONNECT, log_buffer);
174
      }
175

    
176
      //add the new client to the connection pool
177
      if (connection_pool->add_client(accept_socket) < 0) {
178
        printf("\tThere was an error when trying to add a client to the connection pool.");
179
        continue;
180
      }
181

    
182
      if (optionsG.logging_enabled) {
183
        char log_buffer[LOG_BUFFER_LENGTH];
184
        snprintf(log_buffer, LOG_BUFFER_LENGTH, "Client at address %s successfully added to connection pool.",
185
                 inet_ntoa(client_addr.sin_addr));
186
        logger->log_string(LOG_TYPE_CONNECT, log_buffer);
187
      }
188
    }
189

    
190
    //check all the clients in the connection pool
191
    if (connection_pool->check_clients() < 0) {
192
      printf("\tThere was an error trying to update the clients.");
193
    }
194
  }
195

    
196
  return 0;
197
}
198

    
199
/**
200
 * @brief when the server receives a new wireless message, it calls this function to process it
201
 *
202
 * @param source - ID of robot that message is from.
203
 * @param dest - ID of internet client to send message to.
204
 * @param data - Data to send to internet client.
205
 * @param len - Length of the data param.
206
 */
207
int ColonetServer::process_received_wireless_message(int dest, char* data, int len) {
208
  //try to pass the robot's response onto the client it wanted to respond to
209
  if (connection_pool->write_to_client(dest, data, len) == ERROR_INVALID_CLIENT_ID) {
210
    printf("The robot wanted to pass the data to a client not in the pool.\n");
211
    return -1;
212
  }
213
  printf("Processing data from robot: %s\n", data);
214
  return 0;
215
}
216

    
217
/**
218
 * @brief Initializes the wireless
219
 *
220
 * @return 0 on success, negative error code on error
221
 */
222
int ColonetServer::initialize_wireless() {
223
  char* log_filename = NULL;
224

    
225
  if (optionsG.logging_enabled) {
226
    printf("Logging enabled. Log filename: %s\n", optionsG.log_filename);
227
    log_filename = optionsG.log_filename;
228
  } else {
229
    printf("Logging disabled.\n");
230
  }
231

    
232
  //initialize the wireless library giving it the port and the log file name
233
  if (colonet_wl_init(optionsG.wireless_port, log_filename) != 0) {
234
    fprintf(stderr, "ERROR - colonet_wl_init failed.\n");
235
    return -1;
236
  }
237

    
238
  //call the function that will start the thread that will listen for wireless messages
239
  if (colonet_wl_run_listener_thread()) {
240
    fprintf(stderr, "%s: colonet_wl_run_listener_thread failed.\n", __FUNCTION__);
241
    return -1;
242
  }
243

    
244
  return 0;
245
}
246

    
247
/**
248
 * @brief Initialize a connection to listen on
249
 *
250
 * @port The port to try to open to listen on
251
 *
252
 * @return 0 on success, negative error code on error
253
 */
254
int ColonetServer::initialize_connection(int port) {
255
  printf("Initializing connection that will be used to listen for clients...\n");
256
  int options = 1;
257
  struct sockaddr_in my_address;
258

    
259
  //get a socket fd
260
  if ((listen_socket = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
261
    printf("\tThere was an error creating socket\n");
262
    return -1;
263
  }
264

    
265
  //set up the address struct
266
  memset(&my_address,'\0',sizeof(my_address));
267
  my_address.sin_family = AF_INET;
268
  my_address.sin_addr.s_addr = htonl(INADDR_ANY);
269
  my_address.sin_port = htons(port);
270

    
271
  setsockopt(listen_socket, SOL_SOCKET, SO_REUSEADDR, &options, sizeof(options));
272

    
273
  //get the current socket options
274
  if ((options = fcntl(listen_socket, F_GETFL)) < 0) {
275
    printf("\tThere was an error getting the socket options.\n");
276
    return -1;
277
  }
278

    
279
  //set the socket to non blocking
280
  options = (options | O_NONBLOCK);
281
  if (fcntl(listen_socket, F_SETFL, options) < 0) {
282
    printf("\tThere was an error setting the socket to be non blocking.\n");
283
    return -1;
284
  }
285

    
286
  //bind the socket to listen on the specified port
287
  if (bind(listen_socket, (struct sockaddr *) &my_address, sizeof(my_address)) < 0) {
288
    printf("\tThere was an error binding the socket\n");
289
    return -1;
290
  }
291

    
292
  return 0;
293
}
294

    
295
/**
296
 * @brief returns the position monitor
297
 */
298
PositionMonitor* ColonetServer::getPositionMonitor() {
299
  return &position_monitor;
300
}
301

    
302
VirtualWall* ColonetServer::getVirtualWall() {
303
  return &virtual_wall;
304
}