//............................................................................... // handle connection //............................................................................... void Controller::handle() { wifi.handle(); on_wifi_state_change(); handleWifiTimout(); ftpSrv.handleFTP(); clock.handle(); device.handle(); // flash? if (espTools.updateRequested()) { String event; event = "~/event/esp/update begin"; handleEvent(event); if (espTools.update() == TOPIC_OK) { event = "~/event/esp/update end"; handleEvent(event); delay(1000); espTools.reboot(); } else { event = "~/event/esp/update fail"; handleEvent(event); } } // handle events while (topicQueue.count) { String topicsArgs = topicQueue.get(); yield(); handleEvent(topicsArgs); } }
void Session::_main_loop(SessionLog& log, HandState& hand_state) { // Pre-deal cards before any of the Player's start calling rand() ps::Card holdings[2][2]; ps::Card flop[3]; ps::Card turn; ps::Card river; for (int p=0; p<2; ++p) { for (int i=0; i<2; ++i ) { holdings[p][i] = _deck.deal(); } } for (int i=0; i<3; ++i ) { flop[i] = _deck.deal(); } turn = _deck.deal(); river = _deck.deal(); for (seat_t seat=0; seat<2; ++seat) { HoleCardDealEvent event(holdings[seat], seat); _players[seat]->handleEvent(hand_state, event); _set_holding(event.getSeat(), event.getCard(0), event.getCard(1)); log.record(*this, hand_state, event); } hand_state.setActionOn(_button); BlindPostDecision small_blind = _players[_button]->handleBlindRequest(SMALL_BLIND); log.record(*this, hand_state, small_blind); hand_state.setActionOn(!_button); BlindPostDecision big_blind = _players[!_button]->handleBlindRequest(BIG_BLIND); log.record(*this, hand_state, big_blind); hand_state.payBlinds(_button, _betting_rules->getSmallBlind(), _betting_rules->getBigBlind()); hand_state.setActionOn(_button); hand_state.setBettingRound(ROUND_PREFLOP); _do_betting_round(log, hand_state); if (hand_state.isDone()) return; PublicDealEvent flop_event(flop, 3); handleEvent(log, hand_state, flop_event); broadcastEvent(hand_state, flop_event); hand_state.setBettingRound(ROUND_FLOP); _do_betting_round(log, hand_state); if (hand_state.isDone()) return; PublicDealEvent turn_event(&turn, 1); handleEvent(log, hand_state, turn_event); broadcastEvent(hand_state, turn_event); hand_state.setBettingRound(ROUND_TURN); _do_betting_round(log, hand_state); if (hand_state.isDone()) return; PublicDealEvent river_event(&river, 1); handleEvent(log, hand_state, river_event); broadcastEvent(hand_state, river_event); hand_state.setBettingRound(ROUND_RIVER); _do_betting_round(log, hand_state); }
void Input::poll() { SDL_Event event; #ifdef NEED_RESIZE_HACK assert(eventQueue); EventQueue::iterator it(eventQueue->begin()); while (it!=eventQueue->end()) { if (handleEvent(*it)) it=eventQueue->erase(it); else ++it; } while ( SDL_PollEvent(&event) ) { if (!handleEvent(event)) { eventQueue->push_back(event); } } #else while ( SDL_PollEvent(&event) ) { handleEvent(event); } #endif }
// Обрабатываем событие void *worker(void *args) { // Получаем аргументы в новом потоке struct WorkerArgs *workerArgs = args; while (!done) { // Ожидание поступления события в очередь pthread_mutex_lock(workerArgs->mutex); while (isEmptyQueue(workerArgs->queue)) { pthread_cond_wait(workerArgs->condition, workerArgs->mutex); } struct epoll_event event; popQueue(workerArgs->queue, &event); pthread_mutex_unlock(workerArgs->mutex); if (event.data.fd == socketfd) { int connectionfd = acceptConnection(); if (connectionfd == -1) { fprintf(stderr, "Error: accepting new connection\n"); continue; } if (handleEvent(connectionfd) == -1) { fprintf(stderr, "Error: handling event\n"); continue; } } else { if (handleEvent(event.data.fd) == -1) { fprintf(stderr, "Error: handling event\n"); continue; } } } return NULL; }
END_TEST /* ================================================= */ /* ========= START OF CONTROLS TEST SUITE ========== */ /* ================================================= */ /* Test segfaults. Matt's input: "SDL_Events are weird." */ /* From controls.h */ /* Test passes!*/ START_TEST(test_handleEvent){ SDL_Event event; GameData gameData; SDL_Init(SDL_INIT_VIDEO); /* see startGame in game.c */ event.type = SDL_KEYDOWN; event.key.type = SDL_KEYDOWN; event.key.state = SDL_PRESSED; fail_unless(handleEvent(&event,&gameData.gameObjectData,&gameData.uiData,&gameData.controlsData, &gameData.graphicsData) == 1, "handleEvent function failed."); event.key.type = 0; event.key.state = 0; event.type = SDL_QUIT; event.quit.type = SDL_QUIT; fail_unless(handleEvent(&event,&gameData.gameObjectData,&gameData.uiData,&gameData.controlsData, &gameData.graphicsData) == 0, "handleEvent function failed."); SDL_Quit(); }
void EventHandler::threadFunc() { LOG4CPLUS_TRACE_METHOD(msLogger, __PRETTY_FUNCTION__ ); assert(mStartSemaphore); mStartSemaphore->signal(); do { assert(mEventQueue); assert(mExceptionQueue); if (IEvent * event = mExceptionQueue->pop()) { handleEvent(event); } else if (IEvent * event = mEventQueue->pop()) { handleEvent(event); } else { LOG4CPLUS_INFO(msLogger, "thread func before wait"); mEventSemaphore->wait(); LOG4CPLUS_INFO(msLogger, "thread func after wait"); } } while (!getStopFlag()); }
bool HudItemButton::onInput(const InputEvent &event) { bool is_mouse_over = isMouseOver(event); if(event.isMouseOverEvent()) { setHighlighted(is_mouse_over); if(is_mouse_over && isVisible()) handleEvent(this, HudEvent::item_focused); } if(event.mouseButtonDown(InputButton::left) && is_mouse_over) handleEvent(this, isEnabled()? HudEvent::item_unequip : HudEvent::item_equip); if(event.mouseButtonDown(InputButton::right) && is_mouse_over) { if(isEnabled()) { handleEvent(this, HudEvent::item_unequip); } else { m_drop_count = 1.0; m_drop_start_pos = (float2)event.mousePos(); } } if(event.mouseButtonPressed(InputButton::right) && isDropping()) m_drop_diff = (event.mousePos().y - m_drop_start_pos.y) / 20.0f; if(event.mouseButtonUp(InputButton::right) && isDropping()) { if(dropCount() > 0) handleEvent(this, HudEvent::item_drop, dropCount()); m_drop_count = -1.0f; } return false; }
void BootManager::onWebAppMgrConnectionStatusChanged() { if (WebAppMgrProxy::instance()->connected()) handleEvent(BOOT_EVENT_WEBAPPMGR_AVAILABLE); else handleEvent(BOOT_EVENT_WEBAPPMGR_NOT_AVAILABLE); }
void nRF51GattServer::hwCallback(ble_evt_t * p_ble_evt) { uint16_t handle_value; GattServerEvents::gattEvent_t event; switch (p_ble_evt->header.evt_id) { case BLE_GATTS_EVT_WRITE: /* There are 2 use case here: Values being updated & CCCD (indicate/notify) enabled */ /* 1.) Handle CCCD changes */ handle_value = p_ble_evt->evt.gatts_evt.params.write.handle; for(uint8_t i=0; i<characteristicCount; i++) { if ( (p_characteristics[i]->properties & (GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_INDICATE | GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_NOTIFY)) && (nrfCharacteristicHandles[i].cccd_handle == handle_value) ) { uint16_t cccd_value = (p_ble_evt->evt.gatts_evt.params.write.data[1] << 8) | p_ble_evt->evt.gatts_evt.params.write.data[0]; /* Little Endian but M0 may be mis-aligned */ if ( ((p_characteristics[i]->properties & GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_INDICATE) && (cccd_value & BLE_GATT_HVX_INDICATION )) || ((p_characteristics[i]->properties & GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_NOTIFY ) && (cccd_value & BLE_GATT_HVX_NOTIFICATION))) { event = GattServerEvents::GATT_EVENT_UPDATES_ENABLED; } else { event = GattServerEvents::GATT_EVENT_UPDATES_DISABLED; } handleEvent(event, i); return; } } /* 2.) Changes to the characteristic value will be handled with other events below */ event = GattServerEvents::GATT_EVENT_DATA_WRITTEN; break; case BLE_GATTS_EVT_HVC: /* Indication confirmation received */ event = GattServerEvents::GATT_EVENT_CONFIRMATION_RECEIVED; handle_value = p_ble_evt->evt.gatts_evt.params.hvc.handle; break; default: return; } /* Find index (charHandle) in the pool */ for(uint8_t i=0; i<characteristicCount; i++) { if (nrfCharacteristicHandles[i].value_handle == handle_value) { handleEvent(event, i); break; } } }
IOReturn SPFramebuffer::setAttribute(IOSelect sel, uintptr_t value) { IOLog("SPFramebuffer::setAttribute(%s, %lu)\n", getSelectorString(sel), value); switch (sel) { case kIOPowerAttribute: handleEvent(value >= kUBWakeState ? kIOFBNotifyWillPowerOn : kIOFBNotifyWillPowerOff); powerState = (int)value; handleEvent(value >= kUBWakeState ? kIOFBNotifyDidPowerOn : kIOFBNotifyDidPowerOff); return kIOReturnSuccess; default: break; } return super::setAttribute(sel, value); }
PulseAnalysisDisplay::PulseAnalysisDisplay (xdaq::Client* c) { // copy over the client pointer client = c; // setup the window setup(); // add the channels char buf[8]; for (unsigned int i=0; i<INDEPENDENT_TRACES; i++) { channelSelector[i]->value(0); traceColorSelector[i]->value(i%8); for (unsigned int j=0; j<client->nDatatStreams(); j++) { sprintf (buf,"%d",j); channelSelector[i]->add(buf,0,(Fl_Callback*) handleEvent, (void*) this); } } // push the plot selector button to refresh everything handleEvent(plotSelector); // hide the window window->hide(); }
unsigned int assertTimers(void *handle) { unsigned short commandCount = 2; redisReply *reply; void *rulesBinding; unsigned int result = peekTimers(handle, &rulesBinding, &reply); if (result != RULES_OK) { return result; } result = prepareCommands(rulesBinding); if (result != RULES_OK) { freeReplyObject(reply); return result; } for (unsigned long i = 0; i < reply->elements; ++i) { result = removeTimer(rulesBinding, reply->element[i]->str); if (result != RULES_OK) { freeReplyObject(reply); return result; } ++commandCount; result = handleEvent(handle, reply->element[i]->str, &rulesBinding, ACTION_ASSERT_TIMER, &commandCount); if (result != RULES_OK && result != ERR_EVENT_NOT_HANDLED) { freeReplyObject(reply); return result; } } result = executeCommands(rulesBinding, commandCount); freeReplyObject(reply); return result; }
void LogicHandler::run(void){ double deltaTime = 0; sf::Clock clock; double startTime, endTime; while (window->isOpen()){ startTime = clock.getElapsedTime().asMicroseconds(); sf::Event evt; while (window->pollEvent(evt)){ handleEvent(evt); } LogicHandler::update(deltaTime); LogicHandler::render(); long sleepTime = ((float)1 / (float)60) * 1000; sf::sleep(sf::milliseconds(sleepTime)); endTime = clock.getElapsedTime().asMicroseconds(); deltaTime = endTime - startTime; } }
bool MasterConfig::run( co::Object* frameData ) { LBASSERT( _objects ); if( frameData ) LBCHECK( _objects->register_( frameData, OBJECTTYPE_FRAMEDATA )); _objects->setFrameData( frameData ); seq::Application* const app = getApplication(); while( isRunning( )) { startFrame(); if( getError( )) LBWARN << "Error during frame start: " << getError() << std::endl; finishFrame(); while( !needRedraw( )) // wait for an event requiring redraw { if( app->hasCommands( )) // execute non-critical pending commands { app->processCommand(); handleEvents(); // non-blocking } else // no pending commands, block on user event { const eq::EventCommand& event = getNextEvent(); if( !handleEvent( event )) LBVERB << "Unhandled " << event << std::endl; } } handleEvents(); // process all pending events } finishAllFrames(); return true; }
//обработка событий потоком void* workThread(void* p){ struct Params* params = (struct Params*) p; printf("Wait"); pthread_mutex_lock(¶ms->mutex); pthread_cond_wait(¶ms->condvar,¶ms->mutex); pthread_mutex_unlock(¶ms->mutex); printf("Hi"); int cur = malloc(sizeof(int)); while(!done) { int flag = 0; pthread_mutex_lock(¶ms->mutex); if(params->currrent < params->end){ cur = params->currrent; params->currrent++; flag = 1; } else{ //если нет новых событий pthread_cond_wait(¶ms->condvar,¶ms->mutex); } pthread_mutex_unlock(¶ms->mutex); if(flag){ printf("handling event %d of %d\n", params->currrent, params->end); printf("%d\n",cur ); handleEvent(params->events+cur, params->epollfd, params->socketfd, params->userParams, params->mutex); } } }
int main(int argc, char* args[]){ bool quit = false; int select = -1; int modeMaxButtons[6]; int keyboardMode = -1; isConnected = false; for(int i=0; i < MAX_PLAYERS; i++) playerReady[i] = 0; SDL_Event event; SDL_Rect buttonPlacement[MAXBUTTONS]; // Interactable buttons SDL_Rect windowPlacement[2]; // Window backgrounds initSDL(); loadMedia(); initModeMaxButtons(modeMaxButtons); setWindows(windowPlacement); clearTextStrings(6); //SDL_StartTextInput(); while(!quit){ while (SDL_PollEvent(&event)) handleEvent(&event, buttonPlacement, &select, &mode, modeMaxButtons, &keyboardMode, &quit); renderScreen(&mode, &select, buttonPlacement, windowPlacement); SDL_Delay(10); } closeRenderer(); return 0; }
void showDialog(Widget *widget, Window *window) { memset(&dialog, 0, sizeof(Window)); dialog.leftTopX = 400; dialog.leftTopY = 375; dialog.width = 350; dialog.height = 150; dialog.show = 1; dialog.hasCaption = 1; strcpy(dialog.caption, "Save File"); addCloseButton(&dialog, &dialogCloseButtonImageView, dialogCloseButtonImageViewTemp); dialogCloseButtonImageView.onLeftClickHandler.handlerFunction = closeDialog; filenameBox.width = 150; filenameBox.height = 25; filenameBox.leftTopX = 20; filenameBox.leftTopY = dialog.height - BORDER_WIDTH - filenameBox.height - 40; strcpy(filenameBox.text, window->caption); filenameBox.cursor = filenameBox.textLength = strlen(filenameBox.text); dialog.widgets[dialog.widgetsNum].type = textBox; dialog.widgets[dialog.widgetsNum].context.textBox = &filenameBox; dialog.widgetsNum++; okButton.width = 100; okButton.height = 50; okButton.leftTopX = filenameBox.leftTopX + filenameBox.width + 50; okButton.leftTopY = filenameBox.leftTopY - 20; strcpy(okButton.text, "OK"); okButton.onLeftClickHandler.handlerFunction = saveFile; dialog.widgets[dialog.widgetsNum].type = button; dialog.widgets[dialog.widgetsNum].context.button = &okButton; dialog.widgetsNum++; hDlog = createWindow(&dialog); while (hDlog != -1) handleEvent(&dialog); }
void TRawServer::Run( void ) { srand( time(&curTime) ); Logger::open("/var/log/crowdspider.log", 1); LOG(1)("crowdspider is now started.\n"); if( Init() ) { bool running = true; while( running ) { int rc = m_poller->poll(200); if( rc < 0 ) { dbgout("poll failed:error=%i (%s)",errno,strerror(errno)); break; } if( rc == 0 ) {} if( rc > 0 ) { TPollEvent * pevents = m_poller->getPollEvents(); handleEvent(pevents, rc); } } } Exit(); LOG(1)("crowdspider is now stoped.\n"); }
int main(int argc, char *argv[]) { int rc; int exit_application = 0; initBBSpecific(); initOpenGL(screen_cxt); while (closeApplication == 0) { handleEvent(); render(); } //Stop requesting events from libscreen screen_stop_events(screen_cxt); //Shut down BPS library for this process bps_shutdown(); //Use utility code to terminate EGL setup bbutil_terminate(); //Destroy libscreen context screen_destroy_context(screen_cxt); return 0; }
void StatCache::refresh() { #ifdef __linux__ SimpleLock lock(m_lock); if (m_ifd == -1) { return; } while (true) { int nread = read(m_ifd, m_readBuf, kReadBufSize); if (nread == -1) { // No pending events. assertx(errno == EAGAIN); // Record the last refresh time *after* processing the event queue, in // order to assure that once the event queue has been merged into the // cache state, all cached values have timestamps older than // m_lastRefresh (assuming no timestamps are ever set into the future). m_lastRefresh = time(nullptr); TRACE(1, "StatCache: refresh time %lu\n", (unsigned long)m_lastRefresh); return; } for (char* p = m_readBuf; p < m_readBuf + nread;) { struct inotify_event* event = (struct inotify_event*) p; if (handleEvent(event)) { return; } p += sizeof(struct inotify_event) + event->len; } } #endif }
void MenuState::pollInputEvent(bool& finishState) { /* Check for events */ SDL_Event event; if(SDL_PollEvent(&event)) { switch (event.type) { case SDL_KEYDOWN: { switch(event.key.keysym.sym) { case SDLK_ESCAPE: { finishState = true; return; } default: { break; } } break; } default: { break; } } // If the menu pane didn't consume this event at all, then propagate to the generic input handling handleEvent(event); } }
void ScriptedIdleTaskController::runCallback( CallbackId id, double deadlineSeconds, IdleDeadline::CallbackType callbackType) { DCHECK(!m_suspended); auto callback = m_callbacks.take(id); if (!callback) return; double allottedTimeMillis = std::max((deadlineSeconds - monotonicallyIncreasingTime()) * 1000, 0.0); DEFINE_STATIC_LOCAL( CustomCountHistogram, idleCallbackDeadlineHistogram, ("WebCore.ScriptedIdleTaskController.IdleCallbackDeadline", 0, 50, 50)); idleCallbackDeadlineHistogram.count(allottedTimeMillis); TRACE_EVENT1( "devtools.timeline", "FireIdleCallback", "data", InspectorIdleCallbackFireEvent::data( getExecutionContext(), id, allottedTimeMillis, callbackType == IdleDeadline::CallbackType::CalledByTimeout)); callback->handleEvent(IdleDeadline::create(deadlineSeconds, callbackType)); double overrunMillis = std::max((monotonicallyIncreasingTime() - deadlineSeconds) * 1000, 0.0); DEFINE_STATIC_LOCAL( CustomCountHistogram, idleCallbackOverrunHistogram, ("WebCore.ScriptedIdleTaskController.IdleCallbackOverrun", 0, 10000, 50)); idleCallbackOverrunHistogram.count(overrunMillis); }
int main() { sf::RenderWindow window(sf::VideoMode(1000, 800), "RoadRunner"); window.setVerticalSyncEnabled(true); int floorWidth = window.getSize().x; int blockSize = 200; int floorHeightPosition = window.getSize().y - blockSize; sf::Texture floorTexture; floorTexture.loadFromFile(resourcePath() + "assets/yellow_floor.jpg"); sf::RectangleShape floor[2]; for (int x = 0; x < 2; x++) { floor[x].setSize(sf::Vector2f(floorWidth, blockSize)); floor[x].setTexture(&floorTexture); floor[x].setPosition(floorWidth * x, floorHeightPosition); } while (window.isOpen()) { handleEvent(window); update(floor, floorWidth, floorHeightPosition); draw(window, floor); } return 0; }
int GenericProcessor::checkForEvents(MidiBuffer& midiMessages) { if (midiMessages.getNumEvents() > 0) { int m = midiMessages.getNumEvents(); //std::cout << m << " events received by node " << getNodeId() << std::endl; MidiBuffer::Iterator i (midiMessages); MidiMessage message(0xf4); int samplePosition = 0; i.setNextSamplePosition(samplePosition); while (i.getNextEvent (message, samplePosition)) { uint8* dataptr = message.getRawData(); handleEvent(*dataptr, message, samplePosition); } } return -1; }
void StripMenuButton::onMouseUp( wxMouseEvent& event ) { if (!handleEvent(event)) sendClickCommand(); event.Skip(); }
int main(int argc ,char **argv){ SDL_Init(SDL_INIT_VIDEO); Window *frame = createWindow(SCREEN_WIDTH,SCREEN_HEIGHT,"Snakeing!"); Game *game = createGame(frame); SDL_Event event; int flag = 1 ; while (flag){ if ( !displayGame(game) ) { flag=0; break; } SDL_PollEvent(&event); SDL_Delay(80); if (event.type == SDL_QUIT){ flag = 0; break; } else if (event.type == SDL_KEYDOWN) { handleEvent(game,event); } } printf("Your Score is : %i\n",getGameScore(game)); destroyGame(game); game = NULL; destroyWindow(frame); frame = NULL; SDL_Quit(); return 0; }
void Win32TestHierarchySandboxRunnerImpl:: process(TestHierarchyHandler* handler) { setupListeners(); DWORD result = ::WaitForMultipleObjects ( sandboxes.size()*2 , handles , FALSE , INFINITE); if(result == WAIT_FAILED) { throwLastError(); } if(WAIT_OBJECT_0 > result || result >= WAIT_OBJECT_0 + sandboxes.size() * 2) { throw Error("Invalid WaitForMultipleObjects result"); } handleEvent ( (result-WAIT_OBJECT_0)/2 , (result-WAIT_OBJECT_0)%2>0 ? true : false , handler); }
void webserver_loop() { dmd_log(LOG_INFO, "in function %s, starting webserver main loop.\n", __func__); int serverfd = newSocket(); webserver_serverAddr = newAddress(); bindAddress(serverfd, webserver_serverAddr); listenAddress(serverfd); struct epoll_event events[MAX_EPOLL_EVENT]; int epollfd = newEpollSocket(); dmd_log(LOG_DEBUG, "in function %s, begin to work\n", __func__); addSockfd(epollfd, serverfd); while (1) { int ret = epoll_wait(epollfd, events, MAX_EPOLL_EVENT, -1); dmd_log(LOG_DEBUG, "in function %s, after epoll wait\n", __func__); if (ret < 0) { dmd_log(LOG_ERR, "in function %s, epoll failure\n", __func__); } else { handleEvent(epollfd, serverfd, events, ret); } } // while closeSocket(serverfd); releaseAddress(webserver_serverAddr); }
// Start the core. Execute the main loop. void Core::execute() { init(); scene = getMainScene(); scene->onInit(); SDL_Event event; gameTime.reset(); while (running) { if (gameTime.hasUpdateTimePassed()) { scene->onPreUpdate(); while (SDL_PollEvent(&event)) { handleEvent(&event); } scene->onUpdate(); } scene->onRender(gameTime.normFrameTimeDiff()); SDL_GL_SwapWindow(sdlMainWindow); } delete scene; SDL_GL_DeleteContext(sdlGlContext); SDL_Quit(); }
/*! * @brief Start the game loop */ void Game::play() { world.loadResources(); world.createRandomWorld(); sf::Clock clock; sf::Time time_fix = sf::Time::Zero; while (window.isOpen()) { sf::Event event; while (window.pollEvent(event)) { handleEvent(event); } time_fix += clock.restart(); while (time_fix > kTimePerFrame) { time_fix -= kTimePerFrame; world.update(window, kTimePerFrame); render(); } } }