Example #1
0
void InputService::processQueue(EventQueue& queue)
{
	// Send events which are piled on queue so far
	size_t numEvents = queue.size(); // TODO: Do we have to limit by numEvents?

	while (!queue.empty())
	{
		EventEntry& e = queue.front();

		EventId id = e.eventID;
		Ref<InputEvent> evt = e.event;
		queue.pop_front();

		if (evt && evt->isConsumed())
			continue;

		EventChannel* channel = e.channel;
		if (channel)
		{
			// If channel specified on post : Send to that channel
			channel->send(id, evt);
			continue;
		}

		// When channel not specified: broadcast upward from source channel

		if (evt == NULL)
			continue; // Can't handle event with no channel specified.

		// 1. Broadcast to source channel
		Ref<InputSource> source = evt->getSource();
		if (source && source->hasChannel())
		{
			source->channel()->send(id, evt);
			if (evt->isConsumed() || !evt->isUplinking())
				continue;
		}

		// 2. Broadcast to device channel
		Weak<InputDevice> device = evt->getDevice();
		if (device && device->hasChannel())
		{
			device->channel()->send(id, evt);
			if (evt->isConsumed() || !evt->isUplinking())
				continue;
		}

		// 3. Broadcast to user channel
		Ref<InputUser> user = evt->getUser();

		if (user && user->hasChannel())
		{
			user->channel()->send(id, evt);
			if (evt->isConsumed() || !evt->isUplinking())
				continue;
		}

		// TODO: 4. Broadcast to service channel?
	}
}
Example #2
0
TEST(A1UnitTestDemos, Interaction) {
  StopWatch* watch = new StopWatch(XApplication::GetInstance()->GetEventQueue(), Rectangle(0, 0, 200, 75));
  EXPECT_FALSE(watch == NULL);

  // Create a synthetic mouse event to test whether watch responds to it
  // or not. Note that this assumes that clicking in the location
  // specified amounts to pressing the start/stop button. Your actual
  // interaction will likely be different, making this test useless.
  // However, this should provide a template for how to do unit tests
  // for interaction.
  EXPECT_FALSE(watch->GetParentWindow() == NULL);
  MouseEvent* e = new MouseEvent(watch->GetParentWindow(), MouseEvent::mouseUp, Point(10, 10));

  EventQueue* queue = XApplication::GetInstance()->GetEventQueue();
  EXPECT_FALSE(queue == NULL);

  EXPECT_FALSE(watch->IsRunning());
  queue->AddEventToQueue(e);
  unsigned int max_num_tries_to_flush_queue = 10;
  while (max_num_tries_to_flush_queue-- > 0
         && queue->GetNumEventsInQueue() > 0
         && !watch->IsRunning())
    {
      queue->ProcessNextEvent();
    }
  EXPECT_TRUE(watch->IsRunning());

  queue->ClearEventQueue();
  delete watch;
  // We do not need to delete the mouse event that we created, because
  // it will be deleted automatically by the EventQueue.
}
    bool authorize(const Service& authService,
                   Identity *providerIdentity,
                   ProviderSession *session,
                   const CorrelationId& cid)
    {
        {
            MutexGuard guard(&g_lock);
            g_authorizationStatus[cid] = WAITING;
        }
        EventQueue tokenEventQueue;
        session->generateToken(CorrelationId(), &tokenEventQueue);
        std::string token;
        Event event = tokenEventQueue.nextEvent();
        if (event.eventType() == Event::TOKEN_STATUS ||
            event.eventType() == Event::REQUEST_STATUS) {
            MessageIterator iter(event);
            while (iter.next()) {
                Message msg = iter.message();
                {
                    MutexGuard guard(&g_lock);
                    msg.print(std::cout);
                }
                if (msg.messageType() == TOKEN_SUCCESS) {
                    token = msg.getElementAsString(TOKEN);
                }
                else if (msg.messageType() == TOKEN_FAILURE) {
                    break;
                }
            }
        }
        if (token.length() == 0) {
            MutexGuard guard(&g_lock);
            std::cout << "Failed to get token" << std::endl;
            return false;
        }

        Request authRequest = authService.createAuthorizationRequest();
        authRequest.set(TOKEN, token.c_str());

        session->sendAuthorizationRequest(
            authRequest,
            providerIdentity,
            cid);

        time_t startTime = time(0);
        const int WAIT_TIME_SECONDS = 10;
        while (true) {
            {
                MutexGuard guard(&g_lock);
                if (WAITING != g_authorizationStatus[cid]) {
                    return AUTHORIZED == g_authorizationStatus[cid];
                }
            }
            time_t endTime = time(0);
            if (endTime - startTime > WAIT_TIME_SECONDS) {
                return false;
            }
            SLEEP(1);
        }
    }
Example #4
0
void testThread(int n, ServiceLocator* aDifferentThreadsLocator) {
    ServiceLocator* loc = ServiceLocator::getDefaultLocator();  
    ServiceLocator* loc2 = ServiceLocator::getDefaultLocator();
    Timer* timer1 = loc->locateTimerService();
    Timer* timer2 = loc2->locateTimerService();
    
    MessageService* mes1 = loc->locateMessageService();
    MessageService* mes2 = loc2->locateMessageService();

    assert(mes1 == mes2);
    mes1->publish("someMessage", StringMap());
    
    MessageService* mes3 = aDifferentThreadsLocator->locateMessageService();
    mes3->publish("aMessage", StringMap());
    
    EventQueue* eq = loc->locateEventService();
    eq->pushTimerEvent(loc->locateTimerService()->getTimeStamp());
    
    assert(loc == loc2);
    assert(loc != aDifferentThreadsLocator);
    assert(loc != NULL);
    assert(aDifferentThreadsLocator != NULL);
    
    assert(timer1 == timer2);
    
    assert(mes1 != NULL);
    assert(mes3 != NULL);
    assert(mes1 != mes3);
}
void
SimpleNbmtr::start(int sk)
{
    EventQueue * q = EventQueue::Instance();
    q->add_event(new ProbeEvent(time(NULL) + probe_interval, this, sk));
    q->add_event(new SaveEvent(time(NULL) + save_interval, this));
}
Example #6
0
int main()
{
	Link link("L1", 10000000, 0.01, 64000);

	Node node1("H1");
	Node node2("H2");
	NetworkManager* nm = NetworkManager::getInstance();

	nm->registerLink(link);
	nm->registerNode(node1);
	nm->registerNode(node2);

	nm->connectLink("L1", "H1", "H2");

	Flow flow("F1", "H1", "H2", 20000000, TCP_RENO_t, 1);
	nm->registerFlow(flow);

	EventQueue* eq = EventQueue::getInstance();
	eq->run();

	Logger * logger = Logger::getInstance();
	delete logger;

	return EXIT_SUCCESS;
}
void GlobalEventQueue::Cycle( ncycle_t steps )
{
    EventQueue *nextEventQueue;
    ncycle_t iterationSteps = 0;

    while( iterationSteps < steps )
    {
        ncycle_t nextEvent = GetNextEvent( &nextEventQueue );

        ncycle_t globalQueueSteps = 0;
        if( nextEvent > currentCycle )
        {
            globalQueueSteps = nextEvent - currentCycle;
        }

        /* Next event occurs after the current number of steps. */
        if( globalQueueSteps > (steps - iterationSteps))
        {
            currentCycle += steps - iterationSteps;
            Sync( );
            break;
        }

        ncycle_t localQueueSteps = nextEventQueue->GetNextEvent( ) - nextEventQueue->GetCurrentCycle( );
        nextEventQueue->Loop( localQueueSteps );

        currentCycle += globalQueueSteps;
        iterationSteps += globalQueueSteps;

        Sync( );
    }
}
Example #8
0
void IDBDatabase::closeConnection() {
  DCHECK(m_closePending);
  DCHECK(m_transactions.isEmpty());

  if (m_backend) {
    m_backend->close();
    m_backend.reset();
  }

  if (m_databaseCallbacks)
    m_databaseCallbacks->detachWebCallbacks();

  if (m_contextStopped || !getExecutionContext())
    return;

  EventQueue* eventQueue = getExecutionContext()->getEventQueue();
  // Remove any pending versionchange events scheduled to fire on this
  // connection. They would have been scheduled by the backend when another
  // connection attempted an upgrade, but the frontend connection is being
  // closed before they could fire.
  for (size_t i = 0; i < m_enqueuedEvents.size(); ++i) {
    bool removed = eventQueue->cancelEvent(m_enqueuedEvents[i].get());
    DCHECK(removed);
  }
}
Example #9
0
void IDBRequest::abort()
{
    ASSERT(!m_requestAborted);
    if (m_contextStopped || !scriptExecutionContext())
        return;
    ASSERT(m_readyState == PENDING || m_readyState == DONE);
    if (m_readyState == DONE)
        return;

    // Enqueued events may be the only reference to this object.
    RefPtr<IDBRequest> self(this);

    EventQueue* eventQueue = scriptExecutionContext()->eventQueue();
    for (size_t i = 0; i < m_enqueuedEvents.size(); ++i) {
        bool removed = eventQueue->cancelEvent(m_enqueuedEvents[i].get());
        ASSERT_UNUSED(removed, removed);
    }
    m_enqueuedEvents.clear();

    m_errorCode = 0;
    m_error.clear();
    m_errorMessage = String();
    m_result.clear();
    onError(IDBDatabaseError::create(IDBDatabaseException::IDB_ABORT_ERR, "The transaction was aborted, so the request cannot be fulfilled."));
    m_requestAborted = true;
}
eVrApiEventStatus SystemActivities_GetNextPendingEvent( EventQueue * queue, char * buffer, unsigned int const bufferSize )
{
	if ( buffer == NULL || bufferSize == 0 ) 
	{
		return VRAPI_EVENT_ERROR_INVALID_BUFFER;
	}
	
	if ( bufferSize < 2 ) 
	{
		buffer[0] = '\0';
		return VRAPI_EVENT_ERROR_INVALID_BUFFER;
	}

	if ( queue == NULL ) 
	{
		return VRAPI_EVENT_ERROR_INTERNAL;
	}

	EventQueue * q = reinterpret_cast< EventQueue* >( queue );
	EventData const * eventData;
	if ( !q->Dequeue( eventData ) ) 
	{
		return VRAPI_EVENT_NOT_PENDING;
	}

	OVR_strncpy( buffer, bufferSize, static_cast< char const * >( eventData->GetData() ), eventData->GetSize() );
	bool overflowed = eventData->GetSize() >= bufferSize;

	delete eventData;
	return overflowed ? VRAPI_EVENT_BUFFER_OVERFLOW : VRAPI_EVENT_PENDING;
}
Example #11
0
// interrupt handler.  this just adds a quit event to the queue.
static
void
interrupt(Arch::ESignal, void* data)
{
    EventQueue* events = static_cast<EventQueue*>(data);
    events->addEvent(Event(Event::kQuit));
}
Example #12
0
void IDBDatabase::enqueueEvent(PassRefPtr<Event> event)
{
    ASSERT(scriptExecutionContext()->isDocument());
    EventQueue* eventQueue = static_cast<Document*>(scriptExecutionContext())->eventQueue();
    event->setTarget(this);
    eventQueue->enqueueEvent(event.get());
    m_enqueuedEvents.append(event);
}
Example #13
0
void IDBDatabase::enqueueEvent(Event* event) {
  DCHECK(!m_contextStopped);
  DCHECK(getExecutionContext());
  EventQueue* eventQueue = getExecutionContext()->getEventQueue();
  event->setTarget(this);
  eventQueue->enqueueEvent(event);
  m_enqueuedEvents.append(event);
}
Example #14
0
	/**
	 * Processes all of the scheduled delegates until there are no more to execute.
	 * Sleeps when waiting for a scheduled delegate to be ready to invoke to reduce processor usage.
	 */
	static void Run() { StackTrace trace(__METHOD__, __FILE__, __LINE__);
		while (FutureEvents.empty() == false) {
			FutureEventHandler event = FutureEvents.top();
			FutureEvents.pop();
			Sleep(event.Time() - DateTime::Utc());
			event();
		}
	}
Example #15
0
void IDBDatabase::enqueueEvent(PassRefPtr<Event> event)
{
    ASSERT(!m_contextStopped);
    ASSERT(scriptExecutionContext());
    EventQueue* eventQueue = scriptExecutionContext()->eventQueue();
    event->setTarget(this);
    eventQueue->enqueueEvent(event.get());
    m_enqueuedEvents.append(event);
}
Example #16
0
File: test8.cpp Project: ombt/ombt
int
main(int argc, char **argv)
{
    dbgopen(stderr);

    if (argc != 3)
    {
        cerr << "usage: " << argv[0] << " maxcount readernum" << endl;
        return(2);
    }

    int arg=0;
    int imax = ::atoi(argv[++arg]);
    MustBeTrue(imax > 0);
    int nreaders = ::atoi(argv[++arg]);
    MustBeTrue(nreaders > 0);

    EventQueue<int> eq;

    std::list<UseCntPtr<Reader> > readers;
    std::list<UseCntPtr<SimpleThread> > threads;

    for (int ireader=1; ireader<=nreaders; ++ireader)
    {
        UseCntPtr<Reader> reader(new Reader(ireader, eq));
	readers.push_back(reader);

        UseCntPtr<SimpleThread> st(new SimpleThread(reader));
        MustBeTrue(st->isOk());

        MustBeTrue(st->run() == 0);
        MustBeTrue(st->isOk());

	threads.push_back(st);
    }

    SimpleThread st(new Writer(0, imax, eq));
    MustBeTrue(st.isOk());

    MustBeTrue(st.run() == 0);
    MustBeTrue(st.isOk());

    void *retval;
    st.join(retval);

    eq.done();

    std::list<UseCntPtr<SimpleThread> >::iterator iter = threads.begin();
    std::list<UseCntPtr<SimpleThread> >::iterator iterend = threads.end();
    for ( ; iter != iterend; ++iter)
    {
        (*iter)->join(retval);
    }

    return(0);
}
void IDBTransaction::enqueueEvent(PassRefPtrWillBeRawPtr<Event> event)
{
    ASSERT_WITH_MESSAGE(m_state != Finished, "A finished transaction tried to enqueue an event of type %s.", event->type().utf8().data());
    if (m_contextStopped || !executionContext())
        return;

    EventQueue* eventQueue = executionContext()->eventQueue();
    event->setTarget(this);
    eventQueue->enqueueEvent(event);
}
Example #18
0
void allocate_failure_test() {
    EventQueue queue;
    int id;

    for (int i = 0; i < 100; i++) {
        id = queue.call((void (*)())0);
    }

    TEST_ASSERT(!id);
}
Example #19
0
		void update(EventQueue& _eventQueue)
		{
			int numButtons, numAxes;
			const unsigned char* buttons = glfwGetJoystickButtons(m_handle.idx, &numButtons);
			const float* axes = glfwGetJoystickAxes(m_handle.idx, &numAxes);

			if (NULL == buttons || NULL == axes)
			{
				return;
			}

			if (numAxes > GamepadAxis::Count)
			{
				numAxes = GamepadAxis::Count;
			}

			if (numButtons > Key::Count - Key::GamepadA)
			{
				numButtons = Key::Count - Key::GamepadA;
			}

			WindowHandle defaultWindow = { 0 };

			for (int ii = 0; ii < numAxes; ++ii)
			{
				GamepadAxis::Enum axis = translateGamepadAxis(ii);
				int32_t value = (int32_t) (axes[ii] * 32768.f);
				if (GamepadAxis::LeftY == axis || GamepadAxis::RightY == axis)
				{
					value = -value;
				}

				if (m_axes[ii] != value)
				{
					m_axes[ii] = value;
					_eventQueue.postAxisEvent(defaultWindow
						, m_handle
						, axis
						, value);
				}
			}

			for (int ii = 0; ii < numButtons; ++ii)
			{
				Key::Enum key = translateGamepadButton(ii);
				if (m_buttons[ii] != buttons[ii])
				{
					m_buttons[ii] = buttons[ii];
					_eventQueue.postKeyEvent(defaultWindow
						, key
						, 0
						, buttons[ii] != 0);
				}
			}
		}
Example #20
0
int main() {
    if (devaddr == 0x0) {
        printf("Set your LoRaWAN credentials first!\n");
        return -1;
    }

    printf("Press BUTTON1 to send the current value of the temperature sensor!\n");

    if (lorawan.initialize(&ev_queue) != LORAWAN_STATUS_OK) {
        printf("LoRa initialization failed!\n");
        return -1;
    }

    // Enable trace output for this demo, so we can see what the LoRaWAN stack does
    mbed_trace_init();

    // Fire a message when the button is pressed
    btn.fall(ev_queue.event(&send_message));

    // prepare application callbacks
    callbacks.events = mbed::callback(lora_event_handler);
    lorawan.add_app_callbacks(&callbacks);

    // Disable adaptive data rating
    if (lorawan.disable_adaptive_datarate() != LORAWAN_STATUS_OK) {
        printf("disable_adaptive_datarate failed!\n");
        return -1;
    }

    lorawan.set_datarate(5); // SF7BW125

    lorawan_connect_t connect_params;
    connect_params.connect_type = LORAWAN_CONNECTION_ABP;
    connect_params.connection_u.abp.nwk_id = net_id;
    connect_params.connection_u.abp.dev_addr = devaddr;
    connect_params.connection_u.abp.nwk_skey = nwk_s_key;
    connect_params.connection_u.abp.app_skey = app_s_key;

    lorawan_status_t retcode = lorawan.connect(connect_params);

    if (retcode == LORAWAN_STATUS_OK ||
        retcode == LORAWAN_STATUS_CONNECT_IN_PROGRESS) {
    } else {
        printf("Connection error, code = %d\n", retcode);
        return -1;
    }

    printf("Connection - In Progress ...\r\n");

    // make your event queue dispatching events forever
    ev_queue.dispatch_forever();

    return 0;
}
Example #21
0
void IDBTransaction::enqueueEvent(Event* event) {
  DCHECK_NE(m_state, Finished)
      << "A finished transaction tried to enqueue an event of type "
      << event->type() << ".";
  if (!getExecutionContext())
    return;

  EventQueue* eventQueue = getExecutionContext()->getEventQueue();
  event->setTarget(this);
  eventQueue->enqueueEvent(event);
}
    void run(int argc, char **argv) {
        if (!parseCommandLine(argc, argv)) {
            printUsage();
            return;
        }

        SessionOptions sessionOptions;
        sessionOptions.setServerHost(d_host.c_str());
        sessionOptions.setServerPort(d_port);

        std::cout << "Connecting to " + d_host + ":" << d_port << std::endl;

        SessionEventHandler eventHandler(d_identities,
                                         d_tokens,
                                         d_securities,
                                         d_field);
        Session session(sessionOptions, &eventHandler);

        if (!session.start()) {
            std::cerr << "Failed to start session. Exiting..." << std::endl;
            std::exit(-1);
        }

        openServices(&session);

        EventQueue authQueue;

        // Authorize all the users that are interested in receiving data
        if (authorizeUsers(&authQueue, &session)) {
            // Make the various requests that we need to make
            session.subscribe(d_subscriptions);
        } else {
            std::cerr << "Unable to authorize users, Press Enter to Exit"
                      << std::endl;
        }

        // wait for enter key to exit application
        char dummy[2];
        std::cin.getline(dummy,2);

        {
            // Check if there were any authorization events received on the
            // 'authQueue'

            Event event;
            while (0 == authQueue.tryNextEvent(&event)) {
                printEvent(event);
            }
        }

        session.stop();
        std::cout << "Exiting...\n";
    }
Example #23
0
void call_every_test() {
    Timer tickers[N];

    EventQueue queue;

    for (int i = 0; i < N; i++) {
        tickers[i].start();
        queue.call_every((i+1)*100, time_func, &tickers[i], (i+1)*100);
    }

    queue.dispatch(N*100);
}
Example #24
0
int main() {
    // creates a queue with the default size
    EventQueue queue;

    // events are simple callbacks
    queue.call(printf, "called immediately\n");
    queue.call_in(2000, printf, "called in 2 seconds\n");
    queue.call_every(1000, printf, "called every 1 seconds\n");

    // events are executed by the dispatch method
    queue.dispatch();
}
void IDBTransaction::enqueueEvent(PassRefPtr<Event> event)
{
    ASSERT(!m_finished);
    if (!scriptExecutionContext())
        return;

    /// M: scriptExecutionContext can be 'document' or 'worker' context
    EventQueue* eventQueue = scriptExecutionContext()->eventQueue();

    event->setTarget(this);
    eventQueue->enqueueEvent(event);
}
Example #26
0
void IDBRequest::enqueueEvent(PassRefPtr<Event> event)
{
    ASSERT(!m_finished);
    ASSERT(m_readyState < DONE);
    if (!scriptExecutionContext())
        return;

    ASSERT(scriptExecutionContext()->isDocument());
    EventQueue* eventQueue = static_cast<Document*>(scriptExecutionContext())->eventQueue();
    event->setTarget(this);
    eventQueue->enqueueEvent(event.get());
    m_enqueuedEvents.append(event);
}
Example #27
0
static void testSignalExecutor2(void) {
	print("*************************************** testSignalExecutor2\r\n");
	eq.clear();
	TestPwm p1;
	TestPwm p2;
	p1.period = 2;
	p2.period = 3;

	complexTestNow = 0;
	callbackCounter = 0;
	eq.insertTask(&p1.s, 0, (schfunc_t) complexCallback, &p1);
	eq.insertTask(&p2.s, 0, (schfunc_t) complexCallback, &p2);
	eq.executeAll(complexTestNow);
	assertEqualsM("callbackCounter #1", 2, callbackCounter);
	assertEquals(2, eq.size());

	eq.executeAll(complexTestNow = 2);
	assertEqualsM("callbackCounter #2", 3, callbackCounter);
	assertEquals(2, eq.size());

	eq.executeAll(complexTestNow = 3);
	assertEqualsM("callbackCounter #3", 4, callbackCounter);
	assertEquals(2, eq.size());

}
Example #28
0
static void testSignalExecutor3(void) {
	print("*************************************** testSignalExecutor3\r\n");
	eq.clear();

	scheduling_s s1;
	scheduling_s s2;
	scheduling_s s3;

	eq.insertTask(&s1, 10, orderCallback, (void*)1);
	eq.insertTask(&s2, 11, orderCallback, (void*)2);
	eq.insertTask(&s3, 12, orderCallback, (void*)3);

	eq.executeAll(100);
}
Example #29
0
TEST(A1MarkingEventQueueTests, EventQueueDestructorTest) {
  // Test that events are properly deleted on destruction
  EventQueue* eventQueue = new EventQueue();

  EXPECT_EQ(0, MemoryTrackingEvent::num_allocated);
  MemoryTrackingEvent* event = new MemoryTrackingEvent();
  EXPECT_EQ(1, MemoryTrackingEvent::num_allocated);

  eventQueue->AddEventToQueue(event);
  EXPECT_EQ(1, eventQueue->GetNumEventsInQueue());

  delete eventQueue;
  EXPECT_EQ(0, MemoryTrackingEvent::num_allocated);
}
Example #30
0
void IDBRequest::enqueueEvent(PassRefPtr<Event> event)
{
    ASSERT(m_readyState == PENDING || m_readyState == DONE);

    if (m_contextStopped || !scriptExecutionContext())
        return;

    ASSERT_WITH_MESSAGE(m_readyState == PENDING || m_didFireUpgradeNeededEvent, "When queueing event %s, m_readyState was %d", event->type().string().utf8().data(), m_readyState);

    EventQueue* eventQueue = scriptExecutionContext()->eventQueue();
    event->setTarget(this);

    if (eventQueue->enqueueEvent(event.get()))
        m_enqueuedEvents.append(event);
}