Exemplo n.º 1
0
Arquivo: main.c Projeto: 119/MCTX3420
/**
 * Main entry point; start worker threads, setup signal handling, wait for threads to exit, exit
 * @param argc - Num args
 * @param argv - Args
 * @returns 0 on success, error code on failure
 * NOTE: NEVER USE exit(3)! Instead call Thread_QuitProgram
 */
int main(int argc, char ** argv)
{

	// Open log before calling ParseArguments (since ParseArguments may call the Log functions)
	openlog("mctxserv", LOG_PID | LOG_PERROR, LOG_USER);

	ParseArguments(argc, argv); // Setup the g_options structure from program arguments

	Log(LOGINFO, "Server started");


	
	#ifdef REALTIME_VERSION
	
	if (is_realtime())
	{
		Log(LOGDEBUG, "Running under realtime kernel");
	}
	else
	{
		Fatal("Not running under realtime kernel");
	}
	struct sched_param param;
	param.sched_priority = 49;
	if (sched_setscheduler(0, SCHED_FIFO, &param) < 0)
		Fatal("sched_setscheduler failed - %s", strerror(errno));
	if (mlockall(MCL_CURRENT | MCL_FUTURE) == -1)
		Fatal("mlockall failed - %s", strerror(errno));
	stack_prefault();
	#endif //REALTIME_VERSION

	

	Pin_Init();
	
	// Try and start things
	
	//const char *ret;
	//if ((ret = Control_SetMode(CONTROL_START, "test")) != NULL)
	//	Fatal("Control_SetMode failed with '%s'", ret);
	

	// run request thread in the main thread
	FCGI_RequestLoop(NULL);

	
	Control_SetMode(CONTROL_STOP, NULL);
	//if ((ret = Control_SetMode(CONTROL_STOP, "test")) != NULL)
	//	Fatal("Control_SetMode failed with '%s'", ret);
	
	//Sensor_StopAll();
	//Actuator_StopAll();

	Pin_Close();

	Cleanup();
	return 0;
}
Exemplo n.º 2
0
int main(int argc, char *argv[])
{
        struct sched_param param;
	pthread_t allthr[MAX_THR];
	int i, ret; 

	det_set_debug(1); 

	while((i=getopt(argc, argv, "n:i:h")) != EOF) {
		switch(i) {
		case 'h':
			usage();
			return 0;
		case 'n':
			max_thr = atoi(optarg);
			if (max_thr >= MAX_THR)
				errx(1, "no more than %d threads", MAX_THR);
			break;
		case 'i': 
			iteration = atoi(optarg); 
			break; 
		default:
			errx(1, "invalid option");
		}
	}

        param.sched_priority = MY_PRIORITY;
        if(sched_setscheduler(0, SCHED_RR, &param) == -1) {
                perror("sched_setscheduler failed");
                // exit(-1);
        }

        if(mlockall(MCL_CURRENT|MCL_FUTURE) == -1) {
                perror("mlockall failed");
                // exit(-2);
        }

        /* Pre-fault our stack */
        stack_prefault();

	pthread_mutex_init(&mutexsum, NULL); 		
	pthread_barrier_init(&barrier, NULL, max_thr); 

	for(i=1; i < max_thr; i++) {
		pthread_create(allthr+i, NULL, my_worker, (void *)(unsigned long)i);
	}

	// comp_worker(0); 
	my_worker(0); 

	for (i = 1; i < max_thr; i++) {
		pthread_join(allthr[i], NULL);
	}

	return 0; 
}
Exemplo n.º 3
0
int main(int argc, char* argv[])
{
        struct timespec t;
        struct sched_param param;
        int interval = 1000000; /* 50us*/

        /* Declare ourself as a real time task */

        param.sched_priority = MY_PRIORITY;
        if(sched_setscheduler(0, SCHED_FIFO, &param) == -1) {
                perror("sched_setscheduler failed");
                exit(-1);
        }

        /* Lock memory */

        if(mlockall(MCL_CURRENT|MCL_FUTURE) == -1) {
                perror("mlockall failed");
                exit(-2);
        }

        /* Pre-fault our stack */

        stack_prefault();

        clock_gettime(CLOCK_MONOTONIC ,&t);
        /* start after one second */
        t.tv_sec++;

        while(1) {
                /* wait until next shot */
                clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &t, NULL);
                printf("%ld:%ld\n",t.tv_sec, t.tv_nsec/1000000);

                /* do the stuff */

                /* calculate next shot */
                t.tv_nsec += interval;

                while (t.tv_nsec >= NSEC_PER_SEC) {
                       t.tv_nsec -= NSEC_PER_SEC;
                        t.tv_sec++;
                }
   }
}
Exemplo n.º 4
0
    bool hrpExecutionContext::enterRT()
    {
        struct sched_param param;
        param.sched_priority = m_priority;

#ifndef __APPLE__
        if (sched_setscheduler(0, SCHED_FIFO, &param) == -1) {
            perror("sched_setscheduler");
            std::cerr << "If you are running this program on normal linux kernel for debug purpose, you can ignore the error message displayed above. If not, this program must have superuser privilege." << std::endl;
            //return -1;
        }else{
            /* Lock memory */
            if(mlockall(MCL_CURRENT|MCL_FUTURE) == -1) {
                perror("mlockall failed");
            }
        }
#endif
        /* Pre-fault our stack */
        stack_prefault();

        return true;
    }
Exemplo n.º 5
0
Arquivo: rt.c Projeto: htot/hs_uart
void set_rt(void) {
        struct sched_param param;

        /* Declare ourself as a real time task */

        param.sched_priority = MY_PRIORITY;
        if(sched_setscheduler(0, SCHED_FIFO, &param) == -1) {
                perror("sched_setscheduler failed");
                exit(-1);
        }

        // Lock memory

        if(mlockall(MCL_CURRENT|MCL_FUTURE) == -1) {
                perror("mlockall failed");
                exit(-2);
        }

        // Pre-fault our stack

        stack_prefault(); 
}
Exemplo n.º 6
0
void hubo_daemonize()
{
    syslog( LOG_NOTICE, "Starting daemonization for CAN" );


	// Initialize signal variables
	hubo_sig_quit = 0;
	hubo_sig_usr1 = 0;
	hubo_sig_usr2 = 0;


	pid_t pid, child, sid, parent;
	int lfp = -1; // lockfile pointer

	// Already a daemon:
	if( getppid() == 1 ) return; // A value of 1 indicates that there is no parent process

    // Make sure lock directory exists
    struct stat st = {0};
    if( stat(LOCKDIR, &st) == -1 )
        mkdir(LOCKDIR, 0700);

	// Create the lockfile
	if( LOCKFILE && LOCKFILE[0] )
	{
		lfp = open(LOCKFILE,O_RDWR|O_CREAT|O_EXCL,0640);
		if( lfp < 0 )
		{
			syslog( LOG_ERR, "Unable to create lock file %s, code=%d (%s)",
				LOCKFILE, errno, strerror(errno) );
            syslog( LOG_ERR, " -- Run the kill script and try again!");
			exit(EXIT_FAILURE);
		}
	}
	
	
	// Drop the user if there is one
	if( getuid()==0 || geteuid()==0 )
	{
		struct passwd *pw = getpwnam(RUN_AS_USER);
		if( pw )
		{
			syslog( LOG_NOTICE, "Setting user to " RUN_AS_USER );
			setuid( pw->pw_uid );
		}
	}

	
	// Redirect the expected signals
	signal( SIGCHLD, hubo_sig_handler );
//	signal( SIGUSR1, hubo_sig_handler );
	signal( SIGUSR2, hubo_sig_handler );
	signal( SIGALRM, hubo_sig_handler );
	signal( SIGINT,  hubo_sig_handler );
	signal( SIGQUIT, hubo_sig_handler );
	signal( SIGTERM, hubo_sig_handler );


	//Specific to the fork
	signal( SIGUSR1, fork_sig_handler );

	// First fork
	child = fork();

	// Quit if a child process could not be made	
	if( child<0 )
	{
		syslog( LOG_ERR, "Unable to fork daemon, code=%d (%s)",
			errno, strerror(errno) );
		exit( EXIT_FAILURE );
	}

	// Quit if we get a good Process ID
	if( child>0 )
	{
		// Wait for confirmation from the child
		// or forcibly quit after 2 seconds elapse
		alarm(2);
		pause();
	
		exit( EXIT_FAILURE );
	}
	
	// If child == 0, then we are in the child process
	
	//Second fork
	pid = fork(); // pid will now represent the final process ID of the daemon
	
	// Quit if the final process could not be made
	if( pid<0 )
	{
		syslog( LOG_ERR, "Unable to fork daemon, code=%d (%s)",
			errno, strerror(errno) );
		exit( EXIT_FAILURE );
	}

	if( pid>0 )
	{
		// Kill the useless parent
		parent = getppid();
		kill( parent, SIGUSR1 );
		
		// Wait for confirmation from the daemon
		// or forcibly quit after 2 seconds elapse
		alarm(2);
		pause();

		exit( EXIT_FAILURE );	
	}

	// If pid == 0, then we are in the final process	
	
	// Now we execute as the final process
	parent = getppid();


	// TODO: Look into correctly handling these signals (SIG_DFL is default and SIG_IGN is ignore):
	signal( SIGCHLD, SIG_DFL ); // Child process dies
	signal( SIGTSTP, SIG_IGN ); // Stop (pause) signal
	signal( SIGTTOU, SIG_IGN ); // Trying to write to terminal
	signal( SIGTTIN, SIG_IGN ); // Trying to read from terminal
	signal( SIGHUP,  SIG_IGN ); // Hangup signal

	signal( SIGUSR1, hubo_sig_handler ); // Return SIGUSR1 to the standard sig handler	
	
	// Change file mode mask
	umask(0);

	// Create a new Session ID for the child process
	sid = setsid();
	if( sid<0 )
	{
		syslog( LOG_ERR, "Unable to create a new session, code=%d (%s)",
			errno, strerror(errno) );
		exit(EXIT_FAILURE);
	}

	
        // Change the current working directory to prevent the current directory from being locked
	if( (chdir("/")) < 0 )
	{
        syslog( LOG_ERR, "Unable to change directory, code=%d (%s)",
                errno, strerror(errno) );
		exit(EXIT_FAILURE);
	}

	struct stat logst = {0};
	if( stat(LOGDIR, &logst) == -1 )
		mkdir(LOGDIR, 0700);


	// Create files for logging, in case they don't exist already
    if(	!fopen( "/var/log/hubo/daemon-output", "w" ) ||
        !fopen( "/var/log/hubo/daemon-error", "w" ) )
	{
		syslog( LOG_ERR, "Unable to create log files, code=%d (%s)",
			errno, strerror(errno) );
        syslog( LOG_ERR, " -- Make sure /var/log/hubo/ directory exists!" );
		exit(EXIT_FAILURE);
	}

	// Redirect standard files to /dev/hubo-daemon
    if(	!freopen( "/var/log/hubo/daemon-output", "w", stdout ) ||
        !freopen( "/var/log/hubo/daemon-error", "w", stderr ) )
	{
		syslog( LOG_ERR, "Unable to stream output, code=%d (%s)",
			errno, strerror(errno) );
		exit(EXIT_FAILURE);
	}


	// Tell parent process that everything is okay
	kill( parent, SIGUSR1 );

	// RT
	struct sched_param param;
	// Declare ourself as a real time task

	param.sched_priority = MY_PRIORITY;
	if(sched_setscheduler(0, SCHED_FIFO, &param) == -1) {
		perror("sched_setscheduler failed");
		exit(-1);
	}

	// Lock memory

	if(mlockall(MCL_CURRENT|MCL_FUTURE) == -1) {
		perror("mlockall failed");
		exit(-2);
	}

	// Pre-fault our stack
	stack_prefault();

	syslog( LOG_NOTICE, "Daemonization finished - Process Beginning" );
}
Exemplo n.º 7
0
int main() {
	struct sched_param param;

        signal(SIGTERM, catch_signal);
        signal(SIGINT, catch_signal);

	param.sched_priority = 49;
        if(sched_setscheduler(0, SCHED_FIFO, &param) == -1) {
                perror("sched_setscheduler failed");
                exit(-1);
        }


        if(mlockall(MCL_CURRENT|MCL_FUTURE) == -1) {
                perror("mlockall failed");
                exit(-2);
        }

	stack_prefault();

	err=config_open("/var/local/rpicopter.config");
	if (err<0) {
            	printf("Failed to initiate config! [%s]\n", strerror(err));	
		return -1;
	}

	err=flog_open("/var/local/");
	if (err<0) {
            	printf("Failed to initiate log! [%s]\n", strerror(err));	
		return -1;
	}

	err = sc_open();
        if (err != 0) {
            printf("Failed to initiate speedcontroller! [%s]\n", strerror(err));	
	    return -1;
	}

	err=ms_open(GYRO_RATE);
        if (err != 0) {
            printf("Failed to initiate gyro! [%s]\n", strerror(err));	
	    return -1;
	}

	err=rec_open();
	if (err<0) {
            	printf("Failed to initiate receiver! [%s]\n", strerror(err));	
		return -1;
	}

/*
	err=bs_open();
	if (err<0) {
            	printf("Failed to initiate pressure sensor! [%s]\n", strerror(err));	
		return -1;
	}
*/
	printf("Waiting for MPU calibration... \n");
	delay_ms(1000);
	controller_stable(NULL);
	return 0;
}
Exemplo n.º 8
0
int main(int argc, char **argv) {

	int vflag = 0;
	int c;


	char* ach_chan = HUBO_CHAN_REF_FILTER_NAME;
	int i = 1;
	while(argc > i) {
		if(strcmp(argv[i], "-d") == 0) {
			debug = 1;
		}
		if(strcmp(argv[i], "-r") == 0) {
			ach_chan = HUBO_CHAN_REF_NAME;
		}
		i++;
	}

	/* RT */
	struct sched_param param;
	/* Declare ourself as a real time task */
	param.sched_priority = MY_PRIORITY;
	if(sched_setscheduler(0, SCHED_FIFO, &param) == -1) {
		perror("sched_setscheduler failed");
		exit(-1);
	}

	/* Lock memory */
	if(mlockall(MCL_CURRENT|MCL_FUTURE) == -1) {
		perror("mlockall failed");
		exit(-2);
	}

	/* Pre-fault our stack */
	stack_prefault();


	/* open ach channel */
	//int r = ach_open(&chan_hubo_ref, HUBO_CHAN_REF_NAME , NULL);
	int r = ach_open(&chan_hubo_ref, ach_chan , NULL);
	assert( ACH_OK == r );

	r = ach_open(&chan_hubo_state, HUBO_CHAN_STATE_NAME , NULL);
	assert( ACH_OK == r );


        // get initial values for hubo
        struct hubo_ref H_ref;
        struct hubo_init_cmd H_init;
        struct hubo_state H_state;
        struct hubo_param H_param;
        memset( &H_ref,   0, sizeof(H_ref));
        memset( &H_init,  0, sizeof(H_init));
        memset( &H_state, 0, sizeof(H_state));
        memset( &H_param, 0, sizeof(H_param));

        usleep(250000);

        // set default values for Hubo
        setJointParams(&H_param, &H_state);

        huboLoop(&H_param);

	pause();
	return 0;

}
Exemplo n.º 9
0
void daemonize(const char *daemon_name)
{
    char pbuff[100];

    sprintf(gdaemon_name, "%s", daemon_name);
//    sprintf(pbuff, "Starting daemonization for %s", daemon_name);
    syslog( LOG_NOTICE, "Starting daemonization for %s", daemon_name );

    // Initialize signal variables;
    daemon_sig_quit = 0;
    daemon_sig_usr1 = 0;
    daemon_sig_usr2 = 0;


    pid_t pid, child, sid, parent;
    int lfp = -1; // lockfile pointer


    // Already a daemon:
    if( getppid() == 1 ) return; // A value of 1 indicates that there is no parent process


    // Create the lockfile
    sprintf(lockfile, "/var/lock/%s", daemon_name);
    if( lockfile && lockfile[0] )
    {
        lfp = open(lockfile,O_RDWR|O_CREAT|O_EXCL,0640);
        if( lfp < 0 )
        {
            syslog( LOG_ERR, "Unable to create lock file %s, code=%d (%s)"
                             "  Check if daemon already exists!",
                    lockfile, errno, strerror(errno) );
            exit( EXIT_FAILURE );
        }
    }


    // Drop the user if there is one
    if( getuid()==0 || geteuid()==0 )
    {
        struct passwd *pw = getpwnam(RUN_AS_USER);
        if( pw )
        {
            syslog( LOG_NOTICE, "Setting user to " RUN_AS_USER );
            setuid( pw->pw_uid );
        }
    }


    // Redirect the expected signals
    signal( SIGCHLD, daemon_sig_handler );
//	signal( SIGUSR1, daemon_sig_handler );
    signal( SIGUSR2, daemon_sig_handler );
    signal( SIGALRM, daemon_sig_handler );
    signal( SIGINT,  daemon_sig_handler );
    signal( SIGQUIT, daemon_sig_handler );
    signal( SIGTERM, daemon_sig_handler );


    // Specific to the fork
    signal( SIGUSR1, fork_sig_handler );

    // First fork
    child = fork();


    // Quit if a child process could not be made
    if( child<0 )
    {
        syslog( LOG_ERR, "Unable to fork daemon, code=%d (%s)",
                errno, strerror(errno) );
        exit( EXIT_FAILURE );
    }

    // Quit if we get a good Process ID
    if( child>0 )
    {
        // Wait for confirmation from the child
        // or forcibly quit after 2 seconds
        alarm(2);
        pause();

        exit( EXIT_FAILURE );
    }

    // If child == 0, then we are in the child process

    // Second fork
    pid = fork(); // pid will now represent the final Process ID of the daemon

    // Quit if the final process could not be made
    if( pid<0 )
    {
        syslog( LOG_ERR, "Unable to fork daemon, code=%d (%s)",
                errno, strerror(errno) );
        exit( EXIT_FAILURE );
    }

    if( pid>0 )
    {
        // Kill the useless parent
        parent = getppid();
        kill( parent, SIGUSR1 );

        // Wait for confirmation from the daemon
        // or forcibly quit after 2 seconds
        alarm(2);
        pause();

        exit( EXIT_FAILURE );
    }

    // If pid == 0, then we are in the final process

    // Now we execute as the final process
    parent = getppid();


    // TODO: Look into correctly handling these signals (SIG_DFL is default and SIG_IGN is ignore):
    signal( SIGCHLD, SIG_DFL ); // Child process dies
    signal( SIGTSTP, SIG_IGN ); // Stop (pause) signal
    signal( SIGTTOU, SIG_IGN ); // Trying to write to terminal
    signal( SIGTTIN, SIG_IGN ); // Trying to read from terminal
    signal( SIGHUP,  SIG_IGN ); // Hangup signal

    signal( SIGUSR1, daemon_sig_handler ); // Return SIGUSR1 to the standard sig handler

    // Change file mode mask
    umask(0);

    // Create a new Session ID for the child process
    sid = setsid();
    if( sid<0 )
    {
        syslog( LOG_ERR, "Unable to create new session, code=%d (%s)",
                errno, strerror(errno) );
        exit( EXIT_FAILURE );
    }

    // Change the current working directory to prevent the current directory from being locked
    if( (chdir("/")) < 0 )
    {
        syslog( LOG_ERR, "Unable to change directory, code=%d (%s)",
                errno, strerror(errno) );
        exit( EXIT_FAILURE );
    }


    // Create files for logging, in case they don't exist already
    char outfile[100];
    char errfile[100];
    sprintf(outfile, "/var/log/daemon/%s-output", daemon_name);
    sprintf(errfile,  "/var/log/daemon/%s-error", daemon_name);
    if(     !fopen( outfile, "w" ) ||
            !fopen( errfile, "w" ) )
    {
        syslog( LOG_ERR, "Unable to create log files, code=%d (%s)",
                errno, strerror(errno) );
        exit(EXIT_FAILURE);
    }


    // Redirect standard files to /var/log/daemon/xx
    if(     !freopen( outfile, "w", stdout ) ||
            !freopen( errfile, "w", stderr ) )
    {
        syslog( LOG_ERR, "Unable to stream output, code=%d (%s)",
                errno, strerror(errno) );
        exit( EXIT_FAILURE );
    }


    // Tell parent process that everything is okay
    kill( parent, SIGUSR1 );

    // Real Time
    struct sched_param param;
    // Declare ourself as a real time task

    param.sched_priority = MY_PRIORITY;
    if( sched_setscheduler(0, SCHED_FIFO, &param) == -1 )
    {
        fprintf(stderr, "sched_setscheduler Failed!\n");
        exit( EXIT_FAILURE );
    }

    // Lock memory

    if(mlockall(MCL_CURRENT|MCL_FUTURE) == -1)
    {
        fprintf(stderr, "mlockall Failed!\n");
        exit( EXIT_FAILURE );
    }

    // Pre-fault our stack
    stack_prefault();

    syslog( LOG_NOTICE, "Daemonization finished - Process Beginning" );
}
Exemplo n.º 10
0
void readFTDI()
{
	struct timespec t;
    struct sched_param param;
    int interval = 5000000 ; /* 5000000 ns */
	 
	 
	struct timeval start, end;
	
	 uint64_t millis;

   long mtime, seconds;

   double useconds = 0.0;   
   
   int id = 0;
   int i;
   sqlite3 *db;
   sqlite3_stmt * stmt;
   
   char * sErrMsg = 0;
	
	
   char *zErrMsg = 0;
   int rc;
	 
	 
	 
	 
	    /* Declare ourself as a real time task */

        param.sched_priority = MY_PRIORITY;
        if(sched_setscheduler(0, SCHED_FIFO, &param) == -1) {
                perror("sched_setscheduler failed");
                exit(-1);
        }

        /* Lock memory */

        if(mlockall(MCL_CURRENT|MCL_FUTURE) == -1) {
                perror("mlockall failed");
                exit(-2);
        }

        /* Pre-fault our stack */

        stack_prefault();

       
		
		
		
		 rc = sqlite3_open("test.db", &db);
   if( rc ){
      fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
      exit(0);
   }else{
      fprintf(stderr, "Opened database successfully\n");
	  
	  sqlite3_exec(db, TABLE, NULL, NULL, &sErrMsg);  
	  
	  // Free table
	   sqlite3_exec(db, "delete from TTC", NULL, NULL, &sErrMsg);  
	  
	  
   }
   
   sqlite3_exec(db, "BEGIN TRANSACTION", NULL, NULL, &sErrMsg);
   
   char buffer[] = "INSERT INTO TTC(millis) VALUES (?1)";
	
	sqlite3_prepare_v2(db, buffer, strlen(buffer), &stmt, NULL);
		
		 clock_gettime(CLOCK_MONOTONIC ,&t);
        /* start after one second */
        t.tv_sec++;
		
		
		 while( keepRunning ) 
		{
            /* wait until next shot */
            clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &t, NULL);

            /* do the stuff */
		    gettimeofday(&start, NULL);
			
		   // useconds =  start.tv_sec/1.0 + start.tv_usec/(1000000.0);
		   
		 //  millis = (start.tv_sec * (uint64_t)1000) + (start.tv_usec / 1000);
		 
		 millis = (start.tv_sec * (uint64_t)1000000) + (start.tv_usec);
		
		
		// sqlite3_bind_int(stmt, 1, ++id);
		 sqlite3_bind_int64(stmt, 1, millis);
 
		if (sqlite3_step(stmt) != SQLITE_DONE)
		{
			printf("Commit Failed!\n");
		}
 
		sqlite3_reset(stmt);
			
				
				
				
			
				

                /* calculate next shot */
                t.tv_nsec += interval;

                while (t.tv_nsec >= NSEC_PER_SEC) 
				{
                       t.tv_nsec -= NSEC_PER_SEC;
                        t.tv_sec++;
                }
		}
		
		
		  sqlite3_exec(db, "END TRANSACTION", NULL, NULL, &sErrMsg);  
   
   sqlite3_finalize(stmt);
   
   printf("Write OK\r\n");
   
   
   sqlite3_close(db);
	 
	
		
}
Exemplo n.º 11
0
int main(int argc, char *argv[])
{
        struct sched_param param;
	pthread_t allthr[MAX_THR];
	int i, ret; 

	while((i=getopt(argc, argv, "n:i:s:hd")) != EOF) {
		switch(i) {
		case 'h':
			usage();
			return 0;
		case 'd':
			det = 1; 
			break; 
		case 'n':
			max_thr = atoi(optarg);
			if (max_thr >= MAX_THR)
				errx(1, "no more than %d threads", MAX_THR);
			break;
		case 'i': 
			iteration = atoi(optarg); 
			break; 
		case 's':
			size = atoi(optarg); 
			break; 
		default:
			errx(1, "invalid option");
		}
	}

        param.sched_priority = MY_PRIORITY;
        if(sched_setscheduler(0, SCHED_RR, &param) == -1) {
                perror("sched_setscheduler failed");
                // exit(-1);
        }

        if(mlockall(MCL_CURRENT|MCL_FUTURE) == -1) {
                perror("mlockall failed");
                // exit(-2);
        }

        /* Pre-fault our stack */
        stack_prefault();

	// pthread_mutex_init(&(mutexsum.mutex), NULL);

	det_init(argc, argv);
	det_lock_init(&mutexsum); 
	if ( det ) { 
		det_create(allthr+0, NULL, my_worker1, (void *)(unsigned long)0);
		det_create(allthr+1, NULL, my_worker2, (void *)(unsigned long)1);
		det_enable(); // enable deterministic execution 
	} else { 
		pthread_create(allthr+0, NULL, my_worker1, (void *)(unsigned long)0);
		pthread_create(allthr+1, NULL, my_worker2, (void *)(unsigned long)1); 
	}

	for (i = 0; i < 2; i++) {
		pthread_join(allthr[i], NULL);
	}

	return 0; 
}
int main(int argc, char **argv) {

        int vflag = 0;
        int c;


        int i = 1;
        while(argc > i) {
                if(strcmp(argv[i], "-d") == 0) { // debug
                        debug = 1;
                }
                if(strcmp(argv[i], "-n") == 0) {
			if( argc > (i+1)) {
	                        fileName = argv[i+1];
				printf("Trejectory file changed\n");
			}
			else {
				printf("ERROR: File name not changed\n");
			}
                }
		if(strcmp(argv[i], "-f") == 0) {
			int j = i+1;
			if( argc > (j)) {
				if(strcmp(argv[j],      "100") == 0) { interval = 10000000; /* 100 hz (0.01 sec) */ }
				else if(strcmp(argv[j], "50") == 0)  { interval = 20000000; /* 50 hz (0.02 sec)  */ }
				else if(strcmp(argv[j], "25") == 0)  { interval = 40000000; /* 25 hz (0.04 sec)  */ }
				else if(strcmp(argv[j], "10") == 0)  { interval = 100000000; /* 25 hz (0.04 sec)  */}
				else if(strcmp(argv[j], "200") == 0) { interval = 5000000;  /* 200 hz (0.005 sec)*/ }
				else if(strcmp(argv[j], "500") == 0) { interval = 2000000;  /* 500 hz (0.002 sec)*/ }
				else { printf("ERROR: Frequency not changed\n"); }
			}
			else {
				printf("ERROR: Frequency not changed\n");
			}
		}
		if(strcmp(argv[i], "-h") == 0) {
                	printf("------------------------------------------\n");
                	printf("-----------hubo-read-trajectory-----------\n");
                	printf("------------------------------------------\n");
			printf("\n");
			printf("Usage: ./hubo-read-trajectory -f 100 -n fileName.traj\n");
			printf("\tOptions:\n");
			printf("\t\t-h   help menu\n");
			printf("\t\t-n   change trajectory\n");
			printf("\t\t\t\tdefault: no file\n");
			printf("\t\t\t\tatguements: filename\n");
			printf("\t\t-f   change frequency\n");
			printf("\t\t\tdefault: 25hz\n");
			printf("\t\t\tatguements: frequency\n");
			printf("\t\t\t\toptions (hz):\n");
			printf("\t\t\t\t\t10\n");
			printf("\t\t\t\t\t25\n");
			printf("\t\t\t\t\t50\n");
			printf("\t\t\t\t\t100\n");
			printf("\t\t\t\t\t200\n");
			printf("\t\t\t\t\t500\n");
			printf("\n");
			printf("File format (Each Column)\n");
			printf("\tRHY RHR RHP RKN RAP RAR LHY LHR LHP LKN LAP LAR RSP RSR RSY REB RWY RWR RWP LSP LSR LSY LEB LWY LWR LWP NKY NK1 NK2 WST RF1 RF2 RF3 RF4 RF5 LF1 LF2 LF3 LF4 LF5\n");
			printf("\n");
			return 0;
		}
		i++;
        }
	

	printf("\n");
	printf("-----------------------------\n");
	printf("Using file: %s \n",fileName);
	printf("Sampling frequency %f\n", 1/((double)interval/(double)NSEC_PER_SEC));
	printf("-----------------------------\n");
	printf("\n");
        /* RT */
        struct sched_param param;
        /* Declare ourself as a real time task */
        param.sched_priority = MY_PRIORITY;
        if(sched_setscheduler(0, SCHED_FIFO, &param) == -1) {
                perror("sched_setscheduler failed");
                exit(-1);
        }

        /* Lock memory */
        if(mlockall(MCL_CURRENT|MCL_FUTURE) == -1) {
                perror("mlockall failed");
                exit(-2);
        }

        /* Pre-fault our stack */
        stack_prefault();


        /* open ach channel */
        int r = ach_open(&chan_hubo_ref, HUBO_CHAN_REF_NAME , NULL);
        assert( ACH_OK == r );
 
	huboLoop();
//        pause();
        return 0;

}
int main()
{
	struct sched_param param;
	param.sched_priority = 97;
    	if(sched_setscheduler(0, SCHED_FIFO, &param) == -1) 
	{
    		perror("sched_setscheduler failed");
        	exit(-1);
   	}
		/* Lock memory */

    	if (mlockall(MCL_CURRENT | MCL_FUTURE) == -1)
	{
        	perror("mlockall failed");
        	exit(-2);
	}
		/* Pre-fault our stack */

    	stack_prefault();
	
	struct timespec t;
	clock_gettime(CLOCK_MONOTONIC, &t);
	t.tv_sec++;

	char *dev;
	dev = WATCHDOGDEV;
	int fd = open(dev, O_RDWR);
	int interval=1;

  	int n = 0;

  	struct sockaddr_in serv_addr;
  	char *message ;
  	int num;

	signal(SIGPIPE, SIG_IGN);
  	signal(SIGINT,Sa_handler);
  	char recvBuff[68];
  	char sendBuff[68];
  	memset(recvBuff, '0',sizeof(recvBuff));
  	if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
  	{
    		printf("\n Error : Could not create socket \n");
    		return -1 ;
  	}

  	memset(&serv_addr, '0', sizeof(serv_addr));
  	serv_addr.sin_family = AF_INET;
  	serv_addr.sin_port = htons(5000);

  	if(inet_pton(AF_INET,"192.168.7.1", &serv_addr.sin_addr)<=0)
  	{
    		printf("\n inet_pton error occured\n");
    		return -1;
  	}
  	if( connect(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0)
  	{
    		printf("\n Error : Connect Failed \n");
    		return -1;
  	}
  	if (ioctl(fd, WDIOC_SETTIMEOUT, &interval) != 0) 
	{
         	fprintf(stderr,"Error: Set watchdog interval failed\n");
         	exit(EXIT_FAILURE);
	}
  	while(1)
  	{
		ioctl(fd, WDIOC_KEEPALIVE, NULL);
         	fprintf(stdout, "Kick watchdog through IOCTL\n");
		clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &t, NULL);

    		struct state st;
    		signal(SIGINT,Sa_handler);
    		int k,g;
    
    
		memset(recvBuff, '0', sizeof(recvBuff));
		if((num = recv(sockfd, &k, sizeof(k),0))<=0)
        	{
            		printf("Either Connection Closed or Error\n");
            		close(sockfd);
            		exit(1);
        	}
		printf("k=%d \n",k);
        	if((num = recv(sockfd, recvBuff, k,0))<=0)
        	{
            		printf("Either Connection Closed or Error\n");
            		close(sockfd);
            		exit(1);
        	}

        	recvBuff[num] = '\0';
        	printf("Client:Message Received From Server -  %s\n",recvBuff);
        	sscanf(strtok(recvBuff , ", "), "%lf", &st.elevation);
        	sscanf(strtok(NULL, ", "), "%lf",&st.pitch);
       		sscanf(strtok(NULL, ", "), "%lf",&st.travel);
		sscanf(strtok(NULL, ", "), "%lf",&st.d_elevation);
        	sscanf(strtok(NULL, ", "), "%lf",&st.d_pitch);
    		sscanf(strtok(NULL, ", "), "%lf",&st.d_travel);
		printf("client:state received \n");
		printf("elevation %lf\n",st.elevation);
		printf("pitch %lf\n",st.pitch);
		printf("travel %lf\n",st.travel);
		printf("d_elevation %lf\n",st.d_elevation);
		printf("d_pitch %lf\n",st.d_pitch);
		printf("d_travel %lf\n",st.d_travel);
		struct command comm= controller_safety(st);
		printf(" u1= %d  u2= %d  \n",comm.u1,comm.u2); 
		sprintf(sendBuff,"complex, %f, %f, ",comm.u1,comm.u2); 
		g=strlen(sendBuff);
		if ((send(sockfd,&g,sizeof(int),0))== -1)
        	{
                 	fprintf(stderr, "Failure Sending Message\n");
                 	close(sockfd);
                 	break;
        	}
		if((send(sockfd,sendBuff,g,0))==-1)
      		{
        		printf("Failure in sending Message\n");
        		close(sockfd);
        		exit(1);
        	}

		t.tv_nsec += interval;

                while (t.tv_nsec >= NSEC_PER_SEC)
		{
                       t.tv_nsec -= NSEC_PER_SEC;
                        t.tv_sec++;
		}
      
        
    	}
    	close(sockfd);
    	return -1;
}
Exemplo n.º 14
0
int main(int argc, char **argv)
{
  #define MAX_BITS (49) // 49-bit word.
  #define MAX_DATA (1*1024) // 1 KB data buffer of 49-bit data words - ~70 seconds @ 1 kHz.
  char data[MAX_DATA*MAX_BITS], word[MAX_BITS];
  //int (*data_ptr)[MAX_DATA][MAX_BITS] = &data, (*bit_ptr)[MAX_BITS] = data;
  int i = 0, j = 0, flag = 0, bit_cnt = 0, data_cnt = 0, zones, cmd;
  int data0,data1,data2,data3,data4,data5,data6;
  char year3[2],year4[2],month[2],day[2],hour[2],minute[2];
  FILE *out_file;
  struct sched_param param;
  struct timespec t, tmark;
  char msg[100] = "", oldMsg[100] = "";
  struct fifo dataFifo;

  /* Declare ourself as a real time task */
  param.sched_priority = MY_PRIORITY;
  if(sched_setscheduler(0, SCHED_FIFO, &param) == -1) {
    perror("sched_setscheduler failed");
    exit(-1);
  }

  /* Lock memory */
  if(mlockall(MCL_CURRENT|MCL_FUTURE) == -1) {
    perror("mlockall failed");
    exit(-2);
  }

  /* Pre-fault our stack */
  stack_prefault();

  for(i = 0; i < MAX_DATA*MAX_BITS; i++)
    data[i] = '0';

  for(i = 0; i < MAX_BITS; i++)
    word[i] = '0';

  // Set up gpio pointer for direct register access
  setup_io();

  // Set up FIFO
  fifo_init(&dataFifo, data, MAX_DATA*MAX_BITS);

  // Set pin direction
  INP_GPIO(PI_DATA_OUT); // must use INP_GPIO before we can use OUT_GPIO
  OUT_GPIO(PI_DATA_OUT);
  INP_GPIO(PI_DATA_IN);
  INP_GPIO(PI_CLOCK_IN);

  // Set PI_DATA_OUT pin low.
  GPIO_CLR = 1<<PI_DATA_OUT;

  clock_gettime(CLOCK_MONOTONIC, &t);
  tmark = t;
  while (1) {
//printf("pi_data:%i,data[%i][%i]:%i\n",GET_GPIO(PI_DATA_IN),data_cnt,bit_cnt,data[data_cnt][bit_cnt]);
    t.tv_nsec += INTERVAL;
    tnorm(&t);
    clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &t, NULL);
    if (GET_GPIO(PI_CLOCK_IN) == PI_CLOCK_HI) flag = 1;
    else if ((GET_GPIO(PI_CLOCK_IN) == PI_CLOCK_LO) && (flag == 1)) {
      if (ts_diff(&t, &tmark) > 1100000) { // new word
        bit_cnt = 0; // start new word
        fifo_write(&dataFifo, word, MAX_BITS); // write current word to FIFO
/*printf("%04i: wrote ", data_cnt);
for(i=0; i<MAX_BITS; i++) printf("%c", word[i]);
printf(" to dataFifo\n");*/
        data_cnt++;
      }
      tmark = t;
      flag = 0;
      t.tv_nsec += INTERVAL;
      tnorm(&t);
      t.tv_nsec += INTERVAL;
      tnorm(&t);
      t.tv_nsec += INTERVAL;
      tnorm(&t);
      t.tv_nsec += INTERVAL;
      tnorm(&t);
      t.tv_nsec += INTERVAL;
      tnorm(&t);
      /*t.tv_nsec += INTERVAL;
      tnorm(&t);
      t.tv_nsec += INTERVAL;
      tnorm(&t);
      t.tv_nsec += INTERVAL;
      tnorm(&t);
      t.tv_nsec += INTERVAL;
      tnorm(&t);
      t.tv_nsec += INTERVAL;
      tnorm(&t);*/
      clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &t, NULL); // wait 50 uS for valid data
      word[bit_cnt++] = (GET_GPIO(PI_DATA_IN) == PI_DATA_HI) ? '0' : '1';
    }
    if (data_cnt == MAX_DATA)
      break;
  }

  // decode and write to file
  if ( (out_file = fopen ("data", "w")) == NULL )
    printf ("*** data could not be opened. \n" );
  else
    for ( i = 0; i < MAX_DATA; i++ ) {
      strcpy(msg, "");
      fifo_read(&dataFifo, word, MAX_BITS);
/*printf("%04i: read  ", i);
for(j=0; j<MAX_BITS; j++) printf("%c", word[j]);
printf(" from dataFifo\n");*/
      cmd = getBinaryData(word,0,8);
      if (cmd == 0x05) {
        strcpy(msg, "LED Status: ");
        if (getBinaryData(word,12,1)) strcat(msg, "Error ");
        if (getBinaryData(word,13,1)) strcat(msg, "Bypass ");
        if (getBinaryData(word,14,1)) strcat(msg, "Memory ");
        if (getBinaryData(word,15,1)) strcat(msg, "Armed ");
        if (getBinaryData(word,16,1)) strcat(msg, "Ready ");
      }
      else if (cmd == 0xa5) {
        sprintf(year3, "%d", getBinaryData(word,9,4));
        sprintf(year4, "%d", getBinaryData(word,13,4));
        sprintf(month, "%d", getBinaryData(word,19,4));
        sprintf(day, "%d", getBinaryData(word,23,5));
        sprintf(hour, "%d", getBinaryData(word,28,5));
        sprintf(minute, "%d", getBinaryData(word,33,6));
        strcpy(msg, "Date: 20");
        strcat(msg, year3);
        strcat(msg, year4);
        strcat(msg, "-");
        strcat(msg, month);
        strcat(msg, "-");
        strcat(msg, day);
        strcat(msg, " ");
        strcat(msg, hour);
        strcat(msg, ":");
        strcat(msg, minute);
      }
      else if (cmd == 0x27) {
        strcpy(msg, "Zone1: ");
        zones = getBinaryData(word,41,8);
        if (zones & 1) strcat(msg, "1 ");
        if (zones & 2) strcat(msg, "2 ");
        if (zones & 4) strcat(msg, "3 ");
        if (zones & 8) strcat(msg, "4 ");
        if (zones & 16) strcat(msg, "5 ");
        if (zones & 32) strcat(msg, "6 ");
        if (zones & 64) strcat(msg, "7 ");
        if (zones & 128) strcat(msg, "8 ");
      }
      else if (cmd == 0x2d) {
        strcpy(msg, "Zone2: ");
        zones = getBinaryData(word,41,8);
        if (zones & 1) strcat(msg, "9 ");
        if (zones & 2) strcat(msg, "10 ");
        if (zones & 4) strcat(msg, "11 ");
        if (zones & 8) strcat(msg, "12 ");
        if (zones & 16) strcat(msg, "13 ");
        if (zones & 32) strcat(msg, "14 ");
        if (zones & 64) strcat(msg, "15 ");
        if (zones & 128) strcat(msg, "16 ");
      }
      else if (cmd == 0x34) {
        strcpy(msg, "Zone3: ");
        zones = getBinaryData(word,41,8);
        if (zones & 1) strcat(msg, "9 ");
        if (zones & 2) strcat(msg, "10 ");
        if (zones & 4) strcat(msg, "11 ");
        if (zones & 8) strcat(msg, "12 ");
        if (zones & 16) strcat(msg, "13 ");
        if (zones & 32) strcat(msg, "14 ");
        if (zones & 64) strcat(msg, "15 ");
        if (zones & 128) strcat(msg, "16 ");
      }
      else if (cmd == 0x3e) {
        strcpy(msg, "Zone4: ");
        zones = getBinaryData(word,41,8);
        if (zones & 1) strcat(msg, "9 ");
        if (zones & 2) strcat(msg, "10 ");
        if (zones & 4) strcat(msg, "11 ");
        if (zones & 8) strcat(msg, "12 ");
        if (zones & 16) strcat(msg, "13 ");
        if (zones & 32) strcat(msg, "14 ");
        if (zones & 64) strcat(msg, "15 ");
        if (zones & 128) strcat(msg, "16 ");
      }
      else
        strcpy(msg, "Unknown command.");
      data0 = getBinaryData(word,0,8);  data1 = getBinaryData(word,8,8);
      data2 = getBinaryData(word,16,8); data3 = getBinaryData(word,24,8);
      data4 = getBinaryData(word,32,8); data5 = getBinaryData(word,40,8);
      data6 = getBinaryData(word,48,2);
      if (strcmp(msg, oldMsg) != 0) {
        fprintf (out_file, "data[%i],cmd:0x%02x,%s\n", i, cmd, msg);
        fprintf (out_file, "***data-all: 0x%02x 0x%02x 0x%02x 0x%02x 0x%02x 0x%02x 0x%02x\n",data0,data1,data2,data3,data4,data5,data6);
        strcpy(oldMsg, msg);
      }
    }
  fclose (out_file);

  /* Unlock memory */
  if(munlockall() == -1) {
    perror("munlockall failed");
    exit(-2);
  }

  return 0;
} // main
Exemplo n.º 15
0
int main(int argc, char* argv[]) {


	cout<<"beta ="<<beta<<endl;
	if (argc < 6) {
		cout
				<< "invalid format: <tasksets><hyperperiod length><computation utilization><interval> <seed>"
				<< endl;
		exit(1);
	}

#if(MATLAB_ENABLE)
	ep =engOpen(NULL);
	if(ep==0)
	{
		cout<<"connection with matlab engine failed"<<endl;

	}
#endif

#if (RT_ENABLE)
	struct sched_param param;

	signal(SIGINT, int_handler);
	freq_set(CORE,"performance");
	cpu_set_t mask;
	CPU_ZERO(&mask);
	CPU_SET(1,&mask);
	cout<<"setting affinity to processor "<<CORE<<endl;
	if(sched_setaffinity(0,CPU_COUNT(&mask),&mask)==-1)
	{
		perror("sched_setscheduler failed");
		exit(-1);
	}
	param.sched_priority = MY_PRIORITY; //priority for the scheduler
	if (sched_setscheduler(0, SCHED_FIFO, &param) == -1) { //scheduler has cooporative scheduling
		perror("sched_setscheduler failed");
		exit(-1);
	}

	//lock memory
	if(mlockall(MCL_CURRENT | MCL_FUTURE)==-1)
	{
		perror("mlockall failed");
		exit(-2);
	}
	stack_prefault();
#endif

	corrected_threshold = corrected_temperature(THRESHOLD);

	cout<<"beta "<<beta<<" corrected threshold "<<corrected_threshold<<endl;
//	exit(1);

	int iter = atoi(argv[1]);
	int hyperperiod = atoi(argv[2]);

	int comp_util = atoi(argv[3]);
	int sched_interval=atoi(argv[4]);
	seed = atoi(argv[5]);

	string task_file;
	if (argc == 7) {
		task_file = argv[6];
	}
	srand(seed);

	vector<task> tasks;
	vector<schedule> edf;
	vector<task> scaled_tasks;
	vector<double> speeds;
	vector<schedule> edf2;
	vector<task> discrete_scaled;
	vector<schedule> edf3;
	vector<schedule> edl2;
	vector<schedule> i_schedule;

	vector<schedule> opt;
	vector<schedule> opt_exact;

	vector<float> possible_speeds;

	vector<double> h_speed;
	vector<double> s_speed;

	vector<double> m_speed;

	vector<double> i_speed;
	vector<double> i_speed_temp;

	vector<slack> slacks;
	vector<schedule> edl;

	vector<task> scaled_max_first;
	vector<task> scaled_static;
	vector<task> scaled_matlab;
	vector<schedule> edf_max_first;
	vector<schedule> edf_static;
	vector<schedule> edf_matlab;

	for (int z = 0; z < iter; z++) {
		thermal_optimal = 0;
		// generate_tasksets(&tasks,1,hyperperiod,50,100);
		if (argc == 6) {
//			generate_tasksets(&tasks, 1, hyperperiod, comp_util, comp_util);
		} else {
			read_tasksets(&tasks, task_file);
		}

		int_pointer=&tasks;


#if(OPT_ENABLE)
		call_gams();
		store_opt(&tasks);
#endif


		double t_util;
//		edf_schedule(&tasks, &edf);
//		consolidate_schedule(&edf, &tasks);

		thermal_optimal = 1;
//		compute_profile(&edf, &tasks, t_util);
//		edl_schedule2(&edl2, &edf);
//		consolidate_schedule(&edl2, &tasks);

//		populate_slacks(&slacks, &edf);
//		edl_schedule(&edl, &edf, &tasks, &slacks);
//		consolidate_schedule(&edl, &tasks);

#if(INST_ENABLE)

		cout<<"entering optimize instances"<<endl;
		vector<int>slack;
		optimize_instances(&i_speed,&tasks,&i_schedule,&edl, &edl2,MIN_SPEED,MAX_SPEED,&i_speed_temp,&slack);
		cout<<"exiting optimize instances"<<endl;

		cout<<"printing optimal schedule"<<endl;
		for(unsigned int i=0;i<i_schedule.size();i++)
		{
			cout<<"task "<<i_schedule[i].task_id<<" start "<<i_schedule[i].start<<" end "<<i_schedule[i].end
			<<" speed "<<i_speed[i]<<" power "<<tasks[i_schedule[i].task_id].power*pow(i_speed[i],3.0)<<
			" slack "<<slack[i]<<" deadline "<<(i_schedule[i].start/tasks[i_schedule[i].task_id].period+1)*tasks[i_schedule[i].task_id].period<<endl;
		}

		verify(&i_schedule,&tasks,&i_speed);
#endif

#if(SLACK_ENABLE)

		verify(&edl, &tasks);

		opt_schedule_exact(&opt_exact, &tasks);

		opt_schedule(&opt, &tasks, &edl);
#endif

#if(MAX_ENABLE)

		vector<float_task>ft;

		vector<long_task>ltasks;
		vector<long_schedule>lschedule;
		vector<long_schedule>lschedule2;
		vector<long_schedule>lschedule3;

		vector<float_schedule>wsch;
		vector<float_schedule>wsch2;
		vector<float_schedule>wsch3;
		vector<float_schedule>fedf;
		vector<schedule>o_sch;
		vector<interval_s>intervals;

	//	cout<<"generating task set "<<endl;

		float thermal_util=0.98;
		float computation_util=1.0;
		int num_tasks=rand() % (11) + 10;


//		generate_taskset(&ft,  1000, num_tasks,computation_util, thermal_util);
//		w2fq_task_convert(&ltasks, &ft);
//		generate_intervals_gps(&intervals, &ltasks);/
//		w2fq_schedule(&lschedule, &ltasks,&intervals,0);
//		edf_schedule(&ft,&fedf);

//		w2fq_schedule_convert(&wsch, &lschedule);
		//cout<<" printing float schedule "<<endl;
//		compute_profile(&wsch, &ft, 1);
//		compute_profile(&fedf, &ft, 4);


//		instance_override(&ft);

//		dynamic_instance_schedule(&lschedule2, &ltasks,&intervals,1);
//		w2fq_schedule_convert(&wsch2, &lschedule2);
//		compute_profile(&wsch2, &ft, 2);

//		dynamic_instance_schedule(&lschedule3, &ltasks,&intervals,2);
//		w2fq_schedule_convert(&wsch3, &lschedule3);
//		compute_profile(&wsch3, &ft, 3);


		ft.clear();
		ltasks.clear();
		lschedule.clear();
		fedf.clear();
		wsch.clear();

		float power;
		power=rand()/(float)RAND_MAX*20.00;
		power=power+18.00;

		cout<<power<<endl;

		float comp_util=1.5;//0.6;
		ofstream taskfile("taskset_file");
		int ** matrix;
		matrix = new int *[20];

		for(unsigned int i=0;i<20;i++)
		{
			matrix[i] =new int[20];
		}

		resource_matrix(matrix,20,0.5);


		stringstream command;

		generate_taskset_multi(&ft,  100, 15,2.0);
		gams_include(&ft, matrix);
		ofstream tasksetfile("taskset");
		for(unsigned int i=0;i<ft.size();i++)
		{
			tasksetfile<<"task"<<i<<"\t"<<ft[i].computation_time<<"\t"<<ft[i].period<<"\t"<<ft[i].power<<endl;
		}

		tasksetfile.close();

		vector<instance>inst;

		vector<interval>speed_intervals;

		vector<long_schedule>lsch;

		generate_intervals_multi(&speed_intervals, "instanceassign_speed.put");




		for(unsigned int i=0;i<speed_intervals.size();i++)
		{
			cout<<"start "<<speed_intervals[i].start<<" end "<<speed_intervals[i].end<<endl;
			for(unsigned int j=0;j<speed_intervals[i].get_size();j++)
			{
				cout<<"task "<<speed_intervals[i].exec[j].task<<"|"<<speed_intervals[i].exec[j].exec<<"|"<<speed_intervals[i].exec[j].core<<endl;
			}

		}


		//exit(1);

		instance_override_speed(&ft, &inst);
		w2fq_task_convert(&ltasks, &ft);

		dynamic_instance_schedule_speed(&lsch, &ltasks, &speed_intervals, &inst,0);

	//	vector<long_schedule>lsch2;
	//	dynamic_instance_schedule_speed(&lsch2, &ltasks, &speed_intervals, &inst,0);


		float scaled_power[CORE];

		double avg_power;

		generate_power_trace(&lsch, "power_profile_scaled", hyperperiod, scaled_power);
		multi_simulate("power_profile_scaled", "multi.flp",0,avg_power);

//		dynamic_instance_schedule


		exit(1);

		float comps[CORE];
		for(unsigned int i=0;i<speed_intervals.size();i++)
		{
			for(unsigned int j=0;j<CORE;j++)
			{
				comps[j]=0;
			}
			for(unsigned int j=0;j<speed_intervals[i].get_size();j++)
			{
				comps[speed_intervals[i].exec[j].core]=comps[speed_intervals[i].exec[j].core]+
						                                      speed_intervals[i].exec[j].exec;
			}

			cout<<speed_intervals[i].start<<"|"<<speed_intervals[i].end<<"|"<<comps[0]<<"|"<<comps[1]<<"|"<<comps[2]<<endl;

		}

		exit(1);

		float bins[BIN_LENGTH]={0.5,0.6,0.7,0.8,0.9,1.0,1.1};
		int bin_count[BIN_LENGTH]={0,0,0,0,0,0,0};

		int task_num=0;
		bool tutil_incomplete=true;
		while(comp_util<3.0)//1.0)
		{


			cout<<"generating for computil"<<comp_util<<endl;
			tutil_incomplete=true;

			for(unsigned  int b=0;b<BIN_LENGTH;b++)
			{
				bin_count[b]=0;
			}

			while(tutil_incomplete)
			{
				//cout<<" task num "<<task_num<<endl;
				//generate_taskset(&ft, 100, 10, comp_util);
				generate_taskset_multi(&ft,  100, 15,comp_util);
				float avg_power=0.00;
				float real_cutil=0.00;

				for(unsigned int i=0;i<ft.size();i++)
				{
					avg_power=avg_power+ft[i].computation_time/ft[i].period*ft[i].power;
					real_cutil=real_cutil+ft[i].computation_time/ft[i].period;
				}
				float tutil=avg_power/(beta*corrected_threshold);//UTIL_POWER;
				bool accept=false;
				for(unsigned int b=0;b<BIN_LENGTH;b++)
				{
					if(tutil> bins[b] && tutil<(bins[b]+0.1) && bin_count[b]<10)
					{
						accept=true;
						bin_count[b]=bin_count[b]+1;
					}
				}

				if(accept)
				{
					/*if(tutil<0.6 && comp_util>0.75)
					{
						ofstream tasksetfile("taskset");
						for(unsigned int i=0;i<ft.size();i++)
						{
							tasksetfile<<"task"<<i<<"\t"<<ft[i].computation_time<<"\t"<<ft[i].period<<"\t"<<ft[i].power<<endl;
						}

						taskfile<<real_cutil<<"\t"<<tutil<<endl;

						//w2fq_task_convert(&ltasks, &ft);
						//generate_intervals_gps(&intervals, &ltasks);
						//w2fq_schedule(&lschedule, &ltasks,&intervals,0);
						//edf_schedule(&ft,&fedf);
						//w2fq_schedule_convert(&wsch, &lschedule);
						//cout<<" printing float schedule "<<endl;
						//compute_profile(&wsch, &ft, 1);
						//compute_profile(&fedf, &ft, 4);

						//command<<"mkdir results_uni/"<<task_num<<";";
						//command<<"cp profile_float results_uni/"<<task_num<<"/.;";
						//command<<"cp profile_default results_uni/"<<task_num<<"/.;";
						//command<<"cp taskset results_uni/"<<task_num<<"/.";
						//system(command.str().c_str());
						//command.str("");
						tasksetfile.close();
						//exit(1);
					}*/
					//cout<<"checkpoint 1 "<<endl;
					gams_include(&ft, matrix);

					//cout<<"checkpoint 2 "<<endl;


					system("cd gams_files; ~rehan/gams/gams lower_bound.gms");
					system("cd gams_files; ~rehan/gams/gams task_assign.gms");

					command<<"mkdir results/"<<task_num<<";";
					command<<"cp gams_files/results.put results/"<<task_num<<"/.;";
					command<<"cp gams_files/taskassign.put results/"<<task_num<<"/.;";
					command<<"cp gams_files/taskassign_assign.put results/"<<task_num<<"/.;";
					command<<"cp gams_files/task_assign.lst results/"<<task_num<<"/.;";
					command<<"cp gams_files/lower_bound.lst results/"<<task_num<<"/.;";
					command<<"cp gams_files/taskset.put results/"<<task_num<<"/.";
					system(command.str().c_str());
					command.str("");

					//cin.get();
					//exit(1);
					task_num=task_num+1;
					tutil_incomplete=false;
					for(unsigned  int b=0;b<BIN_LENGTH;b++)
					{
						if(bin_count[b]<10)
						{
							tutil_incomplete=true;
						}
					}
					//exit(1);

				}
				intervals.clear();
				lschedule.clear();
				ltasks.clear();
				fedf.clear();
				wsch.clear();
				ft.clear();//only ft needs to be cleared for multicore simulation
			}

			//comp_util=comp_util+0.0025;//0.01;
			comp_util=comp_util+0.01;//0.01;
		}
		exit(1);


/*
		int task_num=0;
		while(comp_util<3.0)
		{

			for(unsigned int m=0;m<10;m++)
			{
				generate_taskset_multi(&ft,  100, 15,comp_util);
				float avg_power=0.00;
				float real_cutil=0.00;

				for(unsigned int i=0;i<ft.size();i++)
				{
					avg_power=avg_power+ft[i].computation_time/ft[i].period*ft[i].power;
					real_cutil=real_cutil+ft[i].computation_time/ft[i].period;
				}
				float tutil=avg_power/UTIL_POWER;

				if(tutil>0.5 && tutil<1.2)
				{
					taskfile<<real_cutil<<"\t"<<tutil<<endl;

					cout<<"checkpoint 1 "<<endl;
					gams_include(&ft, matrix);

					cout<<"checkpoint 2 "<<endl;
					system("cd gams_files; ~rehan/gams/gams lower_bound.gms");
					system("cd gams_files; ~rehan/gams/gams task_assign.gms");

					command<<"mkdir results/"<<task_num<<";";
					command<<"cp gams_files/results.put results/"<<atoi(argv[5])<<"/.;";
					command<<"cp gams_files/taskassign.put results/"<<atoi(argv[5])<<"/.;";
					command<<"cp gams_files/taskassign_assign.put results/"<<atoi(argv[5])<<"/.;";
					command<<"cp gams_files/task_assign.lst results/"<<atoi(argv[5])<<"/.;";
					command<<"cp gams_files/lower_bound.lst results/"<<atoi(argv[5])<<"/.;";
					command<<"cp gams_files/taskset.put results/"<<atoi(argv[5])<<"/.";
					system(command.str().c_str());
					command.str("");
					task_num=task_num+1;
				}
				ft.clear();
			}



			comp_util=comp_util+0.001;
		}
/*
		exit(1);

	//	generate_taskset_multi(&ft,  100, 8,2.5, power);
		//read_taskset_multi(&ft, "gams_folder/taskset.put");





		float cutil=0;
		float tutil=0;

		for(unsigned int i=0;i<ft.size();i++)
		{
			cout<<"task "<<i<<" computation time "<<ft[i].computation_time<<" period "
					<<ft[i].period<<" power "<<ft[i].power<<" comp util "<<ft[i].computation_time/ft[i].period
					<<" thermal util "<<ft[i].computation_time*ft[i].power/(ft[i].period*beta*corrected_threshold)<<endl;
			cutil=cutil+ft[i].computation_time/ft[i].period;
			tutil=tutil+ft[i].computation_time*ft[i].power/(ft[i].period*beta*corrected_threshold);
		}

		cout<<" computation utilization "<<cutil<<" thermal utilization "<<tutil<<endl;



		int int_size=gams_include(&ft, matrix);


		populate_beta();

		for(unsigned int i=0;i<CORE;i++)
		{
			for(unsigned int j=0;j<CORE;j++)
			{
				cout<<beta_multi[i][j]<<"\t";
			}
			cout<<endl;
		}







		system("cd gams_files; ~rehan/gams/gams task_assign.gms");//

		//system("cd gams_files; ~rehan/gams/gams instance_assign.gms");//




		//vector<trace>ttrace;


//		read_ttrace("hotspot_files/thermal_profile", &ttrace);


		intervals.clear();



		vector<mprofile>prof;

		generate_intervals_multi(&intervals,"gams_files/taskassign.put", &ft);
		vector<long_schedule>multi_sch;
		ltasks.clear();
		w2fq_task_convert(&ltasks, &ft);
		multi_schedule(&multi_sch,&intervals, &ltasks);
		long hyperperiod=compute_lcm(&ltasks);
		float avg_power[CORE];
		generate_power_trace(&multi_sch, "power_profile", hyperperiod, avg_power);

		generate_power_profile(&prof,&multi_sch, hyperperiod);

		cout<<"power profile length "<<prof.size()<<endl;

		double average_power;
		for(unsigned int i=0;i<ltasks.size();i++)
		{
			average_power=average_power+(((double)ltasks[i].computation_time)/((double)ltasks[i].period))*ltasks[i].power;
		}
		//compute_profile_multi(&multi_sch, &ltasks);

		//exit(1);

	//	multi_simulate("power_profile", "multi.flp",0,average_power);

		exit(1);

		multi_sch.clear();
		intervals.clear();
		generate_intervals_multi(&intervals,"gams_files/instanceassign.put", &ft);
		multi_schedule(&multi_sch,&intervals, &ltasks);
		generate_power_trace(&multi_sch, "power_profile", hyperperiod, avg_power);
		//multi_simulate("power_profile", "multi.flp",1);
	//	exit(1);




		system(command.str().c_str());


		for(unsigned int i=0;i<intervals.size();i++)
		{
			cout<<" start "<<intervals[i].start<<" end "<<intervals[i].end<<endl;
			for(unsigned int k=0;k<CORE;k++)
			{
				cout<<" core"<<k<<": ";
				int total=0;
				float average_power=0;
				for(unsigned int j=0;j<ft.size();j++)
				{
					cout<<intervals[i].computations[j][k]<<" ";
					total=total+intervals[i].computations[j][k];
					average_power=average_power+((float)intervals[i].computations[j][k])*ft[j].power/((float)(intervals[i].end-intervals[i].start));
				}
				assert(total<=(intervals[i].end-intervals[i].start));
				cout<<" total "<<total<<" average power "<<average_power<< endl;
			}
		}


		cout<<endl<<endl;

		for(unsigned int i=0;i<multi_sch.size();i++)
		{
		//	cout<<"task "<<multi_sch[i].task_id<<" start "<<multi_sch[i].start<<" end "<<multi_sch[i].end<<" core "<<multi_sch[i].core<<endl;
		}



		//avg_power=(float*)malloc(sizeof(float)*CORE);






		cout<<" printing average power"<<endl;
		for(unsigned int i=0;i<CORE;i++)
		{
			cout<<"core"<<i<<" average power "<<avg_power[i]<<endl;
		}

		total_comps(&multi_sch,&ltasks,&intervals);

	//	exit(1);



//		void w2fq_schedule(vector<long_schedule>*sch, vector<long_task>*tasks, vector<interval>*intervals, int core)

/*		while(computation_util<=1.0)
		{
			thermal_util=0.99;

			while(thermal_util<=1.0)
			{
				generate_taskset(&ft,  1000, computation_util, thermal_util);
				w2fq_task_convert(&ltasks, &ft);
				w2fq_schedule(&lschedule, &ltasks);
				edf_schedule(&ft,&fedf);

				w2fq_schedule_convert(&wsch, &lschedule);
				//cout<<" printing float schedule "<<endl;
				compute_profile(&wsch, &ft, 1);
				compute_profile(&fedf, &ft, 2);

				ft.clear();
				ltasks.clear();
				lschedule.clear();
				fedf.clear();
				wsch.clear();
				thermal_util=thermal_util+0.001;

			}
			computation_util=computation_util+0.01;

		}

*/


/*

//       t_util=optimize_maxfirst(&h_speed,&tasks,0.75,1.2);
		timespec start_time,end_time;
		clock_gettime(1,&start_time);
		t_util=optimize_maxmin(&h_speed,&tasks,MIN_SPEED,MAX_SPEED);
		clock_gettime(1,&end_time);
		scale(&scaled_max_first,&tasks,&h_speed);
		edf_schedule(&scaled_max_first,&edf_max_first);
		thermal_optimal=4;
		compute_profile(&edf_max_first, &scaled_max_first,t_util);

		float max_first_time=time_diff(&start_time,&end_time);


		slacks.clear();
		opt.clear();
		opt_exact.clear();
		edl.clear();


		populate_slacks(&slacks, &edf_max_first);
		edl_schedule(&edl, &edf_max_first, &scaled_max_first, &slacks);
		consolidate_schedule(&edl, &scaled_max_first);

		clock_gettime(1,&start_time);
		//opt_schedule(&opt, &scaled_max_first, &edl);
		clock_gettime(1,&end_time);

//		opt_schedule_exact(&opt_exact, &scaled_max_first);
	//	cout<<" schedule size "<<opt_exact.size()<<endl;
	//	run_schedule(&opt,&scaled_max_first);
	//	cout<<"TIME to find the optimal schedule "<<time_diff(&start_time,&end_time)<<"ms"<< " Maxfirst time" << max_first_time<<" Hyperperiod "<<tasksets[0].hyperperiod<<" tasks "<< tasks.size()<<endl;

		float max_speeds[tasks.size()];
		for(unsigned int i=0;i<tasks.size();i++)
		{
			max_speeds[i]=((float)tasks[i].computation_time)/((float)scaled_max_first[i].computation_time);
		}


		vector<schedule>o_sch2;
		//run_dynamic(&scaled_max_first,max_speeds);
		vector<instance>dyn_inst;
		dynamic_instances(&scaled_max_first,max_speeds ,&dyn_inst);

		vector<instance>dyn_inst2;
		for(unsigned int i=0;i<dyn_inst.size();i++)
		{
			dyn_inst2.push_back(dyn_inst[i]);
		}
		double tutil=0;

		scheduler(&o_sch,&scaled_max_first,&dyn_inst,max_speeds,sched_interval);
		compute_profile_dynamic(&o_sch, &tasks,tutil,"");




		scheduler2(&o_sch2,&scaled_max_first,&dyn_inst2, max_speeds, sched_interval);
		compute_profile_dynamic(&o_sch2, &tasks,tutil,"window");

/*		for(unsigned int i=0;i<o_sch2.size();i++)
		{
			cout<<"task "<<o_sch2[i].task_id<<" start "<<o_sch2[i].start<<" end "<<o_sch2[i].end<<" speed "<<o_sch2[i].speed<<endl;
		}
*/

#endif
#if(STATIC_ENABLE)
		t_util=optimize_static(&s_speed,&tasks,MIN_SPEED,MAX_SPEED);
		scale(&scaled_static,&tasks,&s_speed);
		edf_schedule(&scaled_static,&edf_static);
		thermal_optimal=5;
		compute_profile(&edf_static, &scaled_static,t_util);
#endif
#if(MATLAB_ENABLE)
		t_util=optimize_matlab(&m_speed,&tasks,MIN_SPEED,MAX_SPEED);
		scale(&scaled_matlab,&tasks,&m_speed);
		edf_schedule(&scaled_matlab,&edf_matlab);
		thermal_optimal=6;
		compute_profile(&edf_matlab, &scaled_matlab,t_util);
#endif
#if(NOCONS_ENABLE)
		speed_scale(&scaled_tasks,&speeds,&tasks,1.0);
		edf_schedule(&scaled_tasks,&edf2);
		thermal_optimal=7;
		compute_profile(&edf2,&scaled_tasks,t_util);
#endif

#if(SPEED_DEBUG)
		for(int i=0;i<tasks.size();i++)
		{
			cout<<"matlab: "<<m_speed[i]<<" max first:"<<h_speed[i]<<" static speed:<<"<<s_speed[i]<<" nocons speed:"<< speeds[i]<<endl;

		}

#endif

#if(ENABLE_PRINTS)
		cout<<"max first taskset"<<endl;
		for(int i=0;i<scaled_max_first.size();i++)
		{
			cout<<"task "<<i<<" computation time:"<<scaled_max_first[i].computation_time<<" period:"<<scaled_max_first[i].period<<" power:"<<scaled_max_first[i].power<<endl;
		}
		cout<<"static speed taskset"<<endl;
		for(int i=0;i<scaled_max_first.size();i++)
		{
			cout<<"task "<<i<<" computation time:"<<scaled_static[i].computation_time<<" period:"<<scaled_static[i].period<<" power:"<<scaled_static[i].power<<endl;
		}
#endif

#if(ENABLE_PRINTS)

		for(unsigned int i=0;i<speeds.size();i++)
		{
			cout<<"speed for task: "<<i<<"|"<<speeds[i]<<endl;
		}
#endif

		for (unsigned int i = 0; i < tasks.size(); i++) {

//			tasks[i].stat_stream->clear();
//			tasks[i].stat_stream->close();



			//        util1=util1+(float)tasks[i].computation_time/(float)tasks[i].period;
			//        util2=util2+(float)scaled_tasks[i].computation_time/(float)scaled_tasks[i].period;
			//        util3=util3+(float)discrete_scaled[i].computation_time/(float)discrete_scaled[i].period;
		}

#if(ENABLE_PRINTS)

		//  cout<<"util "<<util1<<"|"<<util2<<"|"<<util3<<endl;
		// cout<<"globally optimal power"<<g_power<<endl;
		//cout<<"computed thermally optimal schedule"<<endl;
#endif

		tasks.clear();
		edf.clear();
		scaled_tasks.clear();
		speeds.clear();
		edf2.clear();
		discrete_scaled.clear();
		edf3.clear();
		possible_speeds.clear();
		tasksets.clear();

		opt.clear();
		possible_speeds.clear();
		slacks.clear();

		h_speed.clear();
		s_speed.clear();
		m_speed.clear();
		i_speed.clear();
		i_speed_temp.clear();

		scaled_max_first.clear();
		scaled_static.clear();
		scaled_matlab.clear();
		edf_max_first.clear();
		edf_static.clear();
		edf_matlab.clear();
		edl2.clear();
		edl.clear();
		i_schedule.clear();
		o_sch.clear();
	}
#if(MATLAB_ENABLE)
	engClose(ep);
#endif
}