#include "master.h" #include "pthread.h" #include "nanomsg/nn.h" #include "nanomsg/survey.h" #include "json-c/json.h" #include #include #include "sleep.h" static pthread_t master_thread; static int master_sock; static int master_must_terminate = 0; static void *master_func( void *thread_data ) { char *control = (char *)thread_data; master_sock = nn_socket( AF_SP, NN_SURVEYOR ); (void)nn_bind( master_sock, control ); printf( "master connected to %s\n", control ); sleep( 1 ); json_object *obj = json_object_new_object( ); json_object *op = json_object_new_string( "discover" ); json_object_object_add( obj, "op", op ); const char *msg = json_object_to_json_string( obj ); int msg_size = strlen( msg ) + 1; printf( "master send: %s\n", msg ); int bytes = nn_send( master_sock, msg, msg_size, 0 ); if( bytes != msg_size ) { fprintf( stderr, "ERROR: truncated message!" ); } json_object_put( obj ); while( !master_must_terminate ) { printf( "master idle: %d\n", master_must_terminate ); sleep( 1 ); char *answer = NULL; bytes = nn_recv( master_sock, &answer, NN_MSG, 0 ); if( bytes == ETIMEDOUT ) continue; if( master_must_terminate ) continue; if( bytes >= 0 ) { printf( "master received: %s\n", answer ); nn_freemsg( answer ); } } (void)nn_shutdown( master_sock, 0 ); puts( "master disconnected" ); return NULL; } int master_init( const char *control ) { pthread_attr_t attr; int res; master_must_terminate = 0; res = pthread_attr_init( &attr ); if( res != 0 ) { return 1; } res = pthread_create( &master_thread, &attr, master_func, (void *)control ); if( res != 0 ) { return 1; } return 0; } void master_terminate( ) { master_must_terminate = 1; } int master_free( ) { void *result; int res; res = pthread_join( master_thread, &result ); if( res != 0 ) { return 1; } return 0; }