Exemplo n.º 1
0
void
init( so_5::environment_t & env )
{
	auto coop = env.create_coop( "test" );
	coop->add_agent( new a_parent_t( env ) );
	coop->add_agent( new a_time_sentinel_t( env ) );

	env.register_coop( std::move( coop ) );
}
Exemplo n.º 2
0
void
init( so_5::environment_t & env )
{
	auto coop = env.create_coop( "driver",
			so_5::disp::active_obj::create_disp_binder( "active_obj" ) );

	coop->add_agent( new a_driver_t( env ) );
	coop->add_agent( new a_time_sentinel_t( env ) );

	env.register_coop( std::move( coop ) );
}
Exemplo n.º 3
0
void
init(
	so_5::rt::environment_t & env )
	{
		auto coop = env.create_coop(
				"test_coop",
				so_5::disp::active_obj::create_disp_binder( "active_obj" ) );

		auto svc_mbox = env.create_local_mbox();

		coop->add_agent( new a_convert_service_t( env, svc_mbox ) );
		coop->add_agent( new a_client_t( env, svc_mbox ) );
		coop->add_agent( new a_time_sentinel_t( env ) );

		env.register_coop( std::move( coop ) );
	}
Exemplo n.º 4
0
int
main()
{
	try
	{
		std::string sequence;

		so_5::launch(
			[&sequence]( so_5::environment_t & env )
			{
				auto coop = env.create_coop( "test",
					so_5::disp::active_obj::create_disp_binder( "active_obj" ) );

				auto a_test = new a_test_t( env, sequence );
				const so_5::mbox_t mbox = a_test->so_direct_mbox();

				coop->add_agent( a_test );

				coop->define_agent()
					.on_start( [mbox]() 
						{
							mbox->deliver_signal< msg_one >();
							mbox->deliver_signal< msg_two >();
							mbox->run_one()
								.wait_for( std::chrono::seconds(1) )
								.sync_get< msg_three >();

							mbox->deliver_signal< msg_one >();
							mbox->deliver_signal< msg_two >();

							mbox->deliver_signal< msg_four >();
						} );

				env.register_coop( std::move( coop ) );
			},
			[]( so_5::environment_params_t & params )
			{
				params.add_named_dispatcher( "active_obj",
					so_5::disp::active_obj::create_disp() );
			} );

		const std::string expected = "e1:e3:e2:e4:";
		if( sequence != expected )
			throw std::runtime_error( "sequence mismatch! "
					"expected: '" + expected + "', actual: '"
					+ sequence + "'" );

	}
	catch( const std::exception & ex )
	{
		std::cerr << "Error: " << ex.what() << std::endl;
		return 1;
	}

	return 0;
}
Exemplo n.º 5
0
void
init(
	so_5::rt::environment_t & env,
	unsigned int agent_count,
	unsigned int send_count )
	{
		auto mbox = env.create_local_mbox();

		auto coop = env.create_coop( "benchmark",
				so_5::disp::active_obj::create_disp_binder( "active_obj" ) );
		
		for( unsigned int i = 0; i != agent_count; ++i )
			coop->add_agent( new a_sender_t( env, mbox, send_count ) );

		coop->add_agent( new a_shutdowner_t( env, mbox, agent_count ),
				so_5::rt::create_default_disp_binder() );

		env.register_coop( std::move( coop ) );
	}
Exemplo n.º 6
0
		virtual void
		so_evt_start()
		{
			auto child = so_environment().create_coop(
					so_coop_name() + "::child" );
			child->set_parent_coop_name( so_coop_name() );

			auto mbox = so_environment().create_mbox();
			child->add_agent( new a_test_t( so_environment(), mbox ) );

			so_environment().register_coop( std::move(child) );

			mbox->deliver_signal< msg_test_signal >();
		}
Exemplo n.º 7
0
		void
		evt_parent_started()
		{
			auto coop = so_environment().create_coop( "child",
					so_5::disp::active_obj::create_disp_binder( "active_obj" ) );
			coop->set_parent_coop_name( "parent" );

			coop->add_agent(
				new a_child_t(
					so_environment(),
					so_environment().create_mbox(),
					m_mbox ) );

			so_environment().register_coop( std::move( coop ) );

			so_environment().single_timer< msg_shutdown >( m_mbox, 500 );
		}
Exemplo n.º 8
0
void demography  :: treatkeyevent(Keyboard::Key k)
{
    //if(k==Keyboard::Space)
    //{
    //    if(q)
    //    {
    //        World.DestroyBody(q);
    //        q=0;
    //    }
    //}
    if(k==Keyboard::Space)
    {
        //add();
        for(int i = 0 ; i < 50; ++i)        
        add_agent(conv(last_mouse_pos_b2)+Vec2(getrangerand(-50,50),getrangerand(-50,50)),false);
    }
}
Exemplo n.º 9
0
t_agent creer_agent(char * model,int x, int y, float rx,float ry,float rz,float ratio,int type,int add)
{
  t_agent obj = malloc(sizeof (struct s_agent));
  int i;

  (*obj).x = obj->xgoto = (x + 0.5) * TAILLE_CASE;
  (*obj).y = obj->ygoto = 0;
  (*obj).z = obj->zgoto = (y + 0.5) * TAILLE_CASE;
  (*obj).rx = rx;
  (*obj).ry = ry;
  (*obj).rz = rz;
  (*obj).case_x = x;
  (*obj).case_y = y;
  (*obj).ratio = ratio;
  (*obj).step = 0;
  (*obj).model = create_3Dobj(model);
  (*obj).next = temp_agent;
  (*obj).speed = 0;
  (*obj).caddie = NULL;
  (*obj).is_caddie = !add;
  obj->stimuli = calloc(nb_sti,(sizeof (struct stimuli_agent)));

  for(i=0;i<nb_sti;i++)
    {
      obj->stimuli[i].poids = stimuli[i].task.weight;
      obj->stimuli[i].seuil = stimuli[i].task.threshold;
      obj->stimuli[i].force = stimuli[i].task.force;
    }

  obj->ac_tps = 0.0;
  obj->tps = my_rand(CYCLE);
  obj->age = 1;
  obj->na = 1;
  obj->naa = 0;
  obj->en_cours = 0;
  obj->tache = -1;
  obj->type = type;
  /*obj->ag = type;*/ /* doublon?*//*on dirait*/

  temp_agent = obj;
  if (add)
    add_agent(obj->case_x,obj->case_y,obj);
  
  return(obj);
}
Exemplo n.º 10
0
		void
		so_evt_start()
		{
			auto child_coop = so_environment().create_coop( "child" );
			child_coop->set_parent_coop_name( so_coop_name() );
			child_coop->add_reg_notificator( m_reg_notificator );
			child_coop->add_dereg_notificator( m_dereg_notificator );
			child_coop->add_dereg_notificator(
					[this]( so_5::environment_t &,
						const std::string &,
						const so_5::coop_dereg_reason_t &)
					{
						m_mbox->deliver_signal< msg_child_deregistered >();
					} );

			child_coop->add_agent( new a_child_t( so_environment() ) );

			so_environment().register_coop( std::move( child_coop ) );
		}
Exemplo n.º 11
0
		void
		try_start_new_iteration()
		{
			if( m_iterations_left <= 0 )
			{
				std::cout << "COMPLETED!" << std::endl;

				so_environment().stop();
				return;
			}

			std::cout << m_iterations_left << " iterations left...\r"
				<< std::flush;

			m_state = state_t::awaiting_creation;
			m_acks_received = 0;
			m_destroy_received = 0;

			m_child_mboxes = std::vector< so_5::rt::mbox_t >();
			m_child_mboxes.reserve( m_max_agents );

			auto coop = so_environment().create_coop( "child" );
			coop->set_parent_coop_name( so_coop_name() );
			coop->add_reg_notificator(
					so_5::rt::make_coop_reg_notificator( so_direct_mbox() ) );
			coop->add_dereg_notificator(
					so_5::rt::make_coop_dereg_notificator( so_direct_mbox() ) );

			for( std::size_t i = 0; i != m_max_agents; ++i )
			{
				std::unique_ptr< so_5::rt::agent_t > agent(
						new a_child_t(
								so_environment(),
								so_direct_mbox() ) );
				m_child_mboxes.push_back( agent->so_direct_mbox() );

				coop->add_agent( std::move( agent ) );
			}

			so_environment().register_coop( std::move( coop ) );
		}
Exemplo n.º 12
0
/** main **/
int main(int argc, char **argv)
{
    char *user_msg;

    int c = 0, cmdlist = 0;
    char *cmdexport = NULL;
    char *cmdimport = NULL;
    char *cmdbulk = NULL;

    #ifndef WIN32
    char *dir = DEFAULTDIR;
    char *group = GROUPGLOBAL;
    int gid;
    #else
    FILE *fp;
    TCHAR path[2048];
    DWORD last_error;
    int ret;
    #endif


    /* Setting the name */
    OS_SetName(ARGV0);


    while((c = getopt(argc, argv, "Vhle:r:i:f:")) != -1){
        switch(c){
            case 'V':
                print_version();
                break;
            case 'h':
                helpmsg();
                break;
            case 'e':
                #ifdef CLIENT
                ErrorExit("%s: Key export only available on a master.", ARGV0);
                #endif
                if(!optarg)
                    ErrorExit("%s: -e needs an argument.", ARGV0);
                cmdexport = optarg;
                break;
            case 'r':
                #ifdef CLIENT
                ErrorExit("%s: Key removal only available on a master.", ARGV0);
                #endif
                if(!optarg)
                    ErrorExit("%s: -r needs an argument.", ARGV0);

                /* Use environment variables already available to remove_agent() */
                setenv("OSSEC_ACTION", "r", 1);
                setenv("OSSEC_AGENT_ID", optarg, 1);
                setenv("OSSEC_ACTION_CONFIRMED", "y", 1);
                break;
            case 'i':
                #ifndef CLIENT
                ErrorExit("%s: Key import only available on an agent.", ARGV0);
                #endif
                if(!optarg)
                    ErrorExit("%s: -i needs an argument.", ARGV0);
                cmdimport = optarg;
                break;
            case 'f':
                #ifdef CLIENT
                ErrorExit("%s: Bulk generate keys only available on a master.", ARGV0);
                #endif
                if(!optarg)
                    ErrorExit("%s: -f needs an argument.", ARGV0);
                cmdbulk = optarg;
                printf("Bulk load file: %s\n", cmdbulk);
                break;
            case 'l':
                cmdlist = 1;
                break;
            default:
                helpmsg();
                break;
        }

    }



    /* Get current time */
    time1 = time(0);
    restart_necessary = 0;


    #ifndef WIN32
    /* Getting the group name */
    gid = Privsep_GetGroup(group);
    if(gid < 0)
    {
        ErrorExit(USER_ERROR, ARGV0, "", group);
    }


    /* Setting the group */
    if(Privsep_SetGroup(gid) < 0)
    {
        ErrorExit(SETGID_ERROR, ARGV0, group);
    }


    /* Chrooting to the default directory */
    if(Privsep_Chroot(dir) < 0)
    {
        ErrorExit(CHROOT_ERROR, ARGV0, dir);
    }


    /* Inside chroot now */
    nowChroot();


    /* Starting signal handler */
    StartSIG2(ARGV0, manage_shutdown);

    #else

    /* Get full path to the directory this
     * executable lives in
     */
    ret = GetModuleFileName(NULL, path, sizeof(path));

    /* check for errors */
    if(!ret)
    {
        ErrorExit(GMF_ERROR);
    }

    /* Get last error */
    last_error = GetLastError();

    /* Look for errors */
    if(last_error != ERROR_SUCCESS)
    {
        if(last_error == ERROR_INSUFFICIENT_BUFFER)
        {
            ErrorExit(GMF_BUFF_ERROR, ret, sizeof(path));
        }
        else
        {
            ErrorExit(GMF_UNKN_ERROR, last_error);
        }
    }

    /* Remove file name from path */
    PathRemoveFileSpec(path);

    /* Move to correct directory */
    if(chdir(path))
    {
        ErrorExit(CHDIR_ERROR_2, path);
    }

    /* Check permissions */
    fp = fopen(OSSECCONF, "r");
    if(fp)
    {
        fclose(fp);
    }
    else
    {
        ErrorExit(CONF_ERROR, OSSECCONF);
    }

    #endif

    if(cmdlist == 1)
    {
        list_agents(cmdlist);
        exit(0);
    }
    else if(cmdimport)
    {
        k_import(cmdimport);
        exit(0);
    }
    else if(cmdexport)
    {
        k_extract(cmdexport);
        exit(0);
    }
    else if(cmdbulk)
    {
        k_bulkload(cmdbulk);
        exit(0);
    }



    /* Little shell */
    while(1)
    {
        int leave_s = 0;
        print_banner();

        /* Get ACTION from the environment. If ACTION is specified,
         * we must set leave_s = 1 to ensure that the loop will end */
        user_msg = getenv("OSSEC_ACTION");
        if (user_msg == NULL) {
          user_msg = read_from_user();
        }
        else{
          leave_s = 1;
        }

        /* All the allowed actions */
        switch(user_msg[0])
        {
            case 'A':
            case 'a':
                add_agent();
                break;
            case 'e':
            case 'E':
                k_extract(NULL);
                break;
            case 'i':
            case 'I':
                k_import(NULL);
                break;
            case 'l':
            case 'L':
                list_agents(0);
                break;
            case 'r':
            case 'R':
                remove_agent();
                break;
            case 'q':
            case 'Q':
                leave_s = 1;
                break;
	        case 'V':
		        print_version();
		        break;
            default:
                printf("\n ** Invalid Action ** \n\n");
                break;
        }

        if(leave_s)
        {
            break;
        }

        continue;

    }

    /* Checking if restart message is necessary */
    if(restart_necessary)
    {
        printf(MUST_RESTART);
    }
    else
    {
        printf("\n");
    }
    printf(EXIT);

    return(0);
}
Exemplo n.º 13
0
void WorldWindow::AddOrganism(void) {
	QString fileName = QFileDialog::getOpenFileName(this, tr("Open Genome File"), "", tr("Genome Files (*.genome);;All Files (*)"));
	cout << "filename is " << fileName.toStdString() << endl;
	Agent * new_agent = add_agent(fileName.toStdString().c_str());
	InteractionOptions(new_agent);
}
Exemplo n.º 14
0
static void handle_gc_msg(unsigned code, unsigned gen, int fd, bool isclient) {
    char *source = isclient ? "client" : "worker";
    word_t w;
#if RPT >= 5
    report(5,
"Received GC message with code %u from fd %d (%s), while in state %u",
	   code, fd, source, gc_state);
#endif
    switch (gc_state) {
    case GC_READY:
	if (isclient && code == MSG_GC_START) {
	    /* Garbage collection initiated by client */
#if RPT >= 4
	    report(4, "GC request by client");
#endif
	    do_controller_collect_cmd(0, NULL);
	} else if (!isclient && code == MSG_GC_REQUEST) {
	    if (gen == gc_generation+1) {
#if RPT >= 4
		report(4, "GC request by worker");
#endif
		do_controller_collect_cmd(0, NULL);
	    } else {
#if RPT >= 4
		report(4,
"Outdated (gen = %u, current generation = %u) GC request by worker",
		       gen, gc_generation);
#endif
	    }
	} else {
	    err(false,
		"Unexpected GC message.  Code %u.  In GC_READY state", code);
	}
	break;
    case GC_WAIT_WORKER_START:
	if (code == MSG_GC_START && !isclient) {
	    need_worker_cnt--;
	    if (need_worker_cnt == 0) {
		chunk_ptr msg = msg_new_gc_start();
		set_iterstart(client_fd_set);
		while (set_iternext(client_fd_set, &w)) {
		    int cfd = (int) w;
		    if (!chunk_write(cfd, msg)) {
			err(false,
"Failed to send GC start message to client with fd %d", cfd);
		    }
		}
		chunk_free(msg);
		need_client_fd_set = set_clone(client_fd_set, NULL);
		gc_state = GC_WAIT_CLIENT;
#if RPT >= 3
		report(3, "GC waiting for clients to finish");
#endif
	    }
	} else if (code == MSG_GC_REQUEST) {
#if RPT >= 4
	    report(4,
"GC request by worker while waiting for workers to start.  Ignored.");
#endif
	} else {
	    err(false,
"Unexpected code %u from %s while waiting for workers to start",
		code, source);
	}
	break;
    case GC_WAIT_CLIENT:
	if (code == MSG_GC_FINISH && isclient) {
	    if (set_member(need_client_fd_set, (word_t) fd, true)) {
		if (need_client_fd_set->nelements == 0) {
		    set_free(need_client_fd_set);
		    need_client_fd_set = NULL;
		    chunk_ptr msg = msg_new_gc_finish();
		    set_iterstart(worker_fd_set);
		    while (set_iternext(worker_fd_set, &w)) {
			int wfd = (int) w;
			if (!chunk_write(wfd, msg)) {
			    err(false,
"Failed to send GC Finish message to worker with fd %d", wfd);
			}
		    }
		    chunk_free(msg);
		    gc_state = GC_WAIT_WORKER_FINISH;
#if RPT >= 3
		    report(3, "GC waiting for workers to finish");
#endif
		    need_worker_cnt = worker_fd_set->nelements;
		}
	    } else {
		err(false,
"Got unexpected GC_FINISH message from client with fd %d", fd);
	    }
	} else if (code == MSG_GC_REQUEST) {
#if RPT >= 4
	    report(4,
"GC request by worker while waiting for client.  Ignored.");
#endif
	} else {
	    err(false,
"Unexpected code %u from %s while waiting for clients to finish",
		code, source);
	}
	break;
    case GC_WAIT_WORKER_FINISH:
	if (code == MSG_GC_FINISH && !isclient) {
	    need_worker_cnt--;
	    if (need_worker_cnt == 0) {
		chunk_ptr msg = msg_new_gc_finish();
		set_iterstart(client_fd_set);
		while (set_iternext(client_fd_set, &w)) {
		    int cfd = (int) w;
		    if (!chunk_write(cfd, msg))
			err(false,
"Failed to send GC finish message to client with fd %d", fd);
		}
		chunk_free(msg);
		/* See if there are deferred client connections */
		if (defer_client_fd_set != NULL) {
		    set_iterstart(defer_client_fd_set);
		    while (set_iternext(defer_client_fd_set, &w)) {
			int cfd = (int) w;
			set_insert(client_fd_set, (word_t) cfd);
#if RPT >= 4
			report(4, "Added deferred client with fd %d", cfd);
#endif
			if (need_workers == 0)
			    add_agent(cfd, true);
		    }
		    set_free(defer_client_fd_set);
		    defer_client_fd_set = NULL;
		}
		gc_state = GC_READY;
#if RPT >= 3
		report(3, "GC completed");
#endif
	    }
	} else if (code == MSG_GC_REQUEST) {
#if RPT >= 4
	    report(4,
"GC request by worker while waiting for workers to finish.  Ignored.");
#endif
	} else {
	    err(false,
"Unexpected code %u from %s while waiting for workers to finish",
		code, source);
	}
	break;
    default:
	err(false, "GC in unexpected state %u", gc_state);
    }
}
Exemplo n.º 15
0
/** main **/
int main(int argc, char **argv)
{
    char *user_msg;

    int c = 0, cmdlist = 0;
    char *cmdexport = NULL;
    char *cmdimport = NULL;
    char *cmdbulk = NULL;

    #ifndef WIN32
    char *dir = DEFAULTDIR;
    char *group = GROUPGLOBAL;
    int gid;
    #endif


    /* Setting the name */
    OS_SetName(ARGV0);


    while((c = getopt(argc, argv, "Vhle:r:i:f:")) != -1){
        switch(c){
	        case 'V':
		        print_version();
		        break;
            case 'h':
                helpmsg();
                break;
            case 'd':
                nowDebug();
                break;
            case 'e':
                #ifdef CLIENT
                ErrorExit("%s: You can't export keys on an agent", ARGV0);
                #endif
                if(!optarg)
                    ErrorExit("%s: -e needs an argument",ARGV0);
                cmdexport = optarg;
                break;
            case 'r':
                #ifdef CLIENT
                ErrorExit("%s: You can't remove keys on an agent", ARGV0);
                #endif
                if(!optarg)
                    ErrorExit("%s: -r needs an argument",ARGV0);
	            
                /* Use environment variables already available to remove_agent() */           	
                setenv("OSSEC_ACTION", "r", 1);
                setenv("OSSEC_AGENT_ID", optarg, 1);
                setenv("OSSEC_ACTION_CONFIRMED", "y", 1);
                break;
            case 'i':
                #ifndef CLIENT
                ErrorExit("%s: You can't import keys on the manager.", ARGV0);
                #endif
                if(!optarg)
                    ErrorExit("%s: -i needs an argument",ARGV0);
                cmdimport = optarg;
                break;
            case 'f':
                #ifdef CLIENT
                ErrorExit("%s: You can't bulk generate keys on an agent.", ARGV0);
                #endif
                if(!optarg)
                    ErrorExit("%s: -f needs an argument",ARGV0);
                cmdbulk = optarg;
                printf("Bulk load file: %s\n", cmdbulk);
                break;
            case 'l':
                cmdlist = 1;
                break;
            default:
                helpmsg();
                break;
        }

    }



    /* Getting currently time */
    time1 = time(0);
    restart_necessary = 0;


    #ifndef WIN32
    /* Getting the group name */
    gid = Privsep_GetGroup(group);
    if(gid < 0)
    {
	    ErrorExit(USER_ERROR, ARGV0, "", group);
    }


    /* Setting the group */
    if(Privsep_SetGroup(gid) < 0)
    {
	    ErrorExit(SETGID_ERROR, ARGV0, group);
    }


    /* Chrooting to the default directory */
    if(Privsep_Chroot(dir) < 0)
    {
        ErrorExit(CHROOT_ERROR, ARGV0, dir);
    }


    /* Inside chroot now */
    nowChroot();


    /* Starting signal handler */
    StartSIG2(ARGV0, manage_shutdown);
    #endif


    if(cmdlist == 1)
    {
        list_agents(cmdlist);
        exit(0);
    }
    else if(cmdimport)
    {
        k_import(cmdimport);
        exit(0);
    }
    else if(cmdexport)
    {
        k_extract(cmdexport);
        exit(0);
    }
    else if(cmdbulk)
    {
        k_bulkload(cmdbulk);
        exit(0);
    }



    /* Little shell */
    while(1)
    {
        int leave_s = 0;
        print_banner();

        /* Get ACTION from the environment. If ACTION is specified,
         * we must set leave_s = 1 to ensure that the loop will end */
        user_msg = getenv("OSSEC_ACTION");
        if (user_msg == NULL) {
          user_msg = read_from_user();
        }
        else{
          leave_s = 1;
        }

        /* All the allowed actions */
        switch(user_msg[0])
        {
            case 'A':
            case 'a':
                add_agent();
                break;
            case 'e':
            case 'E':
                k_extract(NULL);
                break;
            case 'i':
            case 'I':
                k_import(NULL);
                break;
            case 'l':
            case 'L':
                list_agents(0);
                break;
            case 'r':
            case 'R':
                remove_agent();
                break;
            case 'q':
            case 'Q':
                leave_s = 1;
                break;
	        case 'V':
		        print_version();
		        break;
            default:
                printf("\n ** Invalid Action ** \n\n");
                break;
        }

        if(leave_s)
        {
            break;
        }

        continue;

    }

    /* Checking if restart message is necessary */
    if(restart_necessary)
    {
        printf(MUST_RESTART);
    }
    else
    {
        printf("\n");
    }
    printf(EXIT);

    return(0);
}
Exemplo n.º 16
0
/*
 * This example shows how to use the C "client" API.
 * It essentially wraps a subset of the JSON API,
 * relevant for a SHERPA mission.
 *
 * For communication zyre is used.
 * Please make ensure a correct zyre configuration file
 * is passed.
 */
int main(int argc, char *argv[]) {

	char agent_name[] = "fw0"; // or wasp1, operator0, ... donkey0, sherpa_box0. Please use the same as SWM_AGENT_NAME environment variable.

	/* Load configuration file for communication setup */
	char config_folder[255] = { SWM_ZYRE_CONFIG_DIR };
	char config_name[] = "swm_zyre_config.json";
	char config_file[512] = {0};
	snprintf(config_file, sizeof(config_file), "%s/%s", config_folder, config_name);

    if (argc == 2) { // override default config
    	snprintf(config_file, sizeof(config_file), "%s", argv[1]);
    }
    
    json_t * config = load_config_file(config_file);//"swm_zyre_config.json");
    if (config == NULL) {
      return -1;
    }

    /* Spawn new communication component */
    component_t *self = new_component(config);
    if (self == NULL) {
    	return -1;
    }
    printf("[%s] component initialized!\n", self->name);
    char *msg;

	/* Input variables */
	double x = 979875;
	double y = 48704;
	double z = 405;
	double utcTimeInMiliSec = 0.0;


	int i;
	struct timeval tp;

	printf("###################### CONNECTIVITY #########################\n");
	char *root_id = 0;
	/* Get the root node ID of the local SHWRPA World Model.
	 * This can be used the check connectivity to the SMW.
	 * Typically false means the local SWM cannot be reached. Is it actually started?
	 */
	assert(get_root_node_id(self, &root_id));
	free(root_id);


	printf("###################### AGENT #########################\n");
	/* column-major layout:
	 * 0 4 8  12
	 * 1 5 9  13
	 * 2 6 10 14
	 * 3 7 11 15
	 *
	 *  <=>
	 *
	 * r11 r12 r13  x
	 * r21 r22 r23  y
	 * r31 r32 r33  z
	 * 3    7   11  15
	 */
	double matrix[16] = { 1, 0, 0, 0,
			               0, 1, 0, 0,
			               0, 0, 1, 0,
			               0, 0, 0, 1}; // y,x,z,1 remember this is column-major!
	matrix[12] = x;
	matrix[13] = y;
	matrix[14] = z;
	assert(add_agent(self, matrix, utcTimeInMiliSec, agent_name));
	assert(add_agent(self, matrix, utcTimeInMiliSec, agent_name)); // twice is not a problem, sine it checks for existance

	/*
	 * Add new observations for potential victims
	 */
	for (i = 0; i < 2; ++i) {
		printf("###################### VICTIM #########################\n");
		gettimeofday(&tp, NULL);
		utcTimeInMiliSec = tp.tv_sec * 1000 + tp.tv_usec / 1000; //get current timestamp in milliseconds
		double matrix[16] = { 1, 0, 0, 0,
				               0, 1, 0, 0,
				               0, 0, 1, 0,
				               0, 0, 0, 1}; // y,x,z,1 remember this is column-major!
		matrix[12] = x;
		matrix[13] = y;
		matrix[14] = z;
		assert(add_victim(self, matrix, utcTimeInMiliSec, agent_name));
	}

	/*
	 * Add new image observations
	 */
	for (i = 0; i < 2; ++i) {
		printf("###################### IMAGE #########################\n");
		gettimeofday(&tp, NULL);
		utcTimeInMiliSec = tp.tv_sec * 1000 + tp.tv_usec / 1000; //get current timestamp in milliseconds
		double matrix[16] = { 1, 0, 0, 0,
				               0, 1, 0, 0,
				               0, 0, 1, 0,
				               0, 0, 0, 1}; // y,x,z,1 remember this is column-major!
		matrix[12] = x;
		matrix[13] = y;
		matrix[14] = z;
		assert(add_image(self, matrix, utcTimeInMiliSec, agent_name, "/tmp/image001.jpg"));
	}

	/*
	 * Add new ARTVA observations (Only relevant for the WASPS)
	 */
	for (i = 0; i < 2; ++i) {
		printf("###################### ARTVA #########################\n");
		gettimeofday(&tp, NULL);
		utcTimeInMiliSec = tp.tv_sec * 1000 + tp.tv_usec / 1000; //get current timestamp in milliseconds
		double matrix[16] = { 1, 0, 0, 0,
				               0, 1, 0, 0,
				               0, 0, 1, 0,
				               0, 0, 0, 1}; // y,x,z,1 remember this is column-major!
		matrix[12] = x;
		matrix[13] = y;
		matrix[14] = z;
		assert(add_artva(self, matrix,  77, 12, 0, 0, utcTimeInMiliSec, agent_name));
	}

	/*
	 * Add new battery values. In fact it is stored in a single battery node and
	 * get updated after first creation.
	 */
	for (i = 0; i < 2; ++i) {
		printf("###################### BATTERY #########################\n");
		double voltage = 20 + i;
		assert(add_battery(self, voltage, "HIGH", utcTimeInMiliSec, agent_name));
	}

	/*
	 * Update pose of this agent
	 */
	for (i = 0; i < 30; ++i) {
			printf("######################  POSE  #########################\n");
			gettimeofday(&tp, NULL);
			utcTimeInMiliSec = tp.tv_sec * 1000 + tp.tv_usec / 1000; //get current timestamp in milliseconds
			double matrix[16] = { 1, 0, 0, 0,
					               0, 1, 0, 0,
					               0, 0, 1, 0,
					               0, 0, 0, 1}; // y,x,z,1 remember this is column-major!
			matrix[12] = x;
			matrix[13] = y;
			matrix[14] = z+i;
			update_pose(self, matrix, utcTimeInMiliSec+i, agent_name);
			usleep(100/*[ms]*/ * 1000);
	}

	/*
	 * Get current position
	 */
	printf("######################  GET POSITION  #########################\n");
	x = 0;
	y = 0;
	z = 0;
	gettimeofday(&tp, NULL);
	utcTimeInMiliSec = tp.tv_sec * 1000 + tp.tv_usec / 1000; //get current timestamp in milliseconds
	get_position(self, &x, &y, &z, utcTimeInMiliSec, agent_name);
	printf ("Latest position of agent = (%f,%f,%f)\n", x,y,z);

	/*
	 * Get ID of mediator
	 */
	printf("######################  GET MEDIATOR ID  #########################\n");
	char* mediator_id = NULL;
	assert(get_mediator_id(self, &mediator_id));
	printf ("ID of mediator = %s\n", mediator_id);
	free(mediator_id);


	printf("######################  DONE  #########################\n");
    /* Clean up */
    destroy_component(&self);
    printf ("SHUTDOWN\n");

	return 0;

}
Exemplo n.º 17
0
static void run_controller(char *infile_name) {
    if (!start_cmd(infile_name))
	return;
    while (!cmd_done()) {
	FD_ZERO(&set);
	int fd;
	word_t w;
	unsigned ip;
	unsigned port;
	add_fd(listen_fd);
	keyvalue_iterstart(new_conn_map);
	/* Check for messages from newly connected clients, workers, and routers */
	while (keyvalue_iternext(new_conn_map, &w, NULL)) {
	    fd = w;
	    add_fd(fd);
	}
	if (need_routers == 0) {
	    /* Accept messages from workers */
	    set_iterstart(worker_fd_set);
	    while (set_iternext(worker_fd_set, &w)) {
		fd = w;
		add_fd(fd);
	    }
	    /* Accept messages from clients */
	    set_iterstart(client_fd_set);
	    while (set_iternext(client_fd_set, &w)) {
		fd = w;
		add_fd(fd);
	    }
	}

	cmd_select(maxfd+1, &set, NULL, NULL, NULL);

	for (fd = 0; fd <= maxfd; fd++) {
	    if (!FD_ISSET(fd, &set))
		continue;
	    if (fd == listen_fd) {
		unsigned ip;
		int connfd = accept_connection(fd, &ip);
		keyvalue_insert(new_conn_map, (word_t) connfd, (word_t) ip);
#if RPT >= 4
		report(4, "Accepted new connection.  Connfd = %d, IP = 0x%x",
		       connfd, ip);
#endif
		continue;
	    }
	    bool eof;
	    chunk_ptr msg = chunk_read(fd, &eof);
	    if (eof) {
		/* Unexpected EOF */
		if (keyvalue_remove(new_conn_map, (word_t) fd, NULL, NULL)) {
		    err(false, "Unexpected EOF from new connection, fd %d", fd);
		} else if (set_member(worker_fd_set, (word_t) fd, true)) {
		    err(false, "Unexpected EOF from connected worker, fd %d.  Shutting down", fd);
		    /* Shut down system */
		    finish_cmd();
		} else if (set_member(client_fd_set, (word_t) fd, true)) {
#if RPT >= 3
		    report(3, "Disconnection from client (fd %d)", fd);
#endif
		    if (need_client_fd_set && set_member(need_client_fd_set,
							 (word_t) fd, false)) {
#if RPT >= 3
			report(3, "Removing client from GC activities");
#endif
			handle_gc_msg(MSG_GC_FINISH, 0, fd, true);
		    }
		} else {
		    err(false, "Unexpected EOF from unknown source, fd %d", fd);
		}
		close(fd);
		continue;
	    }
	    if (msg == NULL) {
		err(false, "Could not read chunk from fd %d (ignored)", fd);
		continue;
	    }
	    word_t h = chunk_get_word(msg, 0);
	    unsigned code = msg_get_header_code(h);
#if RPT >= 5
	    report(5, "Received message with code %d from fd %d", code, fd);
#endif
	    if (keyvalue_remove(new_conn_map, (word_t) fd, NULL, &w)) {
		ip = w;
		chunk_free(msg);
		/* Should be a registration message */
		switch (code) {
		case MSG_REGISTER_ROUTER:
		    if (need_routers == 0) {
			err(false, "Unexpected router registration.  (Ignored)");
			close(fd);
			break;
		    }
		    port = msg_get_header_port(h);
		    word_t node_id = msg_build_node_id(port, ip);
		    set_insert(router_addr_set, node_id);
		    set_insert(router_fd_set, (word_t) fd);
#if RPT >= 4
		    report(4, "Added router with fd %d.  IP 0x%x.  Port %u",
			   fd, ip, port);
#endif
		    need_routers --;
		    if (need_routers == 0) {
#if RPT >= 2
			report(2, "All routers connected");
#endif
			/* Have gotten all of the necessary routers.
			   Notify any registered workers */
			set_iterstart(worker_fd_set);
			int wfd;
			while (set_iternext(worker_fd_set, &w)) {
			    wfd = w;
			    add_agent(wfd, false);
			}
		    }
		    break;
		case MSG_REGISTER_WORKER:
		    if (worker_fd_set->nelements >= worker_cnt) {
			err(false, "Unexpected worker registration.  (Ignored)");
			close(fd);
			break;
		    }
		    set_insert(worker_fd_set, (word_t) fd);
#if RPT >= 4
		    report(4, "Added worker with fd %d", fd);
#endif
		    if (need_routers == 0)
			add_agent(fd, false);
		    break;
		case MSG_REGISTER_CLIENT:
		    if (gc_state == GC_READY) {
			set_insert(client_fd_set, (word_t) fd);
#if RPT >= 4
			report(4, "Added client with fd %d", fd);
#endif
			if (need_workers == 0)
			    add_agent(fd, true);
		    } else {
			if (!defer_client_fd_set) {
			    defer_client_fd_set = word_set_new();
			}
			set_insert(defer_client_fd_set, (word_t) fd);
#if RPT >= 3
			report(3, "Deferring client with fd %d until GC completed",
			       fd);
#endif
		    }
		    break;
		default:
		    err(false, "Unexpected message code %u from new connection",
			code);
		    break;
		}
	    } else if (set_member(worker_fd_set, (word_t) fd, false)) {
		/* Message from worker */
		switch (code) {
		    unsigned agent;
		    unsigned gen;
		case MSG_READY_WORKER:
		    chunk_free(msg);
		    if (need_workers == 0) {
			err(false, "Unexpected worker ready.  (Ignored)");
			close(fd);
			break;
		    }
		    need_workers--;
		    if (need_workers == 0) {
#if RPT >= 2
			report(2, "All workers connected");
#endif			
			/* Notify any pending clients */
			set_iterstart(client_fd_set);
			int cfd;
			while (set_iternext(client_fd_set, &w)) {
			    cfd = w;
			    add_agent(cfd, true);
			}
		    }
		    break;
		case MSG_STAT:
		    /* Message gets stashed away.  Don't free it */
		    add_stat_message(msg);
		    break;
		case MSG_CLIOP_ACK:
		    /* Worker acknowledging receipt of global operation info */
		    agent = msg_get_header_agent(h);
		    int client_fd = receive_global_op_worker_ack(agent);
		    if (client_fd >= 0) {
			/* Have received complete set of acknowledgements. */
			/* Send ack to client */
			if (chunk_write(client_fd, msg)) {
#if RPT >= 6
			    report(6,
"Sent ack to client for global operation with id %u", agent);
#endif
			} else {
			    err(false,
"Failed to send ack to client for global operation with id %u.  Fd %d",
				agent, client_fd);
			}
		    }
		    chunk_free(msg);
		    break;
		case MSG_GC_START:
		case MSG_GC_FINISH:
		    handle_gc_msg(code, 0, fd, false);
		    chunk_free(msg);
		    break;
		case MSG_GC_REQUEST:
		    gen = msg_get_header_generation(h);
		    chunk_free(msg);
		    handle_gc_msg(code, gen, fd, false);
		    break;
		default:
		    chunk_free(msg);
		    err(false, "Unexpected message code %u from worker", code);
		}
	    } else if (set_member(client_fd_set, (word_t) fd, false)) {
		/* Message from client */
		switch(code){
		    unsigned agent;
		    word_t w;
		case MSG_KILL:
		    /* Shutdown entire system */
		    chunk_free(msg);
#if RPT >= 2
		    report(2, "Remote request to kill system");
#endif
		    finish_cmd();
		    return;
		case MSG_DO_FLUSH:
		    /* Initiate a flush operation */
		    chunk_free(msg);
		    flush_requestor_fd = fd;
		    do_controller_flush_cmd(0, NULL);
		    break;
		case MSG_CLIOP_DATA:
		    /* Request for global operation from client */
		    agent = msg_get_header_agent(h);
		    add_global_op(agent, fd);
		    /* Send message to all workers */
		    set_iterstart(worker_fd_set);
		    while (set_iternext(worker_fd_set, &w)) {
			int worker_fd = (int) w;
			if (chunk_write(worker_fd, msg)) {
#if RPT >= 6
			    report(6,
"Sent global operation information with id %u to worker with fd %d",
				   agent, worker_fd);
#endif
			} else {
			    err(false,
"Failed to send global operation information with id %u to worker with fd %d",
				agent, worker_fd);
			}
		    }
		    chunk_free(msg);
		    break;
		case MSG_CLIOP_ACK:
		    /* Completion of global operation by client */
		    agent = msg_get_header_agent(h);
		    /* Send message to all workers */
		    set_iterstart(worker_fd_set);
		    while (set_iternext(worker_fd_set, &w)) {
			int worker_fd = (int) w;
			if (chunk_write(worker_fd, msg)) {
#if RPT >= 6
			    report(6,
"Sent global operation acknowledgement with id %u to worker with fd %d",
				   agent, worker_fd);
#endif
			} else {
			    err(false,
"Failed to send global operation acknowledgement with id %u to worker with fd %d",
				agent, worker_fd);
			}
		    }
		    chunk_free(msg);
		    break;
		case MSG_GC_START:
		case MSG_GC_FINISH:
		    handle_gc_msg(code, 0, fd, true);
		    chunk_free(msg);
		    break;
		default:
		    err(false, "Unexpected message code %u from client", code);
		}

	    } else {
		chunk_free(msg);
		err(false, "Unexpected message on fd %d (Ignored)", fd);
	    }
	}
    }
}