int main() { const int ballsCount = 20; const int rectsCount = 2; const int SLEEP_TIME = 1; /* initialize system objects */ Ball ballsArr[ballsCount]; srand(time(NULL)); Rect rects[rectsCount]; rects[0].X = 10; rects[0].Y = 5; rects[0].Width = 25; rects[0].Height = 10; rects[1].X = 50; rects[1].Y = 5; rects[1].Width = 15; rects[1].Height = 5; initAll(ballsCount, ballsArr, rectsCount, rects); /* infinite loop engine */ while(1) { clearScreen(); drawRects(2, rects); updateBalls(ballsCount, ballsArr, rectsCount, rects); drawBalls(ballsCount, ballsArr); tSleep(SLEEP_TIME); } return EXIT_SUCCESS; }
int packagesPage::resetLists() { packagesListWidget->blockSignals(true); reposListWidget->blockSignals(true); while(packagesListWidget->count() > 0) { packagesListWidget->takeItem(0); } while(reposListWidget->count() > 0) { reposListWidget->takeItem(0); } emit clearMessages(); packagesListWidget->blockSignals(false); reposListWidget->blockSignals(false); packages.clear(); packagesList.clear(); statuses.clear(); initAll(); return 0; }
int main(int argc) { // Allocate memory and setup sensorData struct sensorData = oi_alloc(); initAll(sensorData); serial_puts("Press 's' to initiate connection with robot\n\r"); while(start != 's') // Wait for Start Command { start = serial_getc(); } serial_puts("Robot communication initiated.\n\r\n\r"); display_help(); running_LED(); while(1) { read_user_input_string(sensorData); } //START TRAVERSING CODE while("NOT DONE") //While the robot is not in the Final Zone { //TODO Interface and Movement } //TODO FLASH LEDS WHEN DONE }
/******************************************************************************* FONCTION PRINCIPALE *******************************************************************************/ main(int argc,char *argv[]) { long adr,len=0L; int i,ret; _argc=argc; /* Tout ce bazar pour sauvegarder */ _argv=argv; /* la ligne de commande */ for (i=1;i<argc;i++) len+=strlen(argv[i])+2L; len+=sizeof(char **)*((long)argc+1L); adr=(long)Malloc(len); if (adr>0L) { _argv=(char **)adr; _argv[0]=(char *)(adr+4L*(long)_argc); _argv[0][0]='\0'; for (i=1;i<_argc;i++) { _argv[i]=(char *)((long)_argv[i-1]+strlen(_argv[i-1])+1L); strcpy(_argv[i],argv[i]); } } ret=initAll(); if (ret) { _EGlib(); if (adr>0L) Mfree((void *)adr); return FALSE; } if (adr>0L) Mfree((void *)adr); return ret; }
/*! * \brief Funkcja main * * Wywołuje inicjalizację wszystkich urządzeń. Zawiera główną pętle programu, * z której wywoływane są funkcje obsługujące części programu, po ustawieniu * flagi dal danego urządzenia. */ int main(void) { initAll(); while(1) { if(LCD_flag){ LCD_flag = 0; lcd_cursor_off(); change_display(); } if(RTC_flag){ RTC_flag = 0; ds1307_getTime( ¤tTime ); } if(buttonCheck_flag){ buttonCheck_flag = 0; int x = button_listener(); transition(x); } if( alarm_flag ){ alarm_flag = 0; alarmCheck(); } } return 0 ; }
int main (void) { // Initialize everything initAll(); xprintf("Startup!"); #ifdef GENERATE_ASCII_RANDOM_BITS uint32_t i,j; uint32_t n; for (i=0; i<NUMBER_OF_RANDOM_WORDS; i++) { n = TM_RNG_Get(); //while (n) { for (j=0; j<32; j++) { if (n & 1) xprintf("1"); else xprintf("0"); n >>= 1; } } #endif #ifdef GENERATE_BINARY_RANDOM_BITS uint32_t i=0; uint32_t n; for (i=0; i<NUMBER_OF_RANDOM_WORDS; i++) { //xprintf("."); n = TM_RNG_Get(); xprintf("%c%c%c%c",(n&0xff),((n>>8)&0xff),((n>>16)&0xff),((n>>24)&0xff)); } #endif #ifdef PERFORM_UNIT_TESTS perform_unit_tests(); #endif #ifdef PERFORM_SPEED_TESTS speed_test(); #endif xputs("[Done]\n\n"); while (1) { } return 0; }
void main(){ unsigned char seg7[] ={0x3f, 0x06,0x5b,0x4f,0x66, 0x6d,0x7d,0x07,0x7f,0x6f, 0x77,0x7c,0x39,0x5e,0x79,0x71}; //Array of Hex table initAll(); // DO EVERYTHING NOW while(1){ // this could go on f0r3v3r lights(PTH & 0x07 ); LED7(); } }
void readFromFile(char *fileName) { fpR = fopen(fileName, "rb"); if(fpR==NULL) showError(2); fscanf(fpR, "%d", &charCount); for(int i=1; i<=charCount; i++) fscanf(fpR, "%d", &charSet[i]); for(i=1; i<=2*charCount-1; i++) fscanf(fpR, "%d", &parent[i]); initAll(); }
int main(void) { initAll(); DIR_TOWARDS(); while(1) { } return 0; }
int main(void) { //VARIABLES uint16_t x = 0, max_x = 0; char speComm = 'O'; //INIT initAll(); //START PROG #ifdef PRINTF_MAIN printf("BEGIN"); #endif #ifdef PRINTF_MAIN printf("\nAppuyer sur le boutton"); #endif //initialisation du blanc while(!cc3_button_get_state());//attente d'une pression du boutton while(1) { #ifdef BENCH uint16_t start_time, end_time; start_time = cc3_timer_get_current_ms(); #endif //IMG if(imgAnalysis(&x, &max_x) == 0) speComm = 'O'; else speComm = 'R'; #ifdef PRINTF_ABS_FINAL printf("\nmoyenneFinal: %d", x); #endif //Motor motComm(x, max_x, speComm); #ifdef BENCH end_time = cc3_timer_get_current_ms(); printf ("\ntime:%d", end_time - start_time); #endif } //END #ifdef PRINTF_MAIN printf ("\nEND"); #endif return 0; }
int main(void) { InitRTOS(); RunRTOS(); initAll(); wdt_enable(WDTO_120MS); RunTasks(); while (1) { wdt_reset(); // �בנמס סמבאק�ודמ עאילונא TaskManager(); // ��חמג הטסןועקונא } }
int calcNumDevices() { if (numDevices>=0) return numDevices; initAll(); unsigned int i=0; for (; i<MAXJOYSTICKS; i++) { int fd=openJoystick(i); if (fd<0) break; closeJoystick(i); } return numDevices=i; }
int main(int argc, char *argv[]) { // initialisation des variables initAll(); // boucle du jeu game(); // netoyage de la memoire et fermeture du programme quit(); return EXIT_SUCCESS; }
void main(){ int checkHigh, checkLow; char chump[33]; initAll(); while(1){ if(ATD0STAT0); (void)sprintf(chump,"%4d mV \n L%d H%d", scaleV((uint)ATD0DR2),checkLow,checkHigh); LCDshark(chump); if(checkHigh < ATD0DR2) checkHigh = ATD0DR2 ; if(checkLow > ATD0DR2) checkLow = ATD0DR2; } }
bool LonLatParser::parse(const QString& string) { const QString input = string.toLower().trimmed(); // #1: Just two numbers, no directions, e.g. 74.2245 -32.2434 (assumes lat lon) { const QString numberCapExp = QStringLiteral("\\A(?:") + QStringLiteral("([-+]?\\d{1,3}%1?\\d*(?:[eE][+-]?\\d+)?)(?:,|;|\\s)\\s*").arg(m_decimalPointExp) + QStringLiteral("([-+]?\\d{1,3}%1?\\d*(?:[eE][+-]?\\d+)?)").arg(m_decimalPointExp) + QStringLiteral(")\\z"); const QRegularExpression regex(numberCapExp); QRegularExpressionMatch match = regex.match(input); if (match.hasMatch()) { m_lon = parseDouble(match.captured(2)); m_lat = parseDouble(match.captured(1)); return true; } } initAll(); if (tryMatchFromD(input, PostfixDir)) { return true; } if (tryMatchFromD(input, PrefixDir)) { return true; } if (tryMatchFromDms(input, PostfixDir)) { return true; } if (tryMatchFromDms(input, PrefixDir)) { return true; } if (tryMatchFromDm(input, PostfixDir)) { return true; } if (tryMatchFromDm(input, PrefixDir)) { return true; } return false; }
void classified_address_analysis(char *bin_fname) { int dbg = 0; int i,j,k; P_Queue *pQueue; tcfg_node_t *tbb,*tsrc,*tdes; cfg_node_t *bb,*src,*des; tcfg_edge_t *tedge; cfg_edge_t *edge; inf_node_t *ib,*isrc,*ides; inf_proc_t *ip; // inf_edge_t *iedge; de_inst_t *inst; dat_inst_t *d_inst; loop_t *loop, *preLoop; FILE *dbgAddr; dbgAddr = fopen("dbg_addr.dbg","w"); printf("\nPerforming address analysis");fflush(stdout); setAddrDebugFile(dbgAddr); initAll(bin_fname); /*generate mem.blk & access scope for each data reference*/ for (i=0; i<prog.num_procs; i++) { ip = &(inf_procs[i]); for (j=0; j<ip->num_bb; j++) { ib = &(ip->inf_cfg[j]); if (dbg) { fprintf(dbgAddr,"\nBB (%d,%d) L%d num:%d sa:%s", i,j,ib->loop_id, ib->num_insn, ib->insnlist[0].addr); fflush(dbgAddr); } bb = ib->bb; for (k = 0; k<bb->num_d_inst; k++) { d_inst = (dat_inst_t*)(bb->d_instlist); d_inst = d_inst + k; genAccessAddress(d_inst,ib); } } } if (1) { fprintf(dbgAddr,"Created memblk: %d",totalBlk);fflush(dbgAddr); printf("Created memblk: %d",totalBlk);fflush(stdout); } freeMem(); }
int main(void) { UINT8 mpu_address = MPU6050_ADDRESS_AD0_LOW; initAll(); UINT8 acc[2] = {0}; INT16 acc16 = 0; float acc_g = 0; UINT8 data = 0; while(TRUE) { requestReadBytes(MPU6050_ADDRESS_AD0_LOW, (UINT8)MPU6050_RA_ACCEL_XOUT_H, acc, 2); // burst read two bytes. PORTToggleBits(IOPORT_F, BIT_0); // LED5. DelayMs(1000); acc16 = (INT16)((acc[0] << 8) | acc[1]); acc_g = (float)acc16 / 16384.0; printf("\n\rACC X: %f\n\r", acc_g); } return (EXIT_SUCCESS); }
int main(int argc, char * argv[]) { initAll(); if(argc != 2) { error("Minus takes a single argument: the program file to run.\n"); } FILE * file = readFile(argv[1]); process(file); fclose(file); //printf("%s\n\n", processedProgram); runInit(); while(1) runStep(); }
int main(void) { initAll(); pid_config(&motor_pid1,2.0,0.5,0,MAX_PWM,1000); // sets up the PID struct pid_config(&motor_pid2,1.0,1.0,0,MAX_PWM,500); pid_config(&motor_vel_pid1,30.0,1.0,0,MAX_PWM,3000); // max output, max integration factor absolute_to_relative_config(&counts1,14000,7000,getMotor1Counts()); //char output[50]; pid_auto_tune(&motor_pid1, 100, MAX_PWM, 1000,getMotor1Counts,setSpeed,zeroMotor1,1); //int result = pid_test(&motor_pid1,500,getMotor1Counts,setSpeed,1); setSpeed(0,1); //sprintf(output,"Result is %d\r\n",result); //uartWrite(output); while (1) { //int pwm1 = pid_controller(&motor_pid1,500,getMotor1Counts()); //sprintf(output,"Motor int: %f Curr value is: %d, Commanded value is: %d\r\n",motor_pid1.ki,getMotor1Counts(),pwm1); //uartWrite(output); //setSpeed(pwm1,1); //int pwm1vel = pid_controller(&motor_vel_pid1,30,getMotor1Velocity()); //sprintf(output,"PWM is: %d, Curr value is: %d \r\n",pwm1vel,getMotor1Velocity()); //uartWrite(output); processUART(); } }
DialogPreference::DialogPreference(QWidget *parent) : QDialog(parent), ui(new Ui::DialogPreference) { ui->setupUi(this); cnf = new QSettings("Q-Uma","quma-skripsi",this); initAll(); ui->listWidget->setViewMode(QListView::IconMode); ui->listWidget->setIconSize(QSize(75,75)); ui->listWidget->setCurrentRow(0); ui->stackedWidget->setCurrentIndex(0); ui->listWidget->setAcceptDrops(false); curCat = 0; // bahasa ui->label_25->hide(); ui->cbLang->hide(); //Main Connection connect(ui->listWidget,SIGNAL(currentRowChanged(int)), ui->stackedWidget,SLOT(setCurrentIndex(int))); connect(ui->pbApply,SIGNAL(clicked()),this,SLOT(applyConfig())); connect(ui->pbClose,SIGNAL(clicked()),this,SLOT(closeDialog())); // Page General // Page Category connect(ui->cbCategory,SIGNAL(currentIndexChanged(int)), this,SLOT(changeCategory())); connect(ui->pbBrowseCatSaveDir,SIGNAL(clicked()), this,SLOT(browseCategorySaveDir())); connect(ui->leFilesType,SIGNAL(editingFinished()), this,SLOT(leType())); connect(ui->leCategorySaveDir,SIGNAL(editingFinished()), this,SLOT(leSaveDir())); setWindowTitle(tr("Preference")); setWindowIcon(QIcon(":/icon/menu/image/icon/Gear Alt.png")); }
int main(void) { initAll(); // initialize all functions // The PID config is: // pid_config struct | P coefficient | I coefficient | D coefficient | maximum value to output | maximum value to integrate to pid_config(&motor_pid1,2.0,0.5,0,MAX_PWM,1000); // The absolute to relative config is: // absolute_data | rollover value | rollover threshold | current value // The rollover value is when the absolute sensor resets to zero. The absolute_to_relative function adds this modifier each time a reset is detected. A threshold value is used to determine if a rollover has occured with the following formula: threshold = current value - previous value. This threshold is typically set to half of the rollover value absolute_to_relative_config(&counts1,14000,7000,getMotor1Counts()); // The auto_tune inputs are: // pid struct | disturbance in counts | count function | set output function | zero motor function | motor number // This function assumes a certain form for the functions that it calls. The count function will return an integer, the zero function will set the encoder count to zero, and the set output function takes in a pwm value and a motor number and returns nothing. pid_auto_tune(&motor_pid1, 100, getMotor1Counts,setSpeed,zeroMotor1,1); // Send pwm = 0 to motor 1 to stop the motor if it is spinning setSpeed(0,1); while (1) { // start menu processUART(); } }
void Viewer::init() { if (bFirstInit) { // - init GLEW OpenGL::init(); fprintf(stdout, "Status: Using GLEW %s\n", glewGetString(GLEW_VERSION)); // Restore previous viewer state. //restoreStateFromFile(); // Set position of light's camera qgl_cam_light.setPosition( qglviewer::Vec(0, 50, 0) ); qgl_cam_light.fitBoundingBox( qglviewer::Vec(-1, -1, -1), qglviewer::Vec(+1, +1, +1) ); // Add a manipulated frame to the viewer. setManipulatedFrame( qgl_cam_light.frame() ); setAnimationPeriod(0.); setSceneCenter(qglviewer::Vec(0, 0, 0)); setSceneRadius(10.f); } initAll( !bFirstInit ); if (bFirstInit) { qgl_mf_vbo.setPosition( -qglviewer::Vec(ts->getCenter()) ); f_scale_vbo = 1.f / ( ts->getRadius() ); } bFirstInit = false; // On vérifie les erreurs MSG_CHECK_GL; }
/** * Main loop. */ int main(void) { int32_t lastSpeedCalc = 0; int32_t lastDebug = 0; int32_t lastDebug2 = 0; // initalize all modules initAll(); // enable interrupts (i.e timers start from here) sei(); // The LOOP while(1) { // read serial port readCommand(); // communication.c // apply speed calculation and run odometer if (uptime() >= lastSpeedCalc + SPEED_CALC_PERIOD) { lastSpeedCalc += SPEED_CALC_PERIOD; calculateSpeeds(); // motors.c if (pidOn) { runPID(); // motors.c } //if (debug1) printSpeed(CPUCHAR); runOdometer(); // odometer.c navigator(); } // read sensors and apply position correction positionCorrection(); // odometer.c // print debug loop 2 if (uptime() >= (lastDebug2 + 20)) { lastDebug2 = uptime(); if (debug6) printf("%d, %d\r\n", p_LsensVal, p_RsensVal); } // print debug if ((debugPeriod) && uptime() >= (lastDebug + debugPeriod)) { lastDebug += debugPeriod; //if (debug1) printf(">21%02x\r", speed0 >> 4); //if (debug1) printf(">21%04x\r>22%04x\r", readADC(0), readADC(1)); //if (debug2) printf("%ld\t%ld\r\n", timer, timer20); //if (debug2) printf_P(PSTR("%d\t%d\r\n"), p_L, p_R); if (debug3) printf_P(PSTR("%d, %d / %d, %d / %d, %d / %u, %u\r\n"), p_Ltrans, p_Lrel, p_Rtrans, p_Rrel, p_Lerr, p_Rerr, posCorrLeftFailed, posCorrRightFailed); //if (debug4) printf_P(PSTR("%ld\t%ld\r\n"), ticks0, ticks1); //if (debug5) printSpeed(CPUCHAR); //if (debug5) printf_P(PSTR("%d\t%d\r\n"), speed0, speed1); //if (debug6) printf_P(PSTR("%d\t%d\r\n"), accel0, accel1); if (debug7) printf_P(PSTR("%u\t%u\r\n"), power0, power1); // debug for GUI printTicks(CPUCHAR); printSpeed(CPUCHAR); printAccel(CPUCHAR); printAbsDist(CPUCHAR); printRelDist(CPUCHAR); printSensors(CPUCHAR); } } while(1); }
LabViewModule::LabViewModule(PolyboxModule *polybox, QObject *parent) : QObject(parent), AbstractModule(polybox) { initAll(); }
void MultiAgentTest::doTest() { sml::Kernel* pKernel = sml::Kernel::CreateKernelInNewThread(); CPPUNIT_ASSERT_MESSAGE( pKernel->GetLastErrorDescription(), !pKernel->HadError() ); // We'll require commits, just so we're testing that path pKernel->SetAutoCommit( false ) ; // Comment this in if you need to debug the messages going back and forth. //pKernel->SetTraceCommunications(true) ; CPPUNIT_ASSERT( numberAgents < MAX_AGENTS ); std::vector< std::string > names; std::vector< sml::Agent* > agents; std::vector< std::stringstream* > trace; std::vector< int > callbackPrint; // Create the agents for ( int agentCounter = 0 ; agentCounter < numberAgents ; ++agentCounter ) { std::stringstream name; name << "agent" << 1 + agentCounter; names.push_back( name.str() ); sml::Agent* pAgent = pKernel->CreateAgent( name.str().c_str() ) ; CPPUNIT_ASSERT( pAgent != NULL ); CPPUNIT_ASSERT_MESSAGE( pKernel->GetLastErrorDescription(), !pKernel->HadError() ); agents.push_back( pAgent ); std::stringstream path; // TODO: use boost filesystem CPPUNIT_ASSERT( pAgent->LoadProductions( "test_agents/testmulti.soar" ) ); createInput( pAgent, 0 ); // Collect the trace output from the run trace.push_back( new std::stringstream() ); callbackPrint.push_back( pAgent->RegisterForPrintEvent( sml::smlEVENT_PRINT, MultiAgentTest::MyPrintEventHandler, trace[agentCounter] ) ); } pKernel->RegisterForUpdateEvent( sml::smlEVENT_AFTER_ALL_GENERATED_OUTPUT, MultiAgentTest::MyUpdateEventHandler, NULL ) ; // Run for a first set of output, so we can see whether that worked pKernel->RunAllTilOutput() ; // Print out some information reportAgentStatus( pKernel, numberAgents, trace ) ; // Now get serious about a decent run const int kFirstRun = 5 ; for (int i = 0 ; i < kFirstRun ; i++) { // Run for a bit pKernel->RunAllTilOutput() ; } reportAgentStatus(pKernel, numberAgents, trace) ; // Toss in an init-soar and then go on a bit further initAll(pKernel) ; // Second run const int kSecondRun = 5 ; for (int i = 0 ; i < kSecondRun ; i++) { // Run for a bit pKernel->RunAllTilOutput() ; } reportAgentStatus(pKernel, numberAgents, trace) ; for ( std::vector< std::stringstream* >::iterator iter = trace.begin(); iter != trace.end(); ++iter ) { delete *iter; } //cout << "Calling shutdown on the kernel now" << endl ; pKernel->Shutdown() ; //cout << "Shutdown completed now" << endl ; // Delete the kernel. If this is an embedded connection this destroys the kernel. // If it's a remote connection we just disconnect. delete pKernel ; }
void PluginManager::loadPlugins(){ initAll(); runAll(); }
/* * Previously called zzledt... Called by Fortran... * Now renamed to EventLoopPrompt * @TODO remove unused arg buf_size, menusflag, modex & dummy1 */ void C2F(eventloopprompt) (char *buffer, int *buf_size, int *len_line, int *eof) { if (getScilabMode() == SCILAB_API) { return; } if (!initialJavaHooks && getScilabMode() != SCILAB_NWNI) { initialJavaHooks = TRUE; // Execute the initial hooks registered in Scilab.java ExecuteInitialHooks(); } /* if not an interactive terminal */ #ifdef _MSC_VER /* if file descriptor returned is -2 stdin is not associated with an input stream */ /* example : echo plot3d | scilex -nw -e */ if (!isatty(fileno(stdin)) && (fileno(stdin) != -2) && getScilabMode() != SCILAB_STD) #else if (!isatty(fileno(stdin)) && getScilabMode() != SCILAB_STD) #endif { /* remove newline character if there */ if (__CommandLine != NULL) { /* read a line into the buffer, but not too * big */ *eof = (fgets(__CommandLine, *buf_size, stdin) == NULL); *len_line = (int)strlen(__CommandLine); /* remove newline character if there */ if (__CommandLine[*len_line - 1] == '\n') { (*len_line)--; } return; } } if (!initialized) { initAll(); } __LockSignal(pReadyForLaunch); if (__CommandLine) { FREE(__CommandLine); __CommandLine = NULL; } __CommandLine = strdup(""); if (ismenu() == 0) { if (!WatchGetCmdLineThreadAlive) { if (WatchGetCmdLineThread) { __WaitThreadDie(WatchGetCmdLineThread); } if (getScilabMode() != SCILAB_NWNI) { char *cwd = NULL; int err = 0; UpdateBrowseVar(TRUE); cwd = scigetcwd(&err); if (cwd) { FileBrowserChDir(cwd); FREE(cwd); } } __CreateThread(&WatchGetCmdLineThread, &watchGetCommandLine); WatchGetCmdLineThreadAlive = TRUE; } if (!WatchStoreCmdThreadAlive) { if (WatchStoreCmdThread) { __WaitThreadDie(WatchStoreCmdThread); } __CreateThread(&WatchStoreCmdThread, &watchStoreCommand); WatchStoreCmdThreadAlive = TRUE; } __Wait(&TimeToWork, pReadyForLaunch); } __UnLockSignal(pReadyForLaunch); /* ** WARNING : Old crappy f.... code ** do not change reference to buffer ** or fortran will be lost !!!! */ if (__CommandLine) { strcpy(buffer, __CommandLine); } else { strcpy(buffer, ""); } *len_line = (int)strlen(buffer); *eof = FALSE; }
PlaterCalibrator::PlaterCalibrator(PolyboxModule* polybox, QObject *parent) : QObject(parent), AbstractModule(polybox) { initAll(); }
int main( int argc, char **argv ) { mpconfig *control; char *path; FILE *pidlog=NULL; struct timeval tv; control=readConfig( ); if( control == NULL ) { printf( "music directory needs to be set.\n" ); printf( "It will be set up now\n" ); path=(char *)falloc( MAXPATHLEN+1, 1 ); while( 1 ) { printf( "Default music directory:" ); fflush( stdout ); memset( path, 0, MAXPATHLEN ); fgets(path, MAXPATHLEN, stdin ); path[strlen( path )-1]=0; /* cut off CR */ abspath( path, getenv( "HOME" ), MAXPATHLEN ); if( isDir( path ) ) { break; } else { printf( "%s is not a directory!\n", path ); } } writeConfig( path ); free( path ); control=readConfig(); if( control == NULL ) { printf( "Could not create config file!\n" ); return 1; } } muteVerbosity(); /* improve 'randomization' */ gettimeofday( &tv,NULL ); srand( (getpid()*tv.tv_usec)%RAND_MAX ); switch( getArgs( argc, argv ) ) { case 0: /* no arguments given */ break; case 1: /* stream - does this even make sense? */ break; case 2: /* single file */ break; case 3: /* directory */ /* if no default directory is set, use the one given */ if( control->musicdir == NULL ) { incDebug(); addMessage( 0, "Setting default configuration values and initializing..." ); setProfile( control ); if( control->root == NULL ) { addMessage( 0, "No music found at %s!", control->musicdir ); return -1; } addMessage( 0, "Initialization successful!" ); writeConfig( argv[optind] ); freeConfig( ); return 0; } break; case 4: /* playlist */ break; default: addMessage( 0, "Unknown argument!\n", argv[optind] ); return -1; } snprintf( control->pidpath, MAXPATHLEN, "%s/.mixplay/mixplayd.pid", getenv("HOME") ); if( access( control->pidpath, F_OK ) == 0 ) { addMessage( 0, "Mixplayd is already running!" ); freeConfig(); return -1; } signal(SIGINT, sigint ); signal(SIGTERM, sigint ); /* daemonization must happen before childs are created otherwise the pipes are cut */ if( getDebug() == 0 ) { daemon( 0, 1 ); openlog ("mixplayd", LOG_PID, LOG_DAEMON); control->isDaemon=1; pidlog=fopen( control->pidpath, "w"); if( pidlog == NULL ) { addMessage( 0, "Cannot open %s!", control->pidpath ); return -1; } fprintf( pidlog, "%i", getpid() ); fclose(pidlog); } addUpdateHook( &s_updateHook ); control->inUI=1; initAll( ); #ifdef EPAPER sleep(1); if( control->status != mpc_quit ) { epSetup(); addUpdateHook( &ep_updateHook ); } #endif pthread_join( control->stid, NULL ); pthread_join( control->rtid, NULL ); control->inUI=0; #ifdef EPAPER epExit(); #endif if( control->changed ) { writeConfig( NULL ); } unlink(control->pidpath); addMessage( 0, "Daemon terminated" ); freeConfig( ); return 0; }
int main( void ) { // Set locale // - これを指定しないとncursesが文字化けを引き起こす setlocale(LC_ALL, ""); // Initialize ncurses initscr(); // Init window noecho(); // Disable input echo cbreak(); // Turn into Non-Canonical mode clear(); // Clear whole screen curs_set(0); // Set the cursor invisible keypad(stdscr, true); // Enable support for special chars start_color(); init_pair(1, COLOR_WHITE, COLOR_WHITE); // Input char c; // Initialize initAll(); refresh(); // Prepare title frame Frame title_f(COLS-2, LINES-8, RFOrientation::TOP_LEFT); title_f.filledWith("□"); title_f.print( centerizedStrings(getTitle()), 50 ); // Prepare selection frame Frame choices_f(COLS-2, 4, RFOrientation::BOTTOM_LEFT); choices_f.println( "Press key to select menu.\n"); choices_f.println("[1] START GAME\n"); choices_f.println("[2] SHOW RULES\n"); choices_f.println("[3] ルールを見る\n"); while (1) { // Wait for input c = getch(); if (c == '1'){ // Start game clear(); refresh(); gameLoop(); initAll(); title_f.clear(); title_f.filledWith("□"); title_f.print( centerizedStrings(getTitle()), 50 ); } else if(c == '2'){ // Show rules title_f.clear(); title_f.print( getRulesEN(), 70 ); } else if(c == '3'){ // Show rules title_f.clear(); title_f.print( getRulesJP(), 70 ); } choices_f.update(); } // Clear ncurses data structures endwin(); refresh(); return 0; }