diff --git a/clients/c/cosmopolite.c b/clients/c/cosmopolite.c index d378dd9..d797824 100644 --- a/clients/c/cosmopolite.c +++ b/clients/c/cosmopolite.c @@ -161,9 +161,12 @@ static void cosmo_handle_message(cosmo *instance, json_t *event) { break; } } - printf("new message: %lld\n", id); json_array_insert(messages, insert_after + 1, event); assert(!pthread_mutex_unlock(&instance->lock)); + + if (instance->callbacks.message) { + instance->callbacks.message(event); + } } static void cosmo_handle_event(cosmo *instance, json_t *event) { @@ -417,7 +420,7 @@ json_t *cosmo_get_last_message(cosmo *instance, json_t *subject) { return ret; } -cosmo *cosmo_create(const char *base_url, const char *client_id) { +cosmo *cosmo_create(const char *base_url, const char *client_id, const cosmo_callbacks *callbacks) { curl_global_init(CURL_GLOBAL_DEFAULT); srandomdev(); @@ -427,6 +430,8 @@ cosmo *cosmo_create(const char *base_url, const char *client_id) { strcpy(instance->client_id, client_id); cosmo_uuid(instance->instance_id); + memcpy(&instance->callbacks, callbacks, sizeof(instance->callbacks)); + assert(!pthread_mutex_init(&instance->lock, NULL)); assert(!pthread_cond_init(&instance->cond, NULL)); diff --git a/clients/c/cosmopolite.h b/clients/c/cosmopolite.h index 8b612eb..5086089 100644 --- a/clients/c/cosmopolite.h +++ b/clients/c/cosmopolite.h @@ -8,9 +8,14 @@ #define COSMO_UUID_SIZE 37 +typedef struct { + void (*message)(const json_t *); +} cosmo_callbacks; + typedef struct { char client_id[COSMO_UUID_SIZE]; char instance_id[COSMO_UUID_SIZE]; + cosmo_callbacks callbacks; pthread_mutex_t lock; pthread_cond_t cond; @@ -26,7 +31,7 @@ typedef struct { void cosmo_uuid(char *uuid); -cosmo *cosmo_create(const char *base_url, const char *client_id); +cosmo *cosmo_create(const char *base_url, const char *client_id, const cosmo_callbacks *callbacks); void cosmo_shutdown(cosmo *instance); const char *cosmo_current_profile(cosmo *instance); diff --git a/clients/c/test.c b/clients/c/test.c index 2339383..ca40b08 100644 --- a/clients/c/test.c +++ b/clients/c/test.c @@ -2,19 +2,23 @@ #include "cosmopolite.h" +void on_message(const json_t *message) { + printf("new message: %lld\n", json_integer_value(json_object_get(message, "id"))); +} + int main(int argc, char *argv[]) { char client_id[COSMO_UUID_SIZE]; cosmo_uuid(client_id); - cosmo *instance = cosmo_create("https://playground.cosmopolite.org/cosmopolite", client_id); + + cosmo_callbacks callbacks = { + .message = on_message + }; + + cosmo *instance = cosmo_create("https://playground.cosmopolite.org/cosmopolite", client_id, &callbacks); json_t *subject = cosmo_subject("foobar", NULL, NULL); cosmo_subscribe(instance, subject, -1, 0); - json_t *message = json_string("test from C"); - cosmo_send_message(instance, subject, message); - json_decref(message); json_decref(subject); - sleep(5); - printf("profile: %s\n", cosmo_current_profile(instance)); - sleep(120); + sleep(20); cosmo_shutdown(instance); return 0;