84 lines
2.2 KiB
C
84 lines
2.2 KiB
C
#include <stddef.h>
|
|
#include <stdlib.h>
|
|
#include <unistd.h>
|
|
|
|
#include "server.h"
|
|
#include "db.h"
|
|
#include "connection_handler.h"
|
|
#include "shm_conn_handle.h"
|
|
#include "uds_conn_handle.h"
|
|
#include "mq_conn_handle.h"
|
|
|
|
#include "log.h"
|
|
|
|
server_t* server_create(void) {
|
|
log_info_m("Server starting...");
|
|
|
|
server_t* srv = (server_t*)malloc(sizeof(server_t));
|
|
*srv = (server_t) {
|
|
.running = 1,
|
|
.conn_handlers = {
|
|
create_uds_handler(),
|
|
create_mq_handler(),
|
|
create_tcp_handler(),
|
|
create_shm_handler(),
|
|
},
|
|
};
|
|
srv->num_conn_handlers = sizeof(srv->conn_handlers) / sizeof(connection_handler_t);
|
|
return srv;
|
|
}
|
|
|
|
int server_init(server_t* srv) {
|
|
int errors = 0;
|
|
for (size_t handl_i = 0; handl_i < srv->num_conn_handlers; handl_i++) {
|
|
connection_handler_t* handl = &srv->conn_handlers[handl_i];
|
|
errors += handl->init(handl);
|
|
}
|
|
|
|
// create db on heap
|
|
srv->db = db_create();
|
|
log_info_m("Database initialized");
|
|
|
|
log_ok_m("Server started!");
|
|
|
|
return errors;
|
|
};
|
|
|
|
void server_run(server_t* srv) {
|
|
while (srv->running) {
|
|
for (size_t handl_i = 0; handl_i < srv->num_conn_handlers; handl_i++) {
|
|
connection_handler_t* handl = &srv->conn_handlers[handl_i];
|
|
|
|
connection_result_t result = handl->check_conn(handl);
|
|
switch (result.status) {
|
|
case CONN_NONE:
|
|
break;
|
|
case CONN_NEW:
|
|
// TODO: store TID
|
|
break;
|
|
case CONN_ERR:
|
|
log_err_m("Connection handler returned with error!");
|
|
srv->running = 0;
|
|
return;
|
|
}
|
|
}
|
|
|
|
// little delay, clients can wait!
|
|
usleep(1000 * MAIN_LOOP_SLEEP_MS);
|
|
}
|
|
};
|
|
|
|
void server_close(server_t* srv) {
|
|
write(1, "\r", 1); // return cursor so ^C is overwritten
|
|
log_ok_m("Shutting down...");
|
|
|
|
for (size_t handl_i = 0; handl_i < srv->num_conn_handlers; handl_i++) {
|
|
connection_handler_t* handl = &srv->conn_handlers[handl_i];
|
|
handl->cleanup(handl);
|
|
}
|
|
|
|
free(srv);
|
|
|
|
log_ok_m("Done.");
|
|
}
|