diff --git a/src/control.c b/src/control.c index 6c282d0..c72b38e 100644 --- a/src/control.c +++ b/src/control.c @@ -1,5 +1,49 @@ #include "control.h" + +#include +#include +#include +#include +#include + +static int opensocket(const char *hostname, const char *port) { + struct addrinfo *res = NULL, pref; + int ret; + int s; + + pref.ai_flags = 0; + pref.ai_family = PF_UNSPEC; + pref.ai_socktype = SOCK_STREAM; + pref.ai_protocol = 0; + pref.ai_addrlen = 0; + pref.ai_addr = NULL; + pref.ai_canonname = NULL; + pref.ai_next = NULL; + + if (0 != (ret = getaddrinfo(hostname, port, &pref, &res)) || !res) { + fprintf(stderr, "Couldn't find host/port '%s:%s': %s\n", hostname, port, strerror(errno)); + return -1; + } + + if (-1 == (s = socket(res->ai_family, res->ai_socktype, res->ai_protocol))) { + fprintf(stderr, "Couldn't create socket: %s\n", strerror(errno)); + freeaddrinfo(res); + return -1; + } + + if (0 != connect(s, res->ai_addr, res->ai_addrlen)) { + fprintf(stderr, "Couldn't connect socket to '%s:%s': %s\n", hostname, port, strerror(errno)); + freeaddrinfo(res); + return -1; + } + + freeaddrinfo(res); + return s; +} + + + static void telemetry_free(gpointer _te, gpointer x) { telemetry *te = (telemetry*) _te; UNUSED(x); @@ -13,8 +57,14 @@ static telemetry* telemetry_new() { return te; } -trial *trial_new() { - trial *t = g_slice_new0(trial); +trial *trial_new(const char *hostname, const char *port) { + trial *t; + int sock; + + if (-1 == (sock = opensocket(hostname, port))) return NULL; + + t = g_slice_new0(trial); + t->socket = sock; g_queue_init(&t->telemetry); t->map.solid_objects = g_array_new(FALSE, FALSE, sizeof(object)); return t; @@ -27,6 +77,9 @@ void trial_reset_run(trial *t) { } void trial_wait_for_start(trial *t) { + while (0 == t->telemetry.length) { + trial_wait_for_input(t); + } } void trial_check_input(trial *t) { @@ -36,6 +89,8 @@ void trial_wait_for_input(trial *t) { } void trial_free(trial *t) { + shutdown(t->socket, SHUT_RDWR); + close(t->socket); g_queue_foreach(&t->telemetry, telemetry_free, NULL); g_queue_clear(&t->telemetry); g_array_free(t->map.solid_objects, TRUE); diff --git a/src/control.h b/src/control.h index e541ec8..6b31c64 100644 --- a/src/control.h +++ b/src/control.h @@ -70,7 +70,7 @@ struct trial { }; /* trial */ -trial *trial_new(); +trial *trial_new(const char *hostname, const char *port); void trial_reset_run(trial *t); void trial_wait_for_start(trial *t); void trial_check_input(trial *t); diff --git a/src/main.c b/src/main.c index c493b4a..320eee1 100644 --- a/src/main.c +++ b/src/main.c @@ -1,4 +1,21 @@ +#include "control.h" + +#include + int main(int argc, char **argv) { + trial *t; + + if (argc <= 2) { + fprintf(stderr, "Syntax: %s hostname port\n", argv[0]); + return 1; + } + + if (NULL == (t = trial_new(argv[1], argv[2]))) { + return 2; + } + + trial_free(t); + return 0; }