void FFmpegPlayer::run() { av_log(NULL, AV_LOG_INFO, "Start FFmpegPlayer::run()"); try { Mutex lockMutex; ScopedLock lock(lockMutex); bool done = false; while (! done) { if (_status == PLAYING) { bool no_cmd; const Command cmd = m_commands->timedPop(no_cmd, 1); if (no_cmd) { m_commandQueue_cond.wait(& lockMutex); } else { done = ! handleCommand(cmd); } } else { done = ! handleCommand(m_commands->pop()); } } } catch (const std::exception & error) { //OSG_WARN << "FFmpegPlayer::run : " << error.what() << std::endl; av_log(NULL, AV_LOG_WARNING, "FFmpegPlayer::run : %s", error.what()); } catch (...) { //OSG_WARN << "FFmpegPlayer::run : unhandled exception" << std::endl; av_log(NULL, AV_LOG_WARNING, "FFmpegPlayer::run : unhandled exception"); } //OSG_NOTICE<<"Finished FFmpegPlayer::run()"<<std::endl; av_log(NULL, AV_LOG_INFO, "Finished FFmpegPlayer::run()"); // Ensure that all threads are closed cmdPause(); // // Because \open() starts thread, here we should call \close() close(); }
/* sender_peer_id given to this shall be quaranteed to be a valid peer */ void Client::ProcessData(NetworkPacket *pkt) { DSTACK(FUNCTION_NAME); ToClientCommand command = (ToClientCommand) pkt->getCommand(); u32 sender_peer_id = pkt->getPeerId(); //infostream<<"Client: received command="<<command<<std::endl; m_packetcounter.add((u16)command); /* If this check is removed, be sure to change the queue system to know the ids */ if(sender_peer_id != PEER_ID_SERVER) { infostream << "Client::ProcessData(): Discarding data not " "coming from server: peer_id=" << sender_peer_id << std::endl; return; } // Command must be handled into ToClientCommandHandler if (command >= TOCLIENT_NUM_MSG_TYPES) { infostream << "Client: Ignoring unknown command " << command << std::endl; return; } /* * Those packets are handled before m_server_ser_ver is set, it's normal * But we must use the new ToClientConnectionState in the future, * as a byte mask */ if(toClientCommandTable[command].state == TOCLIENT_STATE_NOT_CONNECTED) { handleCommand(pkt); return; } if(m_server_ser_ver == SER_FMT_VER_INVALID) { infostream << "Client: Server serialization" " format invalid or not initialized." " Skipping incoming command=" << command << std::endl; return; } /* Handle runtime commands */ handleCommand(pkt); }
//////////////////////////////////////////////////////////////////////////////// /// Process incoming requests int CameraV4L2::HandleRequests() { void *client; char request[PLAYER_MAX_REQREP_SIZE]; char outBuf[PLAYER_MAX_REQREP_SIZE]; int len; while ((len = GetConfig(&client, &request, sizeof(request),NULL)) > 0) { int ret = -1; PLAYER_MSG2(2,"Got Reguest %c (size: %d)", request[0], len); if (len>1 && (request[0]=='g' || request[0]=='G')){ // pobranie jakiejs wartosci PLAYER_MSG0(2,"Get type request"); ret = handleCommand(request, len, outBuf, PLAYER_MAX_REQREP_SIZE-1); if (ret==0) { outBuf[PLAYER_MAX_REQREP_SIZE-1] = '\0'; PLAYER_MSG1(2,"Sending Ack: %s", outBuf); if (PutReply(client, PLAYER_MSGTYPE_RESP_ACK, outBuf, strlen(outBuf)+1,NULL) != 0) PLAYER_ERROR("PutReply() failed"); } else { PLAYER_MSG0(2,"Sendinf NACK"); if (PutReply(client, PLAYER_MSGTYPE_RESP_NACK,NULL) != 0) PLAYER_ERROR("PutReply() failed"); } } else { if (len>0) { ret = handleCommand(request, len); } if (ret == 0){ PLAYER_MSG0(2,"Sending Ack"); if (PutReply(client, PLAYER_MSGTYPE_RESP_ACK,NULL) != 0) PLAYER_ERROR("PutReply() failed"); } else { PLAYER_MSG0(2,"Sending Nack"); if (PutReply(client, PLAYER_MSGTYPE_RESP_NACK,NULL) != 0) PLAYER_ERROR("PutReply() failed"); } } // if framegrabber is slow(1-10s), it is worth handling all commands at once //usleep(30000); } return 0; }
void ConsoleHandler::handlerThread() { std::string line; while(!m_consoleReader.stopped()) { try { if (!m_prompt.empty()) { if (m_promptColor != Color::Default) { Console::setTextColor(m_promptColor); } std::cout << m_prompt; std::cout.flush(); if (m_promptColor != Color::Default) { Console::setTextColor(Color::Default); } } if (!m_consoleReader.getline(line)) { break; } boost::algorithm::trim(line); if (!line.empty()) { handleCommand(line); } } catch (std::exception&) { // ignore errors } } }
void Robot::handleCommunicationMessage(std::string message) { if (Command::isValid(message)) { Command command = Command::parse(message); handleCommand(command); } }
void run_electronics_test() { cli(); //Disable times and PWM, except for timer5, which controls the motor current PWM levels. TCCR1A = 0; TCCR2A = 0; TCCR3A = 0; TCCR4A = 0; uint8_t idx = 0; char command_buffer[32]; send_P(PSTR("TEST\r\n")); while(true) { watchdog_reset(); if (UCSR0A & _BV(RXC0)) { uint8_t recv = UDR0; if (recv == '\n' || recv == '\r') { command_buffer[idx] = 0; idx = 0; handleCommand(command_buffer); } else { command_buffer[idx++] = recv; } } } }
// -------------------------------------------------------------------------------------- static pascal OSStatus appEventHandler(EventHandlerCallRef nextHandler, EventRef event, void *junk) { #pragma unused (nextHandler, junk) OSStatus result = eventNotHandledErr; UInt32 eventClass, eventKind; HICommand command; eventClass = GetEventClass(event); eventKind = GetEventKind(event); switch (eventClass) { case kEventClassCommand: switch (eventKind) { case kEventCommandProcess: GetEventParameter(event, kEventParamDirectObject, typeHICommand, NULL, sizeof(HICommand), NULL, &command); result = handleCommand(command); break; } break; } return result; }
// Handle command event processing. void commandProcessingThread(void const *argument) { UINT8 currentIndex; for (;;) { // Wait for a command message. osEvent commandEvent = osMessageGet(commandQueue, osWaitForever); // Is this a command event? if (commandEvent.status == osEventMessage) { // Point to the message. commandMessage *message = (commandMessage *) commandEvent.value.p; // Execute all the commands currentIndex = 0; while (currentIndex < message->length) { currentIndex += handleCommand(message, currentIndex); } // Free the message. osPoolFree(commandMemPool, message); } } }
void OM_ProccessOperation(OPERATION_HEADER_t* operation_header) { /* TESTING REGION */ //For testing purposes just send throw UART port HAL_UartPrint("PROCESSIG OPERATION >> TO:"); numWriteHEX(operation_header->destinationAddress); HAL_UartPrint("\t CODE:"); numWriteHEX(operation_header->opCode); HAL_UartPrint("\t ARGS:"); uint8_t length = getCommandArgsLength(&operation_header->opCode); for (uint8_t i = 0; i < length; i++) { numWriteHEX(*((uint8_t*)operation_header + sizeof(OPERATION_HEADER_t) + i)); HAL_UartWriteByte(' '); } HAL_UartPrint("\r\n"); if(operation_header->opCode == EXTENSION_OPCODE) return; /* END OF TESTING REGION */ if(operation_header->destinationAddress == 0) //MINE (INTERNAL) { handleCommand(operation_header, 0); //sourceAddress = 0x00 }else { Radio_AddMessageByReference(operation_header); } }
int _tmain(int argc, TCHAR *argv[], TCHAR *envp[]) { char line[MAX_LINE_LENGTH + 1]; int chr, i; printf("Welcome to the USB Kernel Wrapper test console\n"); BOOL running = TRUE; // Create message queue for device notifications HANDLE queue, notif; createDeviceNotificationQueue(queue, notif); while (running) { checkDeviceNotificationQueue(queue); printMenu(); for (i = 0; i < MAX_LINE_LENGTH; ++i) { chr = getchar(); if (chr == EOF || chr == '\n') break; line[i] = (char)chr; } line[i] = '\0'; running = handleCommand(line); } destroyDeviceNotificationQueue(queue, notif); return 0; }
void CubeSession::OnPackage(Package *&pack) { if (!pack || pack->Header.DataLength == 0) return; pack->Data[pack->Header.DataLength - 1] = '\0'; log_debug("on package (fd = %u): %s", static_cast<unsigned int>(fd), pack->Data); Document doc; doc.Parse(pack->Data); // {"command": "cmd...", arg1: argv1, arg2: argv2, ...} do { if (!doc.IsObject()) { SendError(SESSIONERROR_PROTOCOL_MISMATCH); break; } if (checkObj(doc, 1, "command", "str")) { handleCommand(doc); } else { SendError(SESSIONERROR_PROTOCOL_MISMATCH); break; } } while (false); delete pack; pack = NULL; }
LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { switch (msg) { case WM_CREATE: gRequestSender = new RequestSender(IDC_SEND_BUTTON); if (!setup_window(hwnd, hDefaultFont)) { MessageBoxA(NULL, "Failed to create dialog item(s)", "Error!", MB_ICONEXCLAMATION | MB_OK); return NULL; }; CheckRadioButton(hwnd, IDC_RADIO_GET, IDC_RADIO_OPTIONS, IDC_RADIO_GET); break; case WM_CTLCOLORLISTBOX: return (LONG)gHBRBackground; case WM_PAINT: paintText(hwnd); break; case WM_COMMAND: handleCommand(hwnd, msg, wParam, lParam); break; case WM_CLOSE: delete gRequestSender; WSACleanup(); PostQuitMessage(0); break; case WM_DESTROY: DestroyWindow(hwnd); break; default: return DefWindowProc(hwnd, msg, wParam, lParam); } return 0; }
void SocketManager::handleReceive() { char *cmd; if (isSocketAvailable(this->_clientToServer, this->_fdread)) { cmd = this->_clientToServer->Receive(); if (cmd != NULL) handleCommand(this->_clientToServer, cmd); } if (isSocketAvailable(this->_clientToClient, this->_fdread)) { cmd = this->_clientToClient->Receive(); if (cmd != NULL) handleCommand(this->_clientToClient, cmd); } }
unsigned long TelnetSession::InnerOutputThread() { unsigned char* receivedData = NULL; // Main program loop while(activeConnection) { try { // Download data receivedData = (unsigned char*)connection->receive(); } catch(char* errorMessage) { // Connection has been dropped activeConnection = false; KillThreads(); return 0; } // Scan for command codes unsigned char *pPos = receivedData; while(*pPos != '\0') { // Telnet control code if(*pPos == IAC) { int bytesRead = handleCommand(pPos); pPos += bytesRead; } // VT100 control code else if(*pPos == VT_ESC) { int bytesRead = handleVTCommand(pPos); pPos += bytesRead; } // Just text else { if (NULL != console) { cout << *pPos; cout.flush(); } WaitForSingleObject(m_hMtxS2CBuf, INFINITE); m_s2cBuf += *pPos; ReleaseMutex(m_hMtxS2CBuf); pPos++; } } delete[] receivedData; } KillThreads(); return 0; }
void CRemoteInterface::checkForCommands() { while (REM_SERIAL.available()) { const uint8_t b = REM_SERIAL.read(); if (!receivedSerRecMsgStart) receivedSerRecMsgStart = (b == MSG_STARTMARKER); else if (!receivedSerRecMsgSize) { receivedSerRecMsgSize = true; serRecMsgSize = b; } else if (serRecMsgBytesRead < serRecMsgSize) { if (currentSerRecMsg == MSG_NONE) currentSerRecMsg = static_cast<EMessage>(b); else tempSerialMsgBuffer.push(b); ++serRecMsgBytesRead; } else { // Msg got through OK? if (b == MSG_ENDMARKER) { // UNDONE #if 0 // First check special cases that are not passed through if (currentSerRecMsg == MSG_PONG) { tempSerialMsgBuffer.clear(); // wdt_reset(); } else if (currentSerRecMsg == MSG_CNTRL_DISCONNECT) { tempSerialMsgBuffer.clear(); Serial.println("cntrl disconnect"); btConnected = false; // Wait for a bit for actual disconnection before // updating status ignoreconupdatedelay = curtime + 3000; } else #endif { handleCommand(currentSerRecMsg); } } receivedSerRecMsgStart = receivedSerRecMsgSize = false; serRecMsgSize = 0; serRecMsgBytesRead = 0; currentSerRecMsg = MSG_NONE; tempSerialMsgBuffer.clear(); } } }
void start( const Track& t ) { MutableTrack mt( t ); mt.setSource( Track::Player ); mt.setExtra( "playerId", id() ); mt.setExtra( "playerName", name() ); mt.stamp(); handleCommand( CommandStart, t ); }
NSCAPI::nagiosReturn NSCPlugin::handleCommand(const std::string request, std::string &reply) { char *buffer = NULL; unsigned int len = 0; NSCAPI::nagiosReturn ret = handleCommand(request.c_str(), request.size(), &buffer, &len); if (buffer != NULL) { reply = std::string(buffer, len); deleteBuffer(&buffer); } return ret; }
void ChatTab::handleCommandStr(const std::string &msg) { const size_t pos = msg.find(' '); const std::string type(msg, 0, pos); std::string args(msg, pos == std::string::npos ? msg.size() : pos + 1); args = trim(args); if (!handleCommand(type, args)) inputManager.executeChatCommand(type, args, this); }
int main() { while (1){ int res; ppu_addr_t program_data_ea = spu_read_in_mbox(); program_data_ea += ((ppu_addr_t)spu_read_in_mbox())<<32; res = handleCommand( program_data_ea ); // spu_write_out_mbox( res ); spu_write_out_intr_mbox( res ); } return 0; }
Console::Console(QWidget *parent) : QDockWidget(parent) { setWindowTitle(Main::instance().translate("Console", "Console")); setObjectName("console"); construct(); connect(&Main::instance(), SIGNAL(languageChanged()), this, SLOT(changeLanguage())); connect(centralWidget, SIGNAL(command(QString)), this, SLOT(handleCommand(QString))); changeLanguage(); }
void Console::run() { char buffer[512]; while (true) { printf("> "); char* command = gets(buffer); if (!handleCommand(String(command, (unsigned int)strlen(command)))) { break; } } }
int main(int argc, char *argv[]) { string configFilename = "Config.json"; string logFilename = "-"; #ifndef _WIN32 cmdline::parser arg; arg.add<string>("config", 'c', "configuration file", false, "Config.json"); arg.add<string>("log", 'l', "log file", false, "-"); arg.parse_check(argc, argv); configFilename = arg.get<string>("config"); logFilename = arg.get<string>("log"); #endif log_normal("Using configuration file: %s", configFilename.c_str()); log_normal("Log file: %s", logFilename.c_str()); setLogFile(logFilename); Document configDoc = loadConfigObj(configFilename); Value &roomsVal = configDoc["Rooms"]; assert(roomsVal.IsArray()); vector<RoomInfo> rooms(loadRooms(roomsVal)); initLibraries(); CubeServer server; configRooms(server, rooms); server.EnableTimer(CHECK_INTERVAL_uS); configServer(server, configDoc["Server"]); server.IsRunning = true; thread th(eventEntry, &server); initHandlers(); handleCommand(server); server.Stop(); th.join(); log_normal("%s", "Stopped."); #ifdef MEM_DEBUG #ifdef _WIN32 _CrtDumpMemoryLeaks(); #endif #endif return 0; }
void TUIGame::play() { handleCommand("new"); while (true) { // Print last move if (currentMove > 0) { Position prevPos(getPos()); prevPos.unMakeMove(moveList[currentMove - 1], uiInfoList[currentMove - 1]); std::string moveStr= TextIO::moveToString(prevPos, moveList[currentMove - 1], false); if (haveDrawOffer()) moveStr += " (offer draw)"; std::cout << "Last move: " << prevPos.getFullMoveCounter() << (prevPos.isWhiteMove() ? "." : "...") << ' ' << moveStr << std::endl; } /* { std::stringstream ss; ss << "Hash: " << std::hex << std::setw(16) << std::setfill('0') << pos.zobristHash(); std::cout << ss.str() << std::endl; } */ { auto et = Evaluate::getEvalHashTables(); Evaluate eval(*et); int evScore = eval.evalPos(getPos()) * (getPos().isWhiteMove() ? 1 : -1); std::stringstream ss; ss.precision(2); ss << std::fixed << "Eval: " << (evScore / 100.0); std::cout << ss.str() << std::endl; } // Check game state std::cout << TextIO::asciiBoard(getPos()); std::string stateStr = getGameStateString(); if (stateStr.length() > 0) std::cout << stateStr << std::endl; if (getGameState() != Game::ALIVE) activateHumanPlayer(); // Get command from current player and act on it Player& pl = getPos().isWhiteMove() ? *whitePlayer : *blackPlayer; std::vector<Position> posList; getHistory(posList); std::string moveStr = pl.getCommand(getPos(), haveDrawOffer(), posList); if (moveStr == "quit") return; bool ok = processString(moveStr); if (!ok) std::cout << "Invalid move: " << moveStr << std::endl; } }
void RemoteWorker::executeCommands() { assert(comm); assert(device); CommandTag cmd; ReadBuffer args; while (1) { PING; comm->recv(cmd,args); PRINT(cmd); handleCommand(cmd,args); } }
void FFmpegImageStream::run() { try { bool done = false; while (! done) { if (_status == PLAYING) { bool no_cmd; const Command cmd = m_commands->timedPop(no_cmd, 1); if (no_cmd) { m_decoder->readNextPacket(); } else done = ! handleCommand(cmd); } else { done = ! handleCommand(m_commands->pop()); } } } catch (const std::exception & error) { OSG_WARN << "FFmpegImageStream::run : " << error.what() << std::endl; } catch (...) { OSG_WARN << "FFmpegImageStream::run : unhandled exception" << std::endl; } OSG_NOTICE<<"Finished FFmpegImageStream::run()"<<std::endl; }
void cConsole::poll() { // Poll for new Commands commandMutex.lock(); QStringList commands = commandQueue; commandQueue.clear(); commandMutex.unlock(); while ( commands.count() > 0 ) { handleCommand( commands.front() ); commands.pop_front(); } }
void Session::run(void) { try { Thread::setPriority(Concurrency::Scheduler::POLICY_RR, 1); } catch (...) { } sendReply(220, "DUNE FTP server ready."); Poll poll; poll.add(*m_sock); poll.add(*m_sock_data); while (!isStopping()) { if (m_timer.overflow()) break; try { if (!poll.poll(1.0)) continue; if (!poll.wasTriggered(*m_sock)) continue; int rv = m_sock->read(m_bfr, sizeof(m_bfr)); if (rv <= 0) break; for (int i = 0; i < rv; ++i) { if (m_parser.parse(m_bfr[i])) { handleCommand(m_parser.getCode(), m_parser.getParameters()); m_timer.reset(); } } } catch (...) { break; } } closeControlConnection(); }
/* * This is the protosocket function that handles the communication. A * protosocket function must always return an int, but must never * explicitly return - all return statements are hidden in the PSOCK * macros. */ static int handle_connection(struct socket_app_state *s){ PSOCK_BEGIN(&s->p); while(1){ PSOCK_READTO(&s->p, '\n'); if(*s->inputbuffer=='q'){ PSOCK_SEND_STR(&s->p, "\n"); break; } handleCommand(s->inputbuffer, s->outputbuffer); memset(s->inputbuffer, 0x00, SOCKET_BUFFER_LENGTH); PSOCK_SEND_STR(&s->p, s->outputbuffer); } PSOCK_CLOSE(&s->p); PSOCK_END(&s->p); }
static void *eventThread(void *args) { thread_args *a = (thread_args *)args; mqueue_enqueue(a->dispEvents, "Event thread started", 21 * sizeof(char)); while (1) { msg_command *command = mqueue_dequeue(a->events); if (command->source == MSG_INCOMING) { mqueue_enqueue(a->dispEvents, command->command, strlen(command->command)); } else { handleCommand(command->command); } free(command); } return NULL; }
void iot_subscribe_callback_handler(AWS_IoT_Client *pClient, char *topicName, uint16_t topicNameLen, IoT_Publish_Message_Params *params, void *pData) { IOT_UNUSED(pData); IOT_UNUSED(pClient); IOT_INFO("Message: %.*s\t%.*s", topicNameLen, topicName, (int) params->payloadLen, (char*)params->payload); char* msg = (char*)(malloc((int) params->payloadLen) + 1); strncpy(msg, (char*) params->payload, (int) params->payloadLen); msg[(int) params->payloadLen] = '\0'; if (findCommand(msg)) { handleCommand(); } else { publishRobotState(); publishMessage("Undefined command"); } }