예제 #1
0
/**************************************************************************
  Measure the time between the calls.  Used to see where in the AI too
  much CPU is being used.
**************************************************************************/
void TIMING_LOG(enum ai_timer timer, enum ai_timer_activity activity)
{
  static int turn = -1;
  int i;

  if (turn == -1) {
    for (i = 0; i < AIT_LAST; i++) {
      aitimer[i][0] = new_timer(TIMER_CPU, TIMER_ACTIVE);
      aitimer[i][1] = new_timer(TIMER_CPU, TIMER_ACTIVE);
      recursion[i] = 0;
    }
  }

  if (game.info.turn != turn) {
    turn = game.info.turn;
    for (i = 0; i < AIT_LAST; i++) {
      clear_timer(aitimer[i][0]);
    }
    assert(activity == TIMER_START);
  }

  if (activity == TIMER_START && recursion[timer] == 0) {
    start_timer(aitimer[timer][0]);
    start_timer(aitimer[timer][1]);
    recursion[timer]++;
  } else if (activity == TIMER_STOP && recursion[timer] == 1) {
    stop_timer(aitimer[timer][0]);
    stop_timer(aitimer[timer][1]);
    recursion[timer]--;
  }
}
예제 #2
0
파일: run-corrupt.c 프로젝트: Maxime2/ccan
int main(int argc, char *argv[])
{
	struct timeabs when;
	struct timers timers;

	plan_tests(7);
	
	when.ts.tv_sec = 0; when.ts.tv_nsec = 0;
	timers_init(&timers, when);

	/* Add these */
	new_timer(&timers, 35000000);
	new_timer(&timers, 38000000);
	new_timer(&timers, 59000000);
	new_timer(&timers, 65000000);
	new_timer(&timers, 88000000);
	new_timer(&timers, 125000000);
	new_timer(&timers, 130000000);
	new_timer(&timers, 152000000);
	new_timer(&timers, 168000000);
	/* Expire all but the last one. */
	update_and_expire(&timers);
	update_and_expire(&timers);
	update_and_expire(&timers);
	update_and_expire(&timers);
	update_and_expire(&timers);
	update_and_expire(&timers);
	update_and_expire(&timers);
	update_and_expire(&timers);
	/* Add a new one. */
	new_timer(&timers, 169000000);
	ok1(timers_check(&timers, NULL));

	/* Used to get the wrong one... */
	timers_dump(&timers, stdout);
	ok1(timer_earliest(&timers, &when));
	ok1(when.ts.tv_nsec == 168000000);
	free(timers_expire(&timers, when));

	ok1(timer_earliest(&timers, &when));
	ok1(when.ts.tv_nsec == 169000000);
	free(timers_expire(&timers, when));

	ok1(timers_check(&timers, NULL));
	ok1(!timer_earliest(&timers, &when));
	timers_cleanup(&timers);

	return exit_status();
}
예제 #3
0
/*
 * Adds a timer to an action with the information necessary to callback later
 * when the timer is up.
 */
void add_timer(CHAR_DATA *ch, int type, int count, DO_FUN *fun, int value, char *argument) {
    //log_f("add_timer ch=%s, type=%d, count=%d, value=%d, argument=%s", ch->name, type, count, value, argument);
    TIMER *timer;

    for (timer = ch->first_timer; timer; timer = timer->next)
    {
        if (timer->type == type && timer->type)
        {
            timer->count = count;
            timer->do_fun = fun;
            timer->value = value;
            timer->cmd = str_dup(argument);
            break;
        }
    }

    if (!timer)
    {
        timer = new_timer();
        //CREATE( timer, TIMER, 1 );
        timer->count = count;
        timer->type = type;
        timer->do_fun = fun;
        timer->value = value;
        timer->cmd = str_dup(argument);
        LINK(timer, ch->last_timer, ch->first_timer, prev, next);
    }

} // end add_timer
예제 #4
0
int AddTimer( TIMER_TYPE type, timer_handler handler, const char *name, int interval, void *userptr )
{
	Timer *timer;
	Module *moduleptr;

	SET_SEGV_LOCATION();
	moduleptr = GET_CUR_MODULE();
	if( handler == NULL )
	{
		nlog( LOG_WARNING, "Module %s timer %s does not exist", moduleptr->info->name, name );
		return NS_FAILURE;
	}
	if( FindTimer( name ) )
	{
		nlog( LOG_WARNING, "Module %s timer %s already exists. Not adding.", moduleptr->info->name, name );
		return NS_FAILURE;
	}
	timer = new_timer( name );
	if( timer )
	{
		timer->type = type;
		timer->interval = interval;
		timer->lastrun = me.now;
		timer->moduleptr = moduleptr;
		timer->handler = handler;
		timer->userptr = userptr;
		TimerCalcNextRun(timer, NULL);
		dlog( DEBUG2, "AddTimer: Module %s added timer %s", moduleptr->info->name, name );
		return NS_SUCCESS;
	}
	return NS_FAILURE;
}
예제 #5
0
/*
 * Driver initialisation at IOC startup (ecAsynInit)
 *
 * path - location of Unix Domain Socket, must match the scanner's
 * max_message - maximum size of messages between scanner and ioc
 *               This must be able to accommodate the configuration
 *               of the chain that is transferred from the scanner to
 *               the ioc.
 */
static void makePorts(char * path, int max_message)
{
    ENGINE_USER * usr = (ENGINE_USER *)callocMustSucceed
        (1, sizeof(ENGINE_USER), "can't allocate socket engine private data");
    ellInit(&usr->ports);
    usr->master = new ecMaster((char *)"MASTER0");
    ellAdd(&usr->ports, &usr->master->node);
    usr->config_ready = rtMessageQueueCreate(1, sizeof(int));
    // TODO - no assert for runtime errors, so what should we use to throw?
    assert(usr->config_ready != NULL);
    usr->config = (EC_CONFIG *)callocMustSucceed
        (1, sizeof(EC_CONFIG), "can't allocate chain config lists");
    usr->writeq = rtMessageQueueCreate(1, max_message);
    assert(usr->writeq != NULL);
    ENGINE * engine = new_engine(max_message);
    engine->path = strdup(path);
    engine->connect = client_connect;
    engine->on_connect = receive_config_on_connect;
    engine->send_message = ioc_send;
    engine->receive_message = ioc_receive;
    engine->usr = usr;
    engine_start(engine);

    new_timer(1000000000, usr->writeq, 0, MSG_HEARTBEAT);

    int ack;
    rtMessageQueueReceive(usr->config_ready, &ack, sizeof(int));

}
예제 #6
0
파일: qapi_time.c 프로젝트: DiaosiDev/qnode
static int
qlsleep(lua_State *state) {
  int         second;
  qactor_t   *actor;
  qengine_t  *engine;
  qid_t       id;
  qltimer_t  *timer;

  second = (int)lua_tonumber(state, 1);
  if (second <= 0) {
    lua_pushnil(state);
    lua_pushliteral(state, "wrong param");
    return 2;
  }

  timer = new_timer(NULL, NULL, NULL);
  if (timer == NULL) {
    lua_pushnil(state);
    lua_pushliteral(state, "create timer error");
    return 2;
  }

  actor = qlua_get_actor(state);
  engine = qactor_get_engine(actor->aid);
  id = qtimer_add(engine, second * 1000, timer_handler,
                  free_timer, 0, timer);
  timer->state = state;
  timer->id = id;
  timer->engine = engine;
  timer->actor = actor;
  qdict_set_numdata(actor->timers, id, timer, engine_free_timer);

  return lua_yield(state, 0);
}
/**
 * Support repeated key presses for a platforms with no own support for it.
 *
 * One of the possible implementations is timer-based generation of MIDP
 * events for a keys pressed and not released for a certain time interval.
 *
 * @param midpKeyCode MIDP keycode of the pressed/released key
 * @param isPressed true if the key is pressed, false if released
 */
void handle_repeated_key_port(int midpKeyCode, jboolean isPressed) {
    if (isPressed) {
        jlong current_time = JVM_JavaMilliSeconds();
        new_timer(current_time + REPEAT_TIMEOUT,
            (void*)midpKeyCode, handle_repeat_key_timer_alarm);
    } else {
        delete_timer_by_userdata((void*)midpKeyCode);
    }
}
예제 #8
0
/**
 * etchmbox_set_duration()       
 */
int etchmbox_set_duration(etch_plainmailbox* thisx, const int ms)
{
    thisx->is_alarm_set = TRUE; /* todo implement proper alarm manager */
    thisx->lifetimer = new_timer(ms, thisx, etchmbox_alarm_wakeup);

    if (thisx->lifetimer)
        thisx->lifetimer->start(thisx->lifetimer);

    return NULL != thisx->lifetimer;
}
예제 #9
0
/* returns 1 if link comes up */
int init_phy (void)
{
    int addr;
    int bmcr;
    int stat;
    int phy_id;
    int link_up = 1;
    time_t* link_timer;

    link_timer = new_timer();

    /* Bring PHY out of reset */
    phy_rst(1);  /* reset is active low */

    /* Discover phy addr by searching addrs in order {1,0,2,..., 31} */
    for(addr = 0; addr < 32; addr++) {
            phy_id = (addr == 0) ? 1 : (addr == 1) ? 0 : addr;
            bmcr = mdio_read(phy_id, MII_BMCR);  /* Basic Mode Control Register */
            stat = mdio_read(phy_id, MII_BMSR);
            stat = mdio_read(phy_id, MII_BMSR);
            if(!((bmcr == 0xFFFF) || ((stat == 0) && (bmcr == 0))))
                break;
    }
    /* Failed to find a PHY on the md bus */
    if (addr == 32)
        return 0;

    /* Reset PHY */
    bmcr = mdio_read(phy_id, MII_BMCR);
    mdio_write(phy_id, MII_BMCR, bmcr | BMCR_RESET);

    /* Advertise that PHY is NOT B1000-T capable */
    /* Set bits 9.8, 9.9 to 0 */
    bmcr = mdio_read(phy_id, MII_CTRL1000);
    mdio_write(phy_id, MII_CTRL1000, bmcr & 0xfcff );

    /* Restart autoneg */
    bmcr = mdio_read(phy_id, MII_BMCR);
    mdio_write(phy_id, MII_BMCR, bmcr | BMCR_ANRESTART);

    /* Wait for link up */
    /* Print PHY status MII_BMSR = Basic Mode Status Register*/
    /* allow a few seconds for the link to come up before giving up */
    set_timer(link_timer, 5000);

    while (!((stat = mdio_read(phy_id, MII_BMSR)) & BMSR_LSTATUS)) {
        if (timer_expired(link_timer)) {
            link_up = 0;
            break;
            }
        }

    return link_up;
}
예제 #10
0
int
new_ptimer( timer_func_t *handler, void *usr, int auto_resume )
{
	mtimer_t *t;
	int id=0;
	
	LOCK;
	if( (t=new_timer(handler, usr, TF_PERIODIC | (auto_resume? TF_AUTORESUME:0))) ) {
		id = t->id;
		t->next = ts.inactive;
		ts.inactive = t;
	}
	UNLOCK;
	return id;
}
예제 #11
0
static int
abs_timer( uint tbu, uint tbl, timer_func_t *handler, void *usr )
{
	mtimer_t *t;
	int id=0;

	LOCK;
	if( (t=new_timer(handler, usr, 0)) ) {
		id = t->id;
		t->tbu = tbu;
		t->tbl = tbl;
		insert_timer( t );
	}
	UNLOCK;
	return id;
}
예제 #12
0
파일: timer.c 프로젝트: carriercomm/epic5-1
/*
 * clone_timer: Create a copy of an existing timer, suitable for rescheduling
 */
static Timer *clone_timer (Timer *otimer)
{
	Timer *ntimer = new_timer();

	strlcpy(ntimer->ref, otimer->ref, sizeof ntimer->ref);
	ntimer->time = otimer->time;
	if ((ntimer->callback = otimer->callback))
		ntimer->callback_data = otimer->callback_data;
	else
		ntimer->command = malloc_strdup(otimer->command);
	ntimer->subargs = malloc_strdup(otimer->subargs);
	ntimer->prev = NULL;
	ntimer->next = NULL;
	ntimer->events = otimer->events;
	ntimer->interval = otimer->interval;
	ntimer->server = otimer->server;
	ntimer->window = otimer->window;
	return ntimer;
}
예제 #13
0
파일: timer.c 프로젝트: tcava/bx2
/*
 * clone_timer: Create a copy of an existing timer, suitable for rescheduling
 */
static Timer *clone_timer (Timer *otimer)
{
	Timer *ntimer = new_timer();

	malloc_strcpy(&ntimer->ref, otimer->ref);
	ntimer->time = otimer->time;
	if ((ntimer->callback = otimer->callback))
		ntimer->callback_data = otimer->callback_data;
	else
		ntimer->command = malloc_strdup(otimer->command);
	ntimer->subargs = malloc_strdup(otimer->subargs);
	ntimer->prev = NULL;
	ntimer->next = NULL;
	ntimer->events = otimer->events;
	ntimer->interval = otimer->interval;
	ntimer->domain = otimer->domain;
	ntimer->domref = otimer->domref;
	ntimer->cancelable = otimer->cancelable;
	ntimer->fires = otimer->fires;
	return ntimer;
}
예제 #14
0
shared_ptr<Timer> VariableRegistry::createTimer(VariableProperties *props) {
	VariableProperties *props_copy;
	
	if(props != NULL){
		props_copy = new VariableProperties(*props);	
	} else {
		props_copy = NULL;
	}
	
	shared_ptr<Timer> new_timer(new Timer(props_copy));
	
//	int codec_code = master_variable_list.addReference(new_timer);
	
	std::string tag = new_timer->getVariableName();
	if(!tag.empty()){
        master_variable_dictionary[tag] = new_timer;
	}
	
	new_timer->setCodecCode(-1);
	new_timer->setEventTarget(boost::static_pointer_cast<EventReceiver>(event_buffer));	
	
	return new_timer;
}
예제 #15
0
void SessionManager::on_ccf_response (bool accepted, uint32_t interim_interval, std::string session_id, int rc, Message* msg)
{
    // Log this here, as it's the first time we have access to the
    // session ID for a new session
    SAS::Event new_rf(msg->trail, SASEvent::NEW_RF_SESSION, 0);
    new_rf.add_var_param(session_id);
    SAS::report_event(new_rf);

    if (accepted)
    {
        if (msg->record_type.isInterim() &&
                (!msg->timer_interim) &&
                (msg->session_refresh_time > interim_interval))

        {
            // Interim message generated by Sprout, so update a timer to generate recurring INTERIMs
            std::string timer_id = msg->timer_id;

            send_chronos_update(timer_id,
                                interim_interval,
                                msg->session_refresh_time,
                                "/call-id/"+msg->call_id+"?timer-interim=true",
                                create_opaque_data(msg),
                                msg->trail);

            SAS::Event updated_timer(msg->trail, SASEvent::INTERIM_TIMER_RENEWED, 0);
            updated_timer.add_static_param(interim_interval);
            SAS::report_event(updated_timer);

            // Update the timer_id if it has changed
            if (timer_id != msg->timer_id)
            {
                update_timer_id(msg, timer_id);
            }
        }
        else if (msg->record_type.isStart())
        {
            // New message from Sprout - create a new timer then insert the session into the store

            // Set the timer id initially to NO_TIMER - this isn't included in the path of the POST
            std::string timer_id = NO_TIMER;

            if (msg->session_refresh_time > interim_interval)
            {
                HTTPCode status = _timer_conn->send_post(timer_id,  // Chronos returns a timer ID which is filled in to this parameter
                                  interim_interval, // interval
                                  msg->session_refresh_time, // repeat-for
                                  "/call-id/"+msg->call_id+"?timer-interim=true",
                                  create_opaque_data(msg),
                                  msg->trail);

                if (status != HTTP_OK)
                {
                    // LCOV_EXCL_START
                    LOG_ERROR("Chronos POST failed");
                    // LCOV_EXCL_STOP
                }
            };

            SAS::Event new_timer(msg->trail, SASEvent::INTERIM_TIMER_CREATED, 0);
            new_timer.add_static_param(interim_interval);
            SAS::report_event(new_timer);

            LOG_INFO("Writing session to store");
            SessionStore::Session* sess = new SessionStore::Session();
            sess->session_id = session_id;
            sess->interim_interval = interim_interval;

            sess->timer_id = timer_id;
            msg->timer_id = timer_id;

            sess->ccf = msg->ccfs;
            sess->acct_record_number = msg->accounting_record_number;
            sess->session_refresh_time = msg->session_refresh_time;

            // Do this unconditionally - if it fails, this processing has already been done elsewhere
            _store->set_session_data(msg->call_id,
                                     msg->role,
                                     msg->function,
                                     sess,
                                     msg->trail);
            delete sess;
        }

    }
    else
    {
        LOG_WARNING("Session for %s received error from CDF", msg->call_id.c_str());
        if (msg->record_type.isInterim())
        {
            if (rc == 5002)
            {
                // 5002 means the CDF has no record of this session. It's pointless to send any
                // more messages - delete the session from the store.
                LOG_INFO("Session for %s received 5002 error from CDF, deleting", msg->call_id.c_str());
                _store->delete_session_data(msg->call_id,
                                            msg->role,
                                            msg->function,
                                            msg->trail);
            }
            else if (!msg->timer_interim)
            {
                // Interim failed, but the CDF probably still knows about the session,
                // so keep sending them. We don't do this for START - if a START fails we don't record the session.

                // In error conditions our CCF might not have returned an interim interval,
                // so use the one from the store.
                if (interim_interval == 0)
                {
                    interim_interval = msg->interim_interval;
                }

                if (msg->session_refresh_time > interim_interval)
                {
                    LOG_INFO("Received INTERIM for session %s, updating timer using timer ID %s", msg->call_id.c_str(), msg->timer_id.c_str());

                    std::string timer_id = msg->timer_id;
                    send_chronos_update(timer_id,
                                        interim_interval,
                                        msg->session_refresh_time,
                                        "/call-id/"+msg->call_id+"?timer-interim=true",
                                        create_opaque_data(msg),
                                        msg->trail);

                    // Update the timer_id if it has changed
                    if (timer_id != msg->timer_id)
                    {
                        update_timer_id(msg, timer_id);
                    }
                }
            }
        }
    }

    // Everything is finished and we're the last holder of the Message object - delete it.
    delete msg;
}
예제 #16
0
파일: timer.c 프로젝트: tcava/bx2
/*
 * You call this to register a timer callback.
 *
 * The arguments:
 *  update:      This should be 1 if we're updating the specified refnum
 *  refnum_want: The refnum requested.  This should only be sepcified
 *		 by the user, functions wanting callbacks should specify
 *		 the empty string, which means "dont care".
 * The rest of the arguments are dependant upon the value of "callback"
 *	-- if "callback" is NULL then:
 *  callback:	 NULL
 *  what:	 some ircII commands to run when the timer goes off
 *  subargs:	 what to use to expand $0's, etc in the 'what' variable.
 *
 *	-- if "callback" is non-NULL then:
 *  callback:	 function to call when timer goes off
 *  what:	 argument to pass to "callback" function.  Should be some
 *		 non-auto storage, perhaps a struct or a malloced char *
 *		 array.  The caller is responsible for disposing of this
 *		 area when it is called, since the timer mechanism does not
 *		 know anything of the nature of the argument.
 * subargs:	 should be NULL, its ignored anyhow.
 */
char *add_timer (int update, const char *refnum_want, double interval, long events, int (callback) (void *), void *commands, const char *subargs, TimerDomain domain, int domref, int cancelable)
{
	Timer	*ntimer, *otimer = NULL;
	char *	refnum_got = NULL;
	Timeval right_now;
	char *	retval;

	/* XXX Eh, maybe it's a hack to check this here. */
	if (interval < 0.01 && events == -1)
	{
		say("You can't infinitely repeat a timer that runs more "
			"than 100 times a second.");
		return NULL;
	}

	right_now = get_time(NULL);

	if (update)
	{
	    if (!(otimer = get_timer(refnum_want)))
		update = 0;		/* Ok so we're not updating! */
	}

	if (update)
	{
		unlink_timer(otimer);
		ntimer = clone_timer(otimer);
		delete_timer(otimer);

		if (interval != -1)
		{
			ntimer->interval = double_to_timeval(interval);
			ntimer->time = time_add(right_now, ntimer->interval);
		}
		if (events != -2)
			ntimer->events = events;

		if (callback)
		{
			/* Delete the previous timer, if necessary */
			if (ntimer->command)
				new_free(&ntimer->command);
			if (ntimer->subargs)
				new_free(&ntimer->subargs);
			ntimer->callback = callback;
			/* Unfortunately, command is "sometimes const". */
			ntimer->callback_data = commands;
			ntimer->subargs = NULL;
		}
		else
		{
			if (ntimer->callback)
				ntimer->callback = NULL;
			malloc_strcpy(&ntimer->command, (const char *)commands);
			malloc_strcpy(&ntimer->subargs, subargs);
		}

		if (domref != -1)
			ntimer->domref = domref;
	}
	else
	{
		if (create_timer_ref(refnum_want, &refnum_got) == -1)
		{
			say("TIMER: Refnum '%s' already exists", refnum_want);
			return NULL;
		}

		ntimer = new_timer();
		ntimer->ref = refnum_got;
		ntimer->interval = double_to_timeval(interval);
		ntimer->time = time_add(right_now, ntimer->interval);
		ntimer->events = events;
		ntimer->callback = callback;
		/* Unfortunately, command is "sometimes const". */
		if (callback)
			ntimer->callback_data = commands;
		else
			malloc_strcpy(&ntimer->command, (const char *)commands);
		malloc_strcpy(&ntimer->subargs, subargs);
		ntimer->domain = domain;
		ntimer->domref = domref;
		ntimer->cancelable = cancelable;
		ntimer->fires = 0;
	}

	schedule_timer(ntimer);
	retval = ntimer->ref;
	return retval;		/* Eliminates a specious warning from gcc */
}
예제 #17
0
파일: core.c 프로젝트: shenzhe/bsp
// Start main loop
int core_loop(void (* server_event)(BSP_CALLBACK *))
{
    BSP_THREAD *t = get_thread(MAIN_THREAD);
    if (!t)
    {
        trigger_exit(BSP_RTN_FATAL, "Main thread lost!");
    }

    // Servers
    BSP_VALUE *val = object_get_hash_str(runtime_settings, "servers");
    BSP_OBJECT *vobj = value_get_object(val);
    BSP_STRING *vstr = NULL;
    if (vobj && OBJECT_TYPE_ARRAY == vobj->type)
    {
        struct bsp_conf_server_t srv;
        BSP_OBJECT *vsrv = NULL;
        size_t varr_size = object_size(vobj), i;
        reset_object(vobj);
        for (i = 0; i < varr_size; i ++)
        {
            val = object_get_array(vobj, i);
            vsrv = value_get_object(val);
            if (vsrv && OBJECT_TYPE_HASH == vsrv->type)
            {
                // Default value
                memset(&srv, 0, sizeof(struct bsp_conf_server_t));
                srv.server_inet = INET_TYPE_ANY;
                srv.server_sock = SOCK_TYPE_ANY;
                srv.def_client_type = CLIENT_TYPE_DATA;
                srv.def_data_type = DATA_TYPE_PACKET;
                val = object_get_hash_str(vsrv, "name");
                vstr = value_get_string(val);
                srv.server_name = bsp_strndup(STR_STR(vstr), STR_LEN(vstr));
                val = object_get_hash_str(vsrv, "inet");
                vstr = value_get_string(val);
                if (vstr)
                {
                    if (0 == strncasecmp(STR_STR(vstr), "ipv6", 4))
                    {
                        srv.server_inet = INET_TYPE_IPV6;
                    }
                    else if (0 == strncasecmp(STR_STR(vstr), "ipv4", 4))
                    {
                        srv.server_inet = INET_TYPE_IPV4;
                    }
                    else if (0 == strncasecmp(STR_STR(vstr), "local", 5))
                    {
                        srv.server_inet = INET_TYPE_LOCAL;
                    }
                }
                val = object_get_hash_str(vsrv, "sock");
                vstr = value_get_string(val);
                if (vstr)
                {
                    if (0 == strncasecmp(STR_STR(vstr), "tcp", 3))
                    {
                        srv.server_sock = SOCK_TYPE_TCP;
                    }
                    else if (0 == strncasecmp(STR_STR(vstr), "udp", 3))
                    {
                        srv.server_sock = SOCK_TYPE_UDP;
                    }
                }
                val = object_get_hash_str(vsrv, "addr");
                vstr = value_get_string(val);
                srv.server_addr = bsp_strndup(STR_STR(vstr), STR_LEN(vstr));
                val = object_get_hash_str(vsrv, "port");
                srv.server_port = (int) value_get_int(val);
                val = object_get_hash_str(vsrv, "heartbeat_check");
                srv.heartbeat_check = (int) value_get_int(val);
                val = object_get_hash_str(vsrv, "debug_input");
                srv.debug_hex_input = value_get_boolean(val);
                val = object_get_hash_str(vsrv, "debug_output");
                srv.debug_hex_input = value_get_boolean(val);
                val = object_get_hash_str(vsrv, "max_clients");
                srv.max_clients = (int) value_get_int(val);
                val = object_get_hash_str(vsrv, "max_packet_length");
                srv.max_packet_length = (size_t) value_get_int(val);
                val = object_get_hash_str(vsrv, "websocket");
                if (value_get_boolean(val))
                {
                    srv.def_client_type = CLIENT_TYPE_WEBSOCKET_HANDSHAKE;
                }
                val = object_get_hash_str(vsrv, "data_type");
                vstr = value_get_string(val);
                if (vstr && 0 == strncasecmp(STR_STR(vstr), "stream", 6))
                {
                    srv.def_data_type = DATA_TYPE_STREAM;
                }

                // Add server
                BSP_SERVER *s;
                int srv_fds[MAX_SERVER_PER_CREATION], srv_ct, fd_type;
                int nfds = MAX_SERVER_PER_CREATION;
                nfds = new_server(srv.server_addr, srv.server_port, srv.server_inet, srv.server_sock, srv_fds, &nfds);
                for (srv_ct = 0; srv_ct < nfds; srv_ct ++)
                {
                    fd_type = FD_TYPE_SOCKET_SERVER;
                    s = (BSP_SERVER *) get_fd(srv_fds[srv_ct], &fd_type);
                    if (s)
                    {
                        s->name = srv.server_name;
                        s->heartbeat_check = srv.heartbeat_check;
                        s->def_client_type = srv.def_client_type;
                        s->def_data_type = srv.def_data_type;
                        s->max_packet_length = srv.max_packet_length;
                        s->max_clients = srv.max_clients;
                        s->debug_hex_input = srv.debug_hex_input;
                        s->debug_hex_output = srv.debug_hex_output;

                        add_server(s);
                    }
                    else
                    {
                        bsp_free(srv.server_name);
                    }
                }
            }
        }
    }

    // Server event
    if (server_event)
    {
        core_settings.on_srv_events = server_event;
    }

    // Create 1 Hz clock
    BSP_TIMER *tmr = new_timer(BASE_CLOCK_SEC, BASE_CLOCK_USEC, -1);
    tmr->on_timer = base_timer;
    core_settings.main_timer = tmr;
    dispatch_to_thread(tmr->fd, MAIN_THREAD);
    start_timer(tmr);

    // Let's go
    load_bootstrap();
    trace_msg(TRACE_LEVEL_CORE, "Core   : Main thread loop started");
    thread_process((void *) t);

    return BSP_RTN_SUCCESS;
}
예제 #18
0
파일: timer.c 프로젝트: ailin-nemui/epic5
/*
 * You call this to register a timer callback.
 *
 * The arguments:
 *  update:      This should be 1 if we're updating the specified refnum
 *  refnum_want: The refnum requested.  
 *		 (1) User-supplied for /TIMER timers
 *		 (2) the empty string for system timers ("dont care")
 *  interval:	 How long until the timer should fire; 
 *		 (1) for repeating timers (events != 1), the timer will 
 *		     fire with this interval.
 *		 (2) for "snap" timers, the first fire will be the next
 *		     time time() % interval == 0.
 *  events:	 The number of times this event should fire.  
 *		 (1) The value -1 means "repeat forever"
 *		 (2) Timers automatically delete after they fire the
 *		     requested number of times.
 *
 * Scenario 1: You want to run ircII commands (/TIMER timers)
 * | callback:	 NULL
 * | commands:	 some ircII commands to run when the timer goes off
 * | subargs:	 what to use to expand $0's, etc in the 'what' variable.
 *
 * Scenario 2: You want to call an internal function (system timers)
 * | callback:	 function to call when timer goes off
 * | commands:	 argument to pass to "callback" function.  Should be some
 * |		 non-auto storage, perhaps a struct or a malloced char *
 * |		 array.  The caller is responsible for disposing of this
 * |		 area when it is called, since the timer mechanism does not
 * |		 know anything of the nature of the argument.
 * | subargs:	 should be NULL, its ignored anyhow.
 *
 *  domain:	What the TIMER should bind to:
 *		(a) SERVER_TIMER  - 'domref' refers to a server refnum.
 *			Each time this timer runs, set from_server to 'domref'
 *			and set the current window to whatever 'domref's 
 *			current window is at that time.
 *		(b) WINDOW_TIME - 'domref' refers to a window refnum.
 *			Each time this timer runs, set current_window to
 *			'domref' and set the current server to whatever 
 *			'domref's server is at that time.
 *		(c) GENERAL_TIMER - 'domref' is ignored.  
 *			Do not save or restore from_server or current_window: 
 *			run in whatever the context is when it goes off.
 *  domref:	Either a server refnum, window refnum, or -1 (see 'domain')
 *  cancelable:	A "Cancelable" timer will not fire if its context cannot be
 *		restored (ie, the server it is bound to is disconnected or
 *		deleted; or the window it is bound to is deleted).  A normal
 *		(non-cancelable) timer will turn into a GENERAL_TIMER if its
 *		context cannot be restored.
 *  snap:	A "snap" timer runs every time (time() % interval == 0).
 *		This is useful for things that (eg) run at the top of every 
 *		minute (60), hour (3600), or day (86400)
 */
char *add_timer (int update, const char *refnum_want, double interval, long events, int (callback) (void *), void *commands, const char *subargs, TimerDomain domain, int domref, int cancelable, int snap)
{
	Timer	*ntimer, *otimer = NULL;
	char *	refnum_got = NULL;
	Timeval right_now;
	char *	retval;

	right_now = get_time(NULL);

	/*
	 * We do this first, because if 'interval' is invalid, we don't
	 * want to do the expensive clone/create/delete operation.
 	 * It is ineligant to check for this error here.
	 */
	if (update == 1 && interval == -1)	/* Not changing the interval */
		(void) 0;	/* XXX sigh */
	else if (interval < 0.01 && events == -1)
	{
		say("You can't infinitely repeat a timer that runs more "
			"than 100 times a second.");
		return NULL;
	}

	/* 
	 * If we say we're updating; but the timer does not exist, 
	 * then we're not updating. ;-)
	 */
	if (update)
	{
	    if (!(otimer = get_timer(refnum_want)))
		update = 0;		/* Ok so we're not updating! */
	}

	/*
	 * Arrange for an appropriate Timer to be in 'ntimer'.
	 */
	if (update)
	{
		unlink_timer(otimer);
		ntimer = clone_timer(otimer);
		delete_timer(otimer);
	}
	else
	{
		if (create_timer_ref(refnum_want, &refnum_got) == -1)
		{
			say("TIMER: Refnum '%s' already exists", refnum_want);
			return NULL;
		}

		ntimer = new_timer();
		ntimer->ref = refnum_got;
	}

	/* Update the interval */
	if (update == 1 && interval == -1)
		(void) 0;	/* XXX sigh - not updating interval */
	else
	{
		ntimer->interval = double_to_timeval(interval);
		if (snap)
		{
			double x = time_to_next_interval(interval);
			ntimer->time = time_add(right_now, double_to_timeval(x));
		}
		else
			ntimer->time = time_add(right_now, ntimer->interval);
	}

	/* Update the repeat events */
	if (update == 1 && events == -2)
		(void) 0;	/* XXX sigh - not updating events */
	else
		ntimer->events = events;


	/* Update the callback */
	if (callback)
	{
		/* Delete the previous timer, if necessary */
		if (ntimer->command)
			new_free(&ntimer->command);
		if (ntimer->subargs)
			new_free(&ntimer->subargs);
		ntimer->callback = callback;

		/* Unfortunately, command is "sometimes const". */
		ntimer->callback_data = commands;
		ntimer->subargs = NULL;
	}
	else
	{
		ntimer->callback = NULL;
		malloc_strcpy(&ntimer->command, (const char *)commands);
		malloc_strcpy(&ntimer->subargs, subargs);
	}

	/* Update the domain refnum */
	ntimer->domain = domain;
	if (update == 1 && domref == -1)
		(void) 0;	/* XXX sigh - not updating domref */
	else
		ntimer->domref = domref;

	/* Update the cancelable */
	if (update == 1 && cancelable == -1)
		(void) 0;	/* XXX sigh - not updating cancelable */
	else
		ntimer->cancelable = cancelable;


	/* Schedule up the new/updated timer! */
	schedule_timer(ntimer);
	retval = ntimer->ref;
	return retval;		/* Eliminates a specious warning from gcc */
}
예제 #19
0
파일: qapi_time.c 프로젝트: DiaosiDev/qnode
static int
qltimer_add(lua_State *state) {
  int         timeout, cycle;
  const char *mod, *func;
  qactor_t   *actor;
  qdict_t    *args;
  qengine_t  *engine;
  qid_t       id;
  qltimer_t  *timer;

  timeout = (int)lua_tonumber(state, 1);
  cycle   = (int)lua_tonumber(state, 2);
  mod     = lua_tostring(state, 3);
  func    = lua_tostring(state, 4);
  if (timeout < 0 || cycle < 0 || mod == NULL || func == NULL) {
    lua_pushnil(state);
    lua_pushliteral(state, "wrong param");
    return 2;
  }

  /* if there exist mod.fun? */
  lua_getglobal(state, mod);
  if (!lua_istable(state, -1)) {
    lua_pushnil(state);
    lua_pushfstring(state, "mod %s not exist", mod);
    return 2;
  }

  lua_getfield(state, -1, func);
  if (!lua_isfunction(state, -1)) {
    lua_pushnil(state);
    lua_pushfstring(state, "%s.%s is not lua function", mod, func);
    return 2;
  }
  /* pop the result */
  lua_pop(state, -1);

  args = qdict_new(5);
  if (args == NULL) {
    lua_pushnil(state);
    lua_pushliteral(state, "create args table error");
    return 2;
  }

  if (qlua_copy_table(state, 4, args) != QOK) {
    qdict_free(args);
    lua_pushnil(state);
    lua_pushliteral(state, "copy args table error");
    return 2;
  }

  timer = new_timer(args, mod, func);
  if (timer == NULL) {
    qdict_free(args);
    lua_pushnil(state);
    lua_pushliteral(state, "create timer error");
    return 2;
  }

  actor = qlua_get_actor(state);
  engine = qactor_get_engine(actor->aid);
  id = qtimer_add(engine, timeout, timer_handler,
                  free_timer, cycle, timer);
  timer->state = state;
  timer->id = id;
  timer->engine = engine;
  qdict_set_numdata(actor->timers, id, timer, engine_free_timer);

  lua_pushnumber(state, id);

  return 1;
}
예제 #20
0
int main(void)
{
    int mode = 0;

    /* enable interrupts (on the CPU) */
    init_interrupts();

    /* Initialize peripherals */
    display_init( RESOLUTION_320x240, DEPTH_16_BPP, 2, GAMMA_NONE, ANTIALIAS_RESAMPLE );
    dfs_init( DFS_DEFAULT_LOCATION );
    rdp_init();
    controller_init();
    timer_init();

    /* Read in single sprite */
    int fp = dfs_open("/mudkip.sprite");
    sprite_t *mudkip = malloc( dfs_size( fp ) );
    dfs_read( mudkip, 1, dfs_size( fp ), fp );
    dfs_close( fp );
    
    fp = dfs_open("/earthbound.sprite");
    sprite_t *earthbound = malloc( dfs_size( fp ) );
    dfs_read( earthbound, 1, dfs_size( fp ), fp );
    dfs_close( fp );

    fp = dfs_open("/plane.sprite");
    sprite_t *plane = malloc( dfs_size( fp ) );
    dfs_read( plane, 1, dfs_size( fp ), fp );
    dfs_close( fp );

    /* Kick off animation update timer to fire thirty times a second */
    new_timer(TIMER_TICKS(1000000 / 30), TF_CONTINUOUS, update_counter);

    /* Main loop test */
    while(1) 
    {
        static display_context_t disp = 0;

        /* Grab a render buffer */
        while( !(disp = display_lock()) );
       
        /*Fill the screen */
        graphics_fill_screen( disp, 0xFFFFFFFF );

        /* Set the text output color */
        graphics_set_color( 0x0, 0xFFFFFFFF );
    
        switch( mode )
        {
            case 0:
                /* Software spritemap test */
                graphics_draw_text( disp, 20, 20, "Software spritemap test" );

                /* Display a stationary sprite of adequate size to fit in TMEM */
                graphics_draw_sprite_trans( disp, 20, 50, plane );

                /* Display a stationary sprite to demonstrate backwards compatibility */
                graphics_draw_sprite_trans( disp, 50, 50, mudkip );

                /* Display walking NESS animation */
                graphics_draw_sprite_stride( disp, 20, 100, earthbound, ((animcounter / 15) & 1) ? 1: 0 );

                /* Display rotating NESS animation */
                graphics_draw_sprite_stride( disp, 50, 100, earthbound, ((animcounter / 8) & 0x7) * 2 );

                break;
            case 1:
            {
                /* Hardware spritemap test */
                graphics_draw_text( disp, 20, 20, "Hardware spritemap test" );

                /* Assure RDP is ready for new commands */
                rdp_sync( SYNC_PIPE );

                /* Remove any clipping windows */
                rdp_set_default_clipping();

                /* Enable sprite display instead of solid color fill */
                rdp_enable_texture_copy();

                /* Attach RDP to display */
                rdp_attach_display( disp );
                    
                /* Ensure the RDP is ready to receive sprites */
                rdp_sync( SYNC_PIPE );

                /* Load the sprite into texture slot 0, at the beginning of memory, without mirroring */
                rdp_load_texture( 0, 0, MIRROR_DISABLED, plane );
                
                /* Display a stationary sprite of adequate size to fit in TMEM */
                rdp_draw_sprite( 0, 20, 50 );

                /* Since the RDP is very very limited in texture memory, we will use the spritemap feature to display
                   all four pieces of this sprite individually in order to use the RDP at all */
                for( int i = 0; i < 4; i++ )
                {
                    /* Ensure the RDP is ready to receive sprites */
                    rdp_sync( SYNC_PIPE );

                    /* Load the sprite into texture slot 0, at the beginning of memory, without mirroring */
                    rdp_load_texture_stride( 0, 0, MIRROR_DISABLED, mudkip, i );
                
                    /* Display a stationary sprite to demonstrate backwards compatibility */
                    rdp_draw_sprite( 0, 50 + (20 * (i % 2)), 50 + (20 * (i / 2)) );
                }

                /* Ensure the RDP is ready to receive sprites */
                rdp_sync( SYNC_PIPE );

                /* Load the sprite into texture slot 0, at the beginning of memory, without mirroring */
                rdp_load_texture_stride( 0, 0, MIRROR_DISABLED, earthbound, ((animcounter / 15) & 1) ? 1: 0 );
                
                /* Display walking NESS animation */
                rdp_draw_sprite( 0, 20, 100 );

                /* Ensure the RDP is ready to receive sprites */
                rdp_sync( SYNC_PIPE );

                /* Load the sprite into texture slot 0, at the beginning of memory, without mirroring */
                rdp_load_texture_stride( 0, 0, MIRROR_DISABLED, earthbound, ((animcounter / 8) & 0x7) * 2 );
                
                /* Display rotating NESS animation */
                rdp_draw_sprite( 0, 50, 100 );

                /* Inform the RDP we are finished drawing and that any pending operations should be flushed */
                rdp_detach_display();

                break;
            }
        }

        /* Force backbuffer flip */
        display_show(disp);

        /* Do we need to switch video displays? */
        controller_scan();
        struct controller_data keys = get_keys_down();

        if( keys.c[0].A )
        {
            /* Lazy switching */
            mode = 1 - mode;
        }
    }
}