Beispiel #1
0
void _rtapi_clock_set_period_hook(long int nsecs, RTIME *counts, 
				 RTIME *got_counts) {
    rt_set_periodic_mode();
    *counts = nano2count((RTIME) nsecs);
    if(count2nano(*counts) > nsecs) (*counts)--;
    *got_counts = start_rt_timer(*counts);
    rtapi_data->timer_period = count2nano(*got_counts);
}
Beispiel #2
0
static void *fast_fun(void *arg)
{
	int jit, period;
	RTIME expected;

	if (!(Fast_Task = rt_thread_init(nam2num("FSTSK"), 2, 0, SCHED_FIFO, CPUMAP))) {
		printf("CANNOT INIT FAST TASK\n");
		exit(1);
	}

	mlockall(MCL_CURRENT | MCL_FUTURE);
	rt_make_hard_real_time();
	rt_sem_wait_barrier(barrier);
	period = nano2count(FASTMUL*TICK_TIME);
	expected = start + 6*nano2count(TICK_TIME);
	rt_task_make_periodic(Fast_Task, expected, period);
	while (!end) {
		jit = abs(count2nano(rt_get_time() - expected));
		if (jit > fastjit) {
			fastjit = jit;
		}
		rt_busy_sleep((FASTMUL*TICK_TIME*USEDFRAC)/100);
		expected += period;
		END("FE\n");
		rt_task_wait_period();
		BEGIN("FB\n");
	}
	rt_sem_wait_barrier(barrier);
	rt_make_soft_real_time();
	rt_thread_delete(Fast_Task);
	return 0;
}
Beispiel #3
0
int main(int argc, char *argv[])
{
	int fifo, period, skip, average = 0;
	RT_TASK *task;
	RTIME expected;

        if ((fifo = open("/dev/rtf0", O_WRONLY)) < 0) {
                printf("Error opening FIFO0 in UCAL\n");
                exit(1);
        }
 	if (!(task = rt_task_init_schmod(nam2num("UCAL"), 0, 0, 0, SCHED_FIFO, 0xF))) {
		printf("Cannot init UCAL\n");
		exit(1);
	}

	rt_set_oneshot_mode();
	period = start_rt_timer(nano2count(atoi(argv[1])));
	mlockall(MCL_CURRENT | MCL_FUTURE);
	rt_make_hard_real_time();
	expected = rt_get_time() + 100*period;
	rt_task_make_periodic(task, expected, period);
	for (skip = 0; skip < atoi(argv[2]); skip++) {
		expected += period;
		rt_task_wait_period();
		average += (int)count2nano(rt_get_time() - expected);
	}
	rt_make_soft_real_time();
	stop_rt_timer();
	rt_task_delete(task);
	write(fifo, &average, sizeof(average));
	close(fifo);
	exit(0);
}
Beispiel #4
0
static void *latency_fun(void *arg)
{
	struct sample { long min, max, avrg, jitters[2]; } samp;
	int diff;
	int skip;
	int average;
	int min_diff;
	int max_diff;
	int period;
	RT_TASK *chktsk;
	RTIME expected;

	min_diff = 1000000000;
	max_diff = -1000000000;
	if (!(Latency_Task = rt_thread_init(nam2num("PRETSK"), 0, 0, SCHED_FIFO, CPUMAP))) {
		printf("CANNOT INIT LATENCY TASK\n");
		exit(1);
	}

	mlockall(MCL_CURRENT | MCL_FUTURE);
	rt_make_hard_real_time();
	rt_sem_wait_barrier(barrier);
	period = nano2count(TICK_TIME);
	expected = start + 3*period;
	rt_task_make_periodic(Latency_Task, expected, period);
	while (!end) {
		average = 0;
		for (skip = 0; skip < NAVRG && !end; skip++) {
			expected += period;
			END("HE\n");
			rt_task_wait_period();
			BEGIN("HB\n");
			diff = count2nano(rt_get_time() - expected);
			if (diff < min_diff) {
				min_diff = diff;
			}
			if (diff > max_diff) {
				max_diff = diff;
			}
			average += diff;
		}
		samp.min = min_diff;
		samp.max = max_diff;
		samp.avrg = average/NAVRG;
		samp.jitters[0] = fastjit;
		samp.jitters[1] = slowjit;
		if ((chktsk = rt_get_adr(nam2num("PRECHK")))) {
			rt_sendx_if(chktsk, &samp, sizeof(samp));
		}
	}
	rt_sem_wait_barrier(barrier);
	rt_make_soft_real_time();
	rt_thread_delete(Latency_Task);
	return 0;
}
static void spv(long loops)
{
	int skip, average = 0;
	for (skip = 0; skip < loops; skip++) {
		expected += period;
		rt_task_wait_period();
		average += (int)count2nano(rt_get_time() - expected);
	}
	rtf_put(0, &average, sizeof(average));
	rt_task_suspend(0);
}
void task_body(long int arg) {
     int loop = N_LOOP;

	rt_task_set_resume_end_times(-0, -Period[arg]*time_unit);

    while (loop--) {
        int i;
		RTIME begin, end;

		begin = rt_get_time();
        rt_printk("Start task %d\t  %llu ns\n", arg, count2nano(begin-first_release));
        for(i = 0; i < C[arg] ; i++) {
            run_for_1_time_unit();
        }
        end = rt_get_time();
        rt_printk("End task %d\t  %llu ns\n", arg, count2nano(end-first_release));
        rt_printk("Task length %d\t  %llu ns\n", arg, count2nano(end-begin));

		rt_task_set_resume_end_times(-Period[arg]*time_unit, -Period[arg]*time_unit);
    }
}
Beispiel #7
0
void actcode(int arg) {
  RTIME t, t_old;

    while (1) {
        rt_sem_wait(&sensDone); // wait for sensor acquisition
        t = rt_get_time();
        printk("[act_task] time: %llu ms\n", count2nano(t - now));
        /* controller code */
        //ctrlcode(currentAngle, currentPosition);
    	//setDA_raw(1, (int) command_u16);
        //ctrlcode(0.1, 1.0);
        /* end of controller code */
        t_old = t;
    }
}
Beispiel #8
0
static void fun(long thread) {

	struct sample { long min, max, avrg, jitters[2]; } samp;
	int diff;
	int skip;
	int average;
	int min_diff;
	int max_diff;
	RTIME svt, t;

	t = 0;
	min_diff = 1000000000;
	max_diff = -1000000000;
	while (1) {
		unsigned long flags;
		average = 0;

		svt = rt_get_cpu_time_ns();
		for (skip = 0; skip < NAVRG; skip++) {
			cpu_used[hard_cpu_id()]++;
			expected += period;
			rt_task_wait_period();

			rt_global_save_flags(&flags);
#ifndef ONESHOT_MODE
			diff = (int) ((t = rt_get_cpu_time_ns()) - svt - TICK_TIME);
			svt = t;
#else
			diff = (int) count2nano(rt_get_time() - expected);
#endif
			if (diff < min_diff) {
				min_diff = diff;
			}
			if (diff > max_diff) {
				max_diff = diff;
			}
		average += diff;
		}
		samp.min = min_diff;
		samp.max = max_diff;
		samp.avrg = average/NAVRG;
		samp.jitters[0] = fastjit;
		samp.jitters[1] = slowjit;
		rtf_ovrwr_put(FIFO, &samp, sizeof(samp));
	}
}
Beispiel #9
0
void senscode(int arg) {
  RTIME t, t_old;

    while (1) {
        t = rt_get_time();
        printk("[sens_task] time: %llu ns\n", count2nano(t - now));
        /* sensor acquisition code */
        ADRangeSelect(0,8);
        //currentAngle_raw = readAD();
        currentAngle_raw = readAD();
        //printk("angle = %d (0x%x)\n", (int) currentAngle_raw, (int) currentAngle_raw);
        //printk("angle = %d mRad\n", (int) (raw2Rad(currentAngle_raw*1000)));

        ADRangeSelect(1,8);
        //currentPosition_raw = readAD();
        currentPosition_raw = readAD();
        //printk("position = %d (0x%x)\n", (int) currentPosition_raw, (int) currentPosition_raw);
        //printk("position = %d\n", (int) (currentPosition_raw*1000));

        //printk("\n");

        // signal end of acquisition, ready for control
        rt_sem_signal(&sensDone);
	// u16 command_u16 = control(currentAngle_raw, currentPosition_raw);
	//currentAngle_rad = 0.0; //DEBUG
	//currentPosition_m = 0.0; //DEBUG
	
	// currentPosition_volt = currentPosition_raw * 0.087;
	currentPosition_m = currentPosition_raw * 1.0/4096 - 0.5;
	currentAngle_volt = 0.00244141*(currentAngle_raw - 2048);
	currentAngle_rad = currentAngle_volt * 0.087; 	

	// printk("Position_volt = %d.\n",(int)(currentPosition_volt));
	// printk("Position_cm = %d.\n",(int)(currentPosition_m*100));
	// printk("Angle_rad*1000 = %d.\n", (int) (currentAngle_rad*1000));
	// printk("angle_degre : %d.\n",(int)((currentAngle_rad*180)/3.14));

	ctrlcode(currentAngle_rad, currentPosition_m);

        /* end of sensor acquisition code */
        t_old = t;
        rt_task_wait_period();
    }
}
Beispiel #10
0
int _rtapi_task_start_hook(task_data *task, int task_id,
			  unsigned long int period_nsec) {
    int retval;
    unsigned long int quo, period_counts;

    period_counts = nano2count((RTIME)period_nsec);  
    quo = (period_counts + timer_counts / 2) / timer_counts;
    period_counts = quo * timer_counts;
    period_nsec = count2nano(period_counts);

    /* start the task */
    retval = rt_task_make_periodic(ostask_array[task_id],
	rt_get_time() + period_counts, period_counts);
    if (retval != 0) {
	return -EINVAL;
    }

    return 0;
}
Beispiel #11
0
void fun(int thread) {

	int skip, average;

	average = 0;
	for (skip = 0; skip < SKIP; skip++) {
		expected += period;
		rt_task_wait_period();

		average += (int)count2nano(rt_get_time() - expected);
	}
        if (abs(imuldiv(tuned.setup_time_TIMER_CPUNIT, 1000000000, tuned.cpu_freq) - SETUP_TIME_APIC) < 3) {
		rt_printk("\n\n*** '#define LATENCY_APIC %d' (IN USE %d)", LATENCY_APIC + average/SKIP, LATENCY_APIC);
	} else {
		rt_printk("\n\n*** '#define LATENCY_8254 %d' (IN USE %d)", LATENCY_8254 + average/SKIP, LATENCY_8254);
	}
	rt_printk(", you can do 'make stop' now ***\n");
	while(1) {
		rt_task_wait_period();
	}
}
Beispiel #12
0
int main(int argc, char *argv[])
{
	int diff;
	int skip;
	long average;
	int min_diff;
	int max_diff;
	int period;
	int i;
	RTIME t, svt;
	RTIME expected, exectime[3];
	MBX *mbx;
	RT_TASK *task, *latchk;
	struct sample { long long min; long long max; int index, ovrn; } samp;
	double s;

	signal(SIGHUP,  endme);
	signal(SIGKILL, endme);
	signal(SIGTERM, endme);
	signal(SIGALRM, endme);

 	if (!(mbx = rt_mbx_init(nam2num("LATMBX"), 20*sizeof(samp)))) {
		printf("CANNOT CREATE MAILBOX\n");
		exit(1);
	}

 	if (!(task = rt_task_init_schmod(nam2num("LATCAL"), 0, 0, 0, SCHED_FIFO, 0xF))) {
		printf("CANNOT INIT MASTER TASK\n");
		exit(1);
	}

	printf("\n## RTAI latency calibration tool ##\n");
	printf("# period = %i (ns) \n", PERIOD);
	printf("# average time = %i (s)\n", (int)AVRGTIME);
	printf("# use the FPU\n");
	printf("#%sstart the timer\n", argc == 1 ? " " : " do not ");
	printf("# timer_mode is %s\n", TIMER_MODE ? "periodic" : "oneshot");
	printf("\n");

	if (argc == 1) {
		if (TIMER_MODE) {
			rt_set_periodic_mode();
		} else {
			rt_set_oneshot_mode();
		}
		period = start_rt_timer(nano2count(PERIOD));
	} else {
		period = nano2count(PERIOD);
	}

        for(i = 0; i < MAXDIM; i++) {
                a[i] = b[i] = 3.141592;
        }
	s = dot(a, b, MAXDIM);

	mlockall(MCL_CURRENT | MCL_FUTURE);

	rt_make_hard_real_time();
	rt_task_make_periodic(task, expected = rt_get_tscnt() + 10*period, period);

	svt = rt_get_cpu_time_ns();
	samp.ovrn = i = 0;
	while (!end) {
		min_diff = 1000000000;
		max_diff = -1000000000;
		average = 0;

		for (skip = 0; skip < SKIP && !end; skip++) {
			expected += period;

			if (!rt_task_wait_period()) {
				if (TIMER_MODE) {
					diff = (int) ((t = rt_get_cpu_time_ns()) - svt - PERIOD);
					svt = t;
				} else {
					diff = (int) count2nano(rt_get_tscnt() - expected);
				}
			} else {
				samp.ovrn++;
				diff = 0;
				if (TIMER_MODE) {
					svt = rt_get_cpu_time_ns();
				}
			}
			if (diff < min_diff) {
				min_diff = diff;
			}
			if (diff > max_diff) {
				max_diff = diff;
			}
			average += diff;
			s = dot(a, b, MAXDIM);
		}
		samp.min = min_diff;
		samp.max = max_diff;
		samp.index = average/SKIP;
		rt_mbx_send_if(mbx, &samp, sizeof(samp));
		if ((latchk = rt_get_adr(nam2num("LATCHK"))) && (rt_receive_if(latchk, (unsigned long *)&average) || end)) {
			rt_return(latchk, (unsigned long)average);
			break;
		}
	}

	while (rt_get_adr(nam2num("LATCHK"))) {
		rt_sleep(nano2count(1000000));
	}
	rt_make_soft_real_time();
	if (argc == 1) {
		stop_rt_timer();	
	}
	rt_get_exectime(task, exectime);
	if (exectime[1] && exectime[2]) {
		printf("\n>>> S = %g, EXECTIME = %G\n", s, (double)exectime[0]/(double)(exectime[2] - exectime[1]));
	}
	rt_task_delete(task);
	rt_mbx_delete(mbx);

	return 0;
}
Beispiel #13
0
int main(int argc, char *argv[])
{
	int diff;
	int skip;
	int average;
	int min_diff;
	int max_diff;
	int period;
	int i;
	RTIME expected, ts;
	MBX *mbx;
	RT_TASK *task;
	struct sample { long long min; long long max; int index; double s; int ts; } samp;
	double s;

 	if (!(mbx = rt_mbx_init(nam2num("LATMBX"), 20*sizeof(samp)))) {
		printf("CANNOT CREATE MAILBOX\n");
		exit(1);
	}

 	if (!(task = rt_task_init_schmod(nam2num("LATCAL"), 0, 0, 0, SCHED_FIFO, 0xF))) {
		printf("CANNOT INIT MASTER TASK\n");
		exit(1);
	}

	if (argc == 1) {
		rt_set_oneshot_mode();
		start_rt_timer(0);
	}

        for(i = 0; i < MAXDIM; i++) {
                a[i] = b[i] = 3.141592;
        }
	vdot(a, b, MAXDIM);

	mlockall(MCL_CURRENT | MCL_FUTURE);

	rt_make_hard_real_time();
	period = nano2count(PERIOD);
	rt_task_make_periodic(task, expected = rt_get_time() + 5*period, period);

#ifdef OVERALL
	min_diff = 1000000000;
	max_diff = -1000000000;
#endif
	while (1) {
#ifndef OVERALL
		min_diff = 1000000000;
		max_diff = -1000000000;
#endif
		average = 0;

		for (skip = 0; skip < SKIP; skip++) {
			expected += period;
			rt_task_wait_period();

			diff = (int)count2nano(rt_get_time() - expected);
			if (diff < min_diff) {
				min_diff = diff;
			}
			if (diff > max_diff) {
				max_diff = diff;
			}
			average += diff;
			ts = rt_get_time();
			s = vdot(a, b, MAXDIM);
			ts = rt_get_time() - expected;
		}
		samp.min = min_diff;
		samp.max = max_diff;
		samp.index = average/SKIP;
		samp.s = (double)s;
		samp.ts = (int)count2nano(ts);
		rt_mbx_send_if(mbx, &samp, sizeof(samp));
		if (rt_receive_if(rt_get_adr(nam2num("LATCHK")), (unsigned int *)&average)) {
			rt_return(rt_get_adr(nam2num("LATCHK")), (unsigned int)average);
			break;
		}
	}

	while (rt_get_adr(nam2num("LATCHK"))) {
		rt_sleep(nano2count(1000000));
	}
	rt_make_soft_real_time();
	if (argc == 1) {
		stop_rt_timer();
	}
	rt_task_delete(task);
	rt_mbx_delete(mbx);

	return 0;
}
static void* rt_system_thread(void * arg)
{	
	SEM * status_sem;
	SEM * command_sem;
	RT_TASK *task;
	int cntr=0;
	M3Sds * sds = (M3Sds *)arg;
	printf("Starting real-time thread\n");
		
	
	sds_status_size = sizeof(M3LedMatrixEcShmSdsStatus);
	sds_cmd_size = sizeof(M3LedMatrixEcShmSdsCommand);
	
	memset(&cmd, 0, sds_cmd_size);
	
	task = rt_task_init_schmod(nam2num("LSHMP"), 0, 0, 0, SCHED_FIFO, 0xF);
	rt_allow_nonroot_hrt();
	if (task==NULL)
	{
		printf("Failed to create RT-TASK LSHMP\n");
		return 0;
	}
	status_sem=(SEM*)rt_get_adr(nam2num(MEKA_LED_STATUS_SEM));
	command_sem=(SEM*)rt_get_adr(nam2num(MEKA_LED_CMD_SEM));
	if (!status_sem)
	{
		printf("Unable to find the %s semaphore.\n",MEKA_LED_STATUS_SEM);
		rt_task_delete(task);
		return 0;
	}
	if (!command_sem)
	{
		printf("Unable to find the %s semaphore.\n",MEKA_LED_CMD_SEM);
		rt_task_delete(task);
		return 0;
	}
	
	
	RTIME tick_period = nano2count(RT_TIMER_TICKS_NS_MEKA_LED_SHM); 
	RTIME now = rt_get_time();
	rt_task_make_periodic(task, now + tick_period, tick_period); 
	mlockall(MCL_CURRENT | MCL_FUTURE);
	rt_make_hard_real_time();
	long long start_time, end_time, dt;
	long long step_cnt = 0;
	sys_thread_active=1;
	
	while(!sys_thread_end)
	{
		start_time = nano2count(rt_get_cpu_time_ns());
		rt_sem_wait(status_sem);
		memcpy(&status, sds->status, sds_status_size);		
		rt_sem_signal(status_sem);
		
		StepShm(cntr);		
		
		rt_sem_wait(command_sem);		
		memcpy(sds->cmd, &cmd, sds_cmd_size);		
		rt_sem_signal(command_sem);
				
		end_time = nano2count(rt_get_cpu_time_ns());
		dt=end_time-start_time;
		/*
		Check the time it takes to run components, and if it takes longer
		than our period, make us run slower. Otherwise this task locks
		up the CPU.*/
		if (dt > tick_period && step_cnt>10) 
		{
			printf("Step %lld: Computation time of components is too long. Forcing all components to state SafeOp.\n",step_cnt);
			printf("Previous period: %f. New period: %f\n", (double)count2nano(tick_period),(double)count2nano(dt));
 			tick_period=dt;
			//rt_task_make_periodic(task, end + tick_period,tick_period);			
		}
		step_cnt++;
		if (cntr++ == CYCLE_TIME_SEC * 2 * RT_TIMER_TICKS_NS_MEKA_LED_SHM)
		  cntr = 0;
		rt_task_wait_period();
	}	
	printf("Exiting RealTime Thread...\n",0);
	rt_make_soft_real_time();
	rt_task_delete(task);
	sys_thread_active=0;
	return 0;
}
Beispiel #15
0
void
fun(long thread)
{

    int diff = 0;
    int i;
    int average;
    int min_diff = 0;
    int max_diff = 0;
    RTIME t, svt;

#ifdef CONFIG_RTAI_FPU_SUPPORT
    if (use_fpu) {
        for(i = 0; i < MAXDIM; i++) {
            a[i] = b[i] = 3.141592;
        }
    }
#endif

    svt = rt_get_cpu_time_ns();
    samp.ovrn = 0;
    while (1) {

        min_diff =  1000000000;
        max_diff = -1000000000;

        average = 0;

        for (i = 0; i < loops; i++) {
            cpu_used[hard_cpu_id()]++;
            expected += period_counts;

            if (!rt_task_wait_period()) {
                if (timer_mode) {
                    diff = (int) ((t = rt_get_cpu_time_ns()) - svt - period);
                    svt = t;
                } else {
                    diff = (int) count2nano(rt_get_time() - expected);
                }
            } else {
                samp.ovrn++;
                diff = 0;
                if (timer_mode) {
                    svt = rt_get_cpu_time_ns();
                }
            }

            if (diff < min_diff) {
                min_diff = diff;
            }
            if (diff > max_diff) {
                max_diff = diff;
            }
            average += diff;
#ifdef CONFIG_RTAI_FPU_SUPPORT
            if (use_fpu) {
                dotres = dot(a, b, MAXDIM);
            }
#endif
        }
        samp.min = min_diff;
        samp.max = max_diff;
        samp.index = average / loops;
        rtf_put(DEBUG_FIFO, &samp, sizeof (samp));
    }
    rt_printk("\nDOT PRODUCT RESULT = %lu\n", (unsigned long)dotres);
}
Beispiel #16
0
int main(int argc, char **argv) {

#ifdef RTAI
  RT_TASK *task;
  RTIME period;
#endif
  int i,j,aa;
  void *status;

  /*
  uint32_t rf_mode_max[4]     = {55759,55759,55759,55759};
  uint32_t rf_mode_med[4]     = {39375,39375,39375,39375};
  uint32_t rf_mode_byp[4]     = {22991,22991,22991,22991};
  */
  uint32_t my_rf_mode = RXEN + TXEN + TXLPFNORM + TXLPFEN + TXLPF25 + RXLPFNORM + RXLPFEN + RXLPF25 + LNA1ON +LNAMax + RFBBNORM + DMAMODE_RX + DMAMODE_TX;
  uint32_t rf_mode_base = TXLPFNORM + TXLPFEN + TXLPF25 + RXLPFNORM + RXLPFEN + RXLPF25 + LNA1ON +LNAMax + RFBBNORM;
  uint32_t rf_mode[4]     = {my_rf_mode,0,0,0};
  uint32_t rf_local[4]    = {8255000,8255000,8255000,8255000}; // UE zepto
    //{8254617, 8254617, 8254617, 8254617}; //eNB khalifa
    //{8255067,8254810,8257340,8257340}; // eNB PETRONAS

  uint32_t rf_vcocal[4]   = {910,910,910,910};
  uint32_t rf_vcocal_850[4] = {2015, 2015, 2015, 2015};
  uint32_t rf_rxdc[4]     = {32896,32896,32896,32896};
  uint32_t rxgain[4]      = {20,20,20,20};
  uint32_t txgain[4]      = {20,20,20,20};

  uint16_t Nid_cell = 0;
  uint8_t  cooperation_flag=0, transmission_mode=1, abstraction_flag=0;
  uint8_t beta_ACK=0,beta_RI=0,beta_CQI=2;

  int c;
  char do_forms=0;
  unsigned int fd;
  unsigned int tcxo = 114;

  int amp;
  uint8_t prach_fmt;
  int N_ZC;

  char rxg_fname[100];
  char txg_fname[100];
  char rflo_fname[100];
  char rfdc_fname[100];
  FILE *rxg_fd=NULL;
  FILE *txg_fd=NULL;
  FILE *rflo_fd=NULL;
  FILE *rfdc_fd=NULL;
  unsigned int rxg_max[4]={133,133,133,133}, rxg_med[4]={127,127,127,127}, rxg_byp[4]={120,120,120,120};
  int tx_max_power=0;

  char line[1000];
  int l;
  int ret, ant;
  int ant_offset=0;

  int error_code;
  char *itti_dump_file = NULL;

  const struct option long_options[] = {
    {"calib-ue-rx", required_argument, NULL, 256},
    {"calib-ue-rx-med", required_argument, NULL, 257},
    {"calib-ue-rx-byp", required_argument, NULL, 258},
    {"debug-ue-prach", no_argument, NULL, 259},
    {"no-L2-connect", no_argument, NULL, 260},
    {NULL, 0, NULL, 0}};

  //mode = normal_txrx;


  while ((c = getopt_long (argc, argv, "C:K:O:ST:UdF:V",long_options,NULL)) != -1)
    {
      switch (c)
        {
	case 'V':
          ouput_vcd = 1;
	  break;
        case 'd':
          do_forms=1;
          break;
        case 'U':
          UE_flag = 1;
          break;
        case 'C':
          carrier_freq[0] = atoi(optarg);
          carrier_freq[1] = atoi(optarg);
          carrier_freq[2] = atoi(optarg);
          carrier_freq[3] = atoi(optarg);
          break;
        case 'S':
          fs4_test=1;
          break;
        case 'T':
          tcxo=atoi(optarg);
          break;
        case 'K':
#if defined(ENABLE_ITTI)
          itti_dump_file = strdup(optarg);
#else
          printf("-K option is disabled when ENABLE_ITTI is not defined\n");
#endif
          break;
        case 'O':
#if defined(ENABLE_USE_MME)
          EPC_MODE_ENABLED = 1;
          if (optarg == NULL) /* No IP address provided: use localhost */
          {
            memcpy(&EPC_MODE_MME_ADDRESS[0], "127.0.0.1", 10);
          } else {
            uint8_t ip_length = strlen(optarg) + 1;
            memcpy(&EPC_MODE_MME_ADDRESS[0], optarg,
            ip_length > 16 ? 16 : ip_length);
          }
#else
          printf("You enabled mme mode without s1ap compiled...\n");
#endif
          break;
	case 'F':
	  sprintf(rxg_fname,"%srxg.lime",optarg);
	  rxg_fd = fopen(rxg_fname,"r");
	  if (rxg_fd) {
	    printf("Loading RX Gain parameters from %s\n",rxg_fname);
	    l=0;
	    while (fgets(line, sizeof(line), rxg_fd)) {
	      if ((strlen(line)==0) || (*line == '#')) continue; //ignore empty or comment lines
	      else {
		if (l==0) sscanf(line,"%d %d %d %d",&rxg_max[0],&rxg_max[1],&rxg_max[2],&rxg_max[3]);
		if (l==1) sscanf(line,"%d %d %d %d",&rxg_med[0],&rxg_med[1],&rxg_med[2],&rxg_med[3]);
		if (l==2) sscanf(line,"%d %d %d %d",&rxg_byp[0],&rxg_byp[1],&rxg_byp[2],&rxg_byp[3]);
		l++;
	      }
	    }
	  }
	  else 
	    printf("%s not found, running with defaults\n",rxg_fname);

	  sprintf(txg_fname,"%stxg.lime",optarg);
	  txg_fd = fopen(txg_fname,"r");
	  if (txg_fd) {
	    printf("Loading TX Gain parameters from %s\n",txg_fname);
	    l=0;
	    while (fgets(line, sizeof(line), txg_fd)) {
	      if ((strlen(line)==0) || (*line == '#')) {
		continue; //ignore empty or comment lines
	      }
	      else {
		if (l==0) sscanf(line,"%d %d %d %d",&txgain[0],&txgain[1],&txgain[2],&txgain[3]);
		if (l==1) sscanf(line,"%d",&tx_max_power);
		l++;
	      }
	    }
	  }
	  else 
	    printf("%s not found, running with defaults\n",txg_fname);

	  sprintf(rflo_fname,"%srflo.lime",optarg);
	  rflo_fd = fopen(rflo_fname,"r");
	  if (rflo_fd) {
	    printf("Loading RF LO parameters from %s\n",rflo_fname);
	    fscanf(rflo_fd,"%d %d %d %d",&rf_local[0],&rf_local[1],&rf_local[2],&rf_local[3]);
	  }
	  else 
	    printf("%s not found, running with defaults\n",rflo_fname);

	  sprintf(rfdc_fname,"%srfdc.lime",optarg);
	  rfdc_fd = fopen(rfdc_fname,"r");
	  if (rfdc_fd) {
	    printf("Loading RF DC parameters from %s\n",rfdc_fname);
	    fscanf(rfdc_fd,"%d %d %d %d",&rf_rxdc[0],&rf_rxdc[1],&rf_rxdc[2],&rf_rxdc[3]);
	  }
	  else 
	    printf("%s not found, running with defaults\n",rfdc_fname);

	  break;
	  /*
	case 256:
	  mode = rx_calib_ue;
	  rx_input_level_dBm = atoi(optarg);
	  printf("Running with UE calibration on (LNA max), input level %d dBm\n",rx_input_level_dBm);
	  break;
	case 257:
	  mode = rx_calib_ue_med;
	  rx_input_level_dBm = atoi(optarg);
	  printf("Running with UE calibration on (LNA med), input level %d dBm\n",rx_input_level_dBm);
	  break;
	case 258:
	  mode = rx_calib_ue_byp;
	  rx_input_level_dBm = atoi(optarg);
	  printf("Running with UE calibration on (LNA byp), input level %d dBm\n",rx_input_level_dBm);
	  break;
	case 259:
	  mode = debug_prach;
	  break;
	case 260:
	  mode = no_L2_connect;
	  break;
	  */
        default:
          break;
        }
    }

  if (UE_flag==1)
    printf("configuring for UE\n");
  else
    printf("configuring for eNB\n");

  //randominit (0);
  //set_taus_seed (0);

  // initialize the log (see log.h for details)
  logInit();

#if defined(ENABLE_ITTI)
  itti_init(TASK_MAX, THREAD_MAX, MESSAGES_ID_MAX, tasks_info, messages_info, messages_definition_xml, itti_dump_file);

# if defined(ENABLE_USE_MME)
  if (itti_create_task(TASK_SCTP, sctp_eNB_task, NULL) < 0) {
    LOG_E(EMU, "Create task failed");
    LOG_D(EMU, "Initializing SCTP task interface: FAILED\n");
    return -1;
  }
  if (itti_create_task(TASK_S1AP, s1ap_eNB_task, NULL) < 0) {
    LOG_E(EMU, "Create task failed");
    LOG_D(EMU, "Initializing S1AP task interface: FAILED\n");
    return -1;
  }
# endif

  if (itti_create_task(TASK_L2L1, l2l1_task, NULL) < 0) {
      LOG_E(EMU, "Create task failed");
      LOG_D(EMU, "Initializing L2L1 task interface: FAILED\n");
      return -1;
  }

  // Handle signals until all tasks are terminated
//   itti_wait_tasks_end();
#endif

  if (ouput_vcd) {
    if (UE_flag==1)
      vcd_signal_dumper_init("/tmp/openair_dump_UE.vcd");
    else
      vcd_signal_dumper_init("/tmp/openair_dump_eNB.vcd");
  }

#ifdef NAS_NETLINK
  netlink_init();
#endif

  // to make a graceful exit when ctrl-c is pressed
  signal(SIGSEGV, signal_handler);
  signal(SIGINT, signal_handler);

#ifndef RTAI
  check_clock();
#endif

    g_log->log_component[HW].level = LOG_DEBUG;
    g_log->log_component[HW].flag  = LOG_HIGH;
#ifdef OPENAIR2
    g_log->log_component[PHY].level = LOG_INFO;
#else
    g_log->log_component[PHY].level = LOG_INFO;
#endif
    g_log->log_component[PHY].flag  = LOG_HIGH;
    g_log->log_component[MAC].level = LOG_INFO;
    g_log->log_component[MAC].flag  = LOG_HIGH;
    g_log->log_component[RLC].level = LOG_INFO;
    g_log->log_component[RLC].flag  = LOG_HIGH;
    g_log->log_component[PDCP].level = LOG_INFO;
    g_log->log_component[PDCP].flag  = LOG_HIGH;
    g_log->log_component[OTG].level = LOG_INFO;
    g_log->log_component[OTG].flag  = LOG_HIGH;
    g_log->log_component[RRC].level = LOG_INFO;
    g_log->log_component[RRC].flag  = LOG_HIGH;


  // Initialize card
  ret = openair0_open();
  if ( ret != 0 ) {
          if (ret == -1)
              printf("Error opening /dev/openair0");
          if (ret == -2)
              printf("Error mapping bigshm");
          if (ret == -3)
              printf("Error mapping RX or TX buffer");
          return(ret);
     }

  printf ("Detected %d number of cards, %d number of antennas.\n", openair0_num_detected_cards, openair0_num_antennas[card]);
  
  p_exmimo_config = openair0_exmimo_pci[card].exmimo_config_ptr;
  p_exmimo_id     = openair0_exmimo_pci[card].exmimo_id_ptr;
  
  printf("Card %d: ExpressMIMO %d, HW Rev %d, SW Rev 0x%d\n", card, p_exmimo_id->board_exmimoversion, p_exmimo_id->board_hwrev, p_exmimo_id->board_swrev);

  if (p_exmimo_id->board_swrev>=BOARD_SWREV_CNTL2)
    p_exmimo_config->framing.eNB_flag   = 0; 
  else 
    p_exmimo_config->framing.eNB_flag   = !UE_flag;

  p_exmimo_config->framing.tdd_config = DUPLEXMODE_FDD + TXRXSWITCH_LSB;
  for (ant=0; ant<4; ant++) 
    p_exmimo_config->framing.resampling_factor[ant] = RESAMPLING_FACTOR;
 
  /*
  for (ant=0;ant<max(frame_parms->nb_antennas_tx,frame_parms->nb_antennas_rx);ant++) 
    p_exmimo_config->rf.rf_mode[ant] = rf_mode_base;
  for (ant=0;ant<frame_parms->nb_antennas_tx;ant++)
    p_exmimo_config->rf.rf_mode[ant] += (TXEN + DMAMODE_TX);
  for (ant=0;ant<frame_parms->nb_antennas_rx;ant++)
    p_exmimo_config->rf.rf_mode[ant] += (RXEN + DMAMODE_RX);
  for (ant=max(frame_parms->nb_antennas_tx,frame_parms->nb_antennas_rx);ant<4;ant++) {
    p_exmimo_config->rf.rf_mode[ant] = 0;
    carrier_freq[ant] = 0; //this turns off all other LIMEs
  }
  */

  ant_offset = 0;
  for (ant=0; ant<4; ant++) {
    if (ant==ant_offset) {
      //if (1) {
      p_exmimo_config->rf.rf_mode[ant] = rf_mode_base;
      //p_exmimo_config->rf.rf_mode[ant] += (TXEN + DMAMODE_TX);
      p_exmimo_config->rf.rf_mode[ant] += (RXEN + DMAMODE_RX);
    }
    else {
      p_exmimo_config->rf.rf_mode[ant] = 0;
      carrier_freq[ant] = 0; //this turns off all other LIMEs
    }
  }

  for (ant = 0; ant<4; ant++) { 
    p_exmimo_config->rf.do_autocal[ant] = 1;
    p_exmimo_config->rf.rf_freq_rx[ant] = carrier_freq[ant];
    p_exmimo_config->rf.rf_freq_tx[ant] = carrier_freq[ant];
    p_exmimo_config->rf.rx_gain[ant][0] = rxgain[ant];
    p_exmimo_config->rf.tx_gain[ant][0] = txgain[ant];
    
    p_exmimo_config->rf.rf_local[ant]   = rf_local[ant];
    p_exmimo_config->rf.rf_rxdc[ant]    = rf_rxdc[ant];

    if ((carrier_freq[ant] >= 850000000) && (carrier_freq[ant] <= 865000000)) {
      p_exmimo_config->rf.rf_vcocal[ant]  = rf_vcocal_850[ant];
      p_exmimo_config->rf.rffe_band_mode[ant] = DD_TDD;	    
    }
    else if ((carrier_freq[ant] >= 1900000000) && (carrier_freq[ant] <= 2000000000)) {
      p_exmimo_config->rf.rf_vcocal[ant]  = rf_vcocal[ant];
      p_exmimo_config->rf.rffe_band_mode[ant] = B19G_TDD;	    
    }
    else {
      p_exmimo_config->rf.rf_vcocal[ant]  = rf_vcocal[ant];
      p_exmimo_config->rf.rffe_band_mode[ant] = 0;	    
    }

    p_exmimo_config->rf.rffe_gain_txlow[ant] = 31;
    p_exmimo_config->rf.rffe_gain_txhigh[ant] = 31;
    p_exmimo_config->rf.rffe_gain_rxfinal[ant] = 52;
    p_exmimo_config->rf.rffe_gain_rxlow[ant] = 31;
  }


    number_of_cards = openair0_num_detected_cards;
    /*
    if (p_exmimo_id->board_exmimoversion==1) //ExpressMIMO1
      openair_daq_vars.timing_advance = 138;
    else //ExpressMIMO2
      openair_daq_vars.timing_advance = 0;
    */

  openair0_dump_config(card);

  printf("EXMIMO_CONFIG: rf_mode 0x %x %x %x %x, [0]: TXRXEn %d, TXLPFEn %d, TXLPF %d, RXLPFEn %d, RXLPF %d, RFBB %d, LNA %d, LNAGain %d, RXLPFMode %d, SWITCH %d, rf_rxdc %d, rf_local %d, rf_vcocal %d\n",  
	 p_exmimo_config->rf.rf_mode[0],
	 p_exmimo_config->rf.rf_mode[1],
	 p_exmimo_config->rf.rf_mode[2],
	 p_exmimo_config->rf.rf_mode[3],
	 (p_exmimo_config->rf.rf_mode[0]&3),  // RXen+TXen
	 (p_exmimo_config->rf.rf_mode[0]&4)>>2,         //TXLPFen
	 (p_exmimo_config->rf.rf_mode[0]&TXLPFMASK)>>3, //TXLPF
	 (p_exmimo_config->rf.rf_mode[0]&128)>>7,      //RXLPFen
	 (p_exmimo_config->rf.rf_mode[0]&RXLPFMASK)>>8, //TXLPF
	 (p_exmimo_config->rf.rf_mode[0]&RFBBMASK)>>16, // RFBB mode
	 (p_exmimo_config->rf.rf_mode[0]&LNAMASK)>>12, // RFBB mode
	 (p_exmimo_config->rf.rf_mode[0]&LNAGAINMASK)>>14, // RFBB mode
	 (p_exmimo_config->rf.rf_mode[0]&RXLPFMODEMASK)>>19, // RXLPF mode
	 (p_exmimo_config->framing.tdd_config&TXRXSWITCH_MASK)>>1, // Switch mode
	 p_exmimo_config->rf.rf_rxdc[0],
	 p_exmimo_config->rf.rf_local[0],
	 p_exmimo_config->rf.rf_vcocal[0]);
  
  for (ant=0;ant<4;ant++)
    p_exmimo_config->rf.do_autocal[ant] = 0;

#ifdef EMOS
  error_code = rtf_create(CHANSOUNDER_FIFO_MINOR,CHANSOUNDER_FIFO_SIZE);
  if (error_code==0)
    printf("[OPENAIR][SCHED][INIT] Created EMOS FIFO %d\n",CHANSOUNDER_FIFO_MINOR);
  else if (error_code==ENODEV)
    printf("[OPENAIR][SCHED][INIT] Problem: EMOS FIFO %d is greater than or equal to RTF_NO\n",CHANSOUNDER_FIFO_MINOR);
  else if (error_code==ENOMEM)
    printf("[OPENAIR][SCHED][INIT] Problem: cannot allocate memory for EMOS FIFO %d\n",CHANSOUNDER_FIFO_MINOR);
  else 
    printf("[OPENAIR][SCHED][INIT] Problem creating EMOS FIFO %d, error_code %d\n",CHANSOUNDER_FIFO_MINOR,error_code);
#endif

  mlockall(MCL_CURRENT | MCL_FUTURE);

#ifdef RTAI
  // make main thread LXRT soft realtime
  task = rt_task_init_schmod(nam2num("MYTASK"), 9, 0, 0, SCHED_FIFO, 0xF);

  // start realtime timer and scheduler
#ifdef TIMER_ONESHOT_MODE
  rt_set_oneshot_mode();
  start_rt_timer(0);
  printf("started RTAI timer inoneshot mode\n");
#else
  rt_set_periodic_mode();
  period = start_rt_timer(nano2count(500000));
  printf("started RTAI timer with period %llu ns\n",count2nano(period));
#endif

  printf("Init mutex\n");
  //mutex = rt_get_adr(nam2num("MUTEX"));
  mutex = rt_sem_init(nam2num("MUTEX"), 1);
  if (mutex==0)
    {
      printf("Error init mutex\n");
      exit(-1);
    }
  else
    printf("mutex=%p\n",mutex);
#endif

  DAQ_MBOX = (volatile unsigned int *) openair0_exmimo_pci[card].rxcnt_ptr[0];

  // this starts the DMA transfers
  if (UE_flag!=1)
      openair0_start_rt_acquisition(card);


#ifdef XFORMS
  if (do_forms==1) {
      fl_initialize (&argc, argv, NULL, 0, 0);
      form_stats = create_form_stats_form();
      if (UE_flag==1) {
          form_ue[UE_id] = create_lte_phy_scope_ue();
          sprintf (title, "LTE DL SCOPE UE");
          fl_show_form (form_ue[UE_id]->lte_phy_scope_ue, FL_PLACE_HOTSPOT, FL_FULLBORDER, title);
      } else {
            for(UE_id=0;UE_id<scope_enb_num_ue;UE_id++) {
                form_enb[UE_id] = create_lte_phy_scope_enb();
                sprintf (title, "UE%d LTE UL SCOPE eNB",UE_id+1);
                fl_show_form (form_enb[UE_id]->lte_phy_scope_enb, FL_PLACE_HOTSPOT, FL_FULLBORDER, title);
            }
      }
      fl_show_form (form_stats->stats_form, FL_PLACE_HOTSPOT, FL_FULLBORDER, "stats");
      if (UE_flag==0) {
          for (UE_id=0;UE_id<scope_enb_num_ue;UE_id++) {
              if (otg_enabled) {
                  fl_set_button(form_enb[UE_id]->button_0,1);
                  fl_set_object_label(form_enb[UE_id]->button_0,"DL Traffic ON");
              }
              else {
                  fl_set_button(form_enb[UE_id]->button_0,0);
                  fl_set_object_label(form_enb[UE_id]->button_0,"DL Traffic OFF");
              }
          }
      }
      else {
          if (openair_daq_vars.use_ia_receiver) {
              fl_set_button(form_ue[UE_id]->button_0,1);
              fl_set_object_label(form_ue[UE_id]->button_0, "IA Receiver ON");
          }
          else {
              fl_set_button(form_ue[UE_id]->button_0,0);
              fl_set_object_label(form_ue[UE_id]->button_0, "IA Receiver OFF");
          }
      }

      ret = pthread_create(&thread2, NULL, scope_thread, NULL);
      printf("Scope thread created, ret=%d\n",ret);
    }
#endif

#ifdef EMOS
  ret = pthread_create(&thread3, NULL, emos_thread, NULL);
  printf("EMOS thread created, ret=%d\n",ret);
#endif

  rt_sleep_ns(10*FRAME_PERIOD);

#ifndef RTAI
  pthread_attr_init (&attr_dlsch_threads);
  pthread_attr_setstacksize(&attr_dlsch_threads,OPENAIR_THREAD_STACK_SIZE);
  //attr_dlsch_threads.priority = 1;
  sched_param_dlsch.sched_priority = sched_get_priority_max(SCHED_FIFO); //OPENAIR_THREAD_PRIORITY;
  pthread_attr_setschedparam  (&attr_dlsch_threads, &sched_param_dlsch);
  pthread_attr_setschedpolicy (&attr_dlsch_threads, SCHED_FIFO);
#endif

  // start the main thread
  if (UE_flag == 1) {
    /*
#ifdef RTAI
    thread1 = rt_thread_create(UE_thread, NULL, 100000000);
#else
    error_code = pthread_create(&thread1, &attr_dlsch_threads, UE_thread, NULL);
    if (error_code!= 0) {
      LOG_D(HW,"[lte-softmodem.c] Could not allocate UE_thread, error %d\n",error_code);
      return(error_code);
    }
    else {
      LOG_D(HW,"[lte-softmodem.c] Allocate UE_thread successful\n");
    }
#endif
#ifdef DLSCH_THREAD
    init_rx_pdsch_thread();
    rt_sleep_ns(FRAME_PERIOD/10);
    init_dlsch_threads();
#endif
    printf("UE threads created\n");
    */
  }
  else {
#ifdef RTAI
    thread0 = rt_thread_create(eNB_thread, NULL, 100000000);
#else
    error_code = pthread_create(&thread0, &attr_dlsch_threads, eNB_thread, NULL);
    if (error_code!= 0) {
      LOG_D(HW,"[lte-softmodem.c] Could not allocate eNB_thread, error %d\n",error_code);
      return(error_code);
    }
    else {
      LOG_D(HW,"[lte-softmodem.c] Allocate eNB_thread successful\n");
    }
#endif
#ifdef ULSCH_THREAD
    init_ulsch_threads();
#endif
    printf("eNB threads created\n");
  }


  // wait for end of program
  printf("TYPE <CTRL-C> TO TERMINATE\n");
  //getchar();
  while (oai_exit==0)
    rt_sleep_ns(FRAME_PERIOD);

  // stop threads
#ifdef XFORMS
  printf("waiting for XFORMS thread\n");
  if (do_forms==1)
    {
      pthread_join(thread2,&status);
        fl_hide_form(form_stats->stats_form);
        fl_free_form(form_stats->stats_form);
        if (UE_flag==1) {
            fl_hide_form(form_ue[UE_id]->lte_phy_scope_ue);
            fl_free_form(form_ue[UE_id]->lte_phy_scope_ue);
        } else {
            for(UE_id=0;UE_id<scope_enb_num_ue;UE_id++) {
                fl_hide_form(form_enb[UE_id]->lte_phy_scope_enb);
                fl_free_form(form_enb[UE_id]->lte_phy_scope_enb);
            }
        }
    }
#endif

  printf("stopping MODEM threads\n");
  // cleanup
  if (UE_flag == 1) {
    /*
#ifdef RTAI
    rt_thread_join(thread1); 
#else
    pthread_join(thread1,&status); 
#endif
#ifdef DLSCH_THREAD
    cleanup_dlsch_threads();
    cleanup_rx_pdsch_thread();
#endif
    */
  }
  else {
#ifdef RTAI
    rt_thread_join(thread0); 
#else
    pthread_join(thread0,&status); 
#endif
#ifdef ULSCH_THREAD
    cleanup_ulsch_threads();
#endif
  }

#ifdef OPENAIR2
  //cleanup_pdcp_thread();
#endif

#ifdef RTAI
  stop_rt_timer();
#endif

  printf("stopping card\n");
  openair0_stop(card);
  printf("closing openair0_lib\n");
  openair0_close();

#ifdef EMOS
  printf("waiting for EMOS thread\n");
  pthread_cancel(thread3);
  pthread_join(thread3,&status);
#endif

#ifdef EMOS
  error_code = rtf_destroy(CHANSOUNDER_FIFO_MINOR);
  printf("[OPENAIR][SCHED][CLEANUP] EMOS FIFO closed, error_code %d\n", error_code);
#endif

  if (ouput_vcd)
    vcd_signal_dumper_close();

  logClean();

  return 0;
}
void *init_task(void *arg)
{
	RT_TASK *Task;
	struct thread_param *config = (struct thread_param*) arg;
	int idTask = config->idTask;
	unsigned long pidTask = 0;
	unsigned int cpuFrequencyAtual = 0; // KHz

	RTIME Tinicio;
	RTIME Tperiodo = 0; // unidade -> counts
	double Tperiodo_s = 0.0;
	int prioridade = config->prioridade;

//	clock_t begin, end;
//	double time_spent;

	struct timeval  tv1, tv2;

	if(!(Task = rt_thread_init(idTask, prioridade, 0, SCHED_FIFO, CPU_ALLOWED)))
	{
		printf("[ERRO] Não foi possível criar a tarefa [%d].\n", idTask);
		exit(1);
	}

	Tinicio = start_timeline;
	Tperiodo = config->periodo;
	Tperiodo_s = count2nano(Tperiodo)/1000000000.0;

	rt_allow_nonroot_hrt();
	rt_task_make_periodic(Task, Tinicio, Tperiodo);
	rt_change_prio(Task, prioridade);
	if(config->deadline > 0)
		rt_set_deadline(Task, config->deadline);

	pidTask = rt_cfg_get_pid(Task);
	printf("[TASK %2d] [%lu] Criada com Sucesso  =============== PERIODO => %llu count => %.2f segundos \n", idTask, pidTask, Tperiodo, Tperiodo_s);

	cpuFrequencyAtual = rt_cfg_cpufreq_get(CPUID_RTAI);
	printf("[TASK %2d] [%lu] Curr Freq: %8d Khz\n", idTask, pidTask, cpuFrequencyAtual);

	//TODO: TEMPO DE COMPUTACAO - OPCAO 1
//	begin = clock();
//	rt_cfg_set_cpu_frequency(Task, (int) config->cpuFrequencyMin);
//	end = clock();
//
//	time_spent = (double)(end - begin) / CLOCKS_PER_SEC;
//	printf("[TASK %2d] [%lu] SET_FREQUENCY(%8d Khz);\n", idTask, pidTask, config->cpuFrequencyMin);
//	cpuFrequencyAtual = rt_cfg_cpufreq_get(CPUID_RTAI);
//	printf("[TASK %2d] [%lu] Curr Freq: %8d Khz\n", idTask, pidTask, cpuFrequencyAtual);
//	printf("[TASK %2d] [%lu] TEMPO DE COMPUTACAO SET FREQUENCY - USERSPACE => %.100f segundos\n", idTask, pidTask, time_spent);

	//TODO: TEMPO DE COMPUTACAO - OPCAO 2
	gettimeofday(&tv1, NULL);
	rt_cfg_set_cpu_frequency(Task, (int) config->cpuFrequencyMin);
	gettimeofday(&tv2, NULL);

	printf("[TASK %2d] [%lu] SET_FREQUENCY(%8d Khz);\n", idTask, pidTask, config->cpuFrequencyMin);
	cpuFrequencyAtual = rt_cfg_cpufreq_get(CPUID_RTAI);
	printf("[TASK %2d] [%lu] Curr Freq: %8d Khz\n", idTask, pidTask, cpuFrequencyAtual);
	printf("[TASK %2d] [%lu] TEMPO DE COMPUTACAO SET FREQUENCY - USERSPACE => %.50f segundos\n", idTask, pidTask, (double) (tv2.tv_usec - tv1.tv_usec) / 1000000 +
	         (double) (tv2.tv_sec - tv1.tv_sec));
	rt_task_delete(Task);

	return 0;
}
Beispiel #18
0
int sineoutput()
 {
    //Initial test function to try out Real time stuff.
    int m, i=0;
    lsampl_t data_to_card;
    static comedi_t * dev;
    RTIME ElapsedTime;

    dev = comedi_open(device_names[AnalogOutputChannel.board_number]);

    if(!(Sinewaveloop_Task = rt_task_init_schmod(nam2num( "Sinewave" ), // Name
                                        2, // Priority
                                        0, // Stack Size
                                        0, //, // max_msg_size
                                        SCHED_FIFO, // Policy
                                        CPUMAP ))) // cpus_allowed
        {
            printf("ERROR: Cannot initialize sinewave task\n");
            exit(1);
        }

    //specify that this is to run on one CPU
    //rt_set_runnable_on_cpuid(Sinewaveloop_Task, 0);
    //Convert samp_time, which is in nanoseconds, to tick time
    //sampling_interval = nano2count(SAMP_TIME);  //Converts a value from
                                                //nanoseconds to internal count units.
    mlockall(MCL_CURRENT|MCL_FUTURE);
    rt_make_hard_real_time();
    sampling_interval =nano2count_cpuid(SAMP_TIME, 0);
     rt_printk("Sampling interval is %f12 \n",count2nano((float) sampling_interval));
    // Let's make this task periodic..
    expected = rt_get_time_cpuid(0) + 100*sampling_interval;

    //Manan changed all the timer commands to _couid version on 10/22/2012 to see if it helps
    //sampling_interval =nano2count_cpuid(SAMP_TIME,0);
    // rt_printk("Sampling interval is %f12 \n",count2nano_cpuid((float) sampling_interval,0));
    // Let's make this task periodic..
    //expected = rt_get_time_cpuid(0) + 100*sampling_interval;

    rt_task_make_periodic(Sinewaveloop_Task, expected, sampling_interval); //period in counts
    //rt_task_resume(Sinewaveloop_Task);
    sine_loop_running=1;



    // Concurrent function Loop


     rt_printk("SineWaveAmplitude is is %f \n",SineWaveAmplitude);
     rt_printk("SineWaveFrequency is %f \n",SineWaveFrequency);
     rt_printk("sine_loop_running is %d \n",sine_loop_running);
     rt_printk("SAMP_TIME is %d \n",SAMP_TIME);
     //start_time = (float)rt_get_time_ns_cpuid(0)/1E9; //in seconds
     start_time = (float)rt_get_time_ns_cpuid(0)/1E9;
     old_time = start_time;
     rt_printk("AnalogOutputChannel board_it is %p \n",AnalogOutputChannel.board_id);
     rt_printk("AnalogOutputChannel devicename is %p \n",*(AnalogOutputChannel.devicename));
     rt_printk("AnalogOutputChannel boardname is %p \n",*(AnalogOutputChannel.boardname));
     rt_printk("AnalogOutputChannel subdevice is %d \n",AnalogOutputChannel.subdevice);
     rt_printk("AnalogOutputChannel channel is %d \n",AnalogOutputChannel.channel);
     //OutputValue = 1;
     //ElapsedTime = 0;
     OutputValue = 0;
     //sine_loop_running = 0;  //set this to 0 for testing
     while(sine_loop_running)
     {
        i++; // Count Loops.
        current_time = (float)rt_get_time_ns_cpuid(0)/1E9;
        //current_ticks = rt_get_time_cpuid(0);
        //current_time = (float) (count2nano_cpuid(current_ticks,0)/1E9);
        //current_time = (float)rt_get_time_ns_cpuid(0)/1E9;
        //rt_printk("LOOP %d,-- Period time: %f12 %f12\n",i, current_time - old_time,count2nano((float)sampling_interval)/1E9);
        OutputValue = SineWaveAmplitude*sin(2*PI*SineWaveFrequency*(current_time-start_time));
        //OutputValue+=((SAMP_TIME*PI*2*SineWaveFrequency)/1E9)*cos(2*PI*SineWaveFrequency*((float)SAMP_TIME)/1E9);
        //if (OutputValue>10.0)
        //{OutputValue =  -10;
        //}
        //OutputValue = SineWaveAmplitude*sin(2*PI*SineWaveFrequency*((float)ElapsedTime)/1E9);
        ElapsedTime+=SAMP_TIME;
        //OutputValue = -1*OutputValue;
        //rt_printk("OutputValue is %f12 \n",OutputValue);
        data_to_card = (lsampl_t) nearbyint(((OutputValue - MinOutputVoltage)/OutputRange)*MaxOutputBits);
        //m=rt_comedi_command_data_write(AnalogOutputChannel.board_id, AnalogOutputChannel.subdevice, NCHAN, data_to_card);
        comedi_lock(dev, AnalogOutputChannel.subdevice);
        m=comedi_data_write(dev, AnalogOutputChannel.subdevice, AnalogOutputChannel.channel, AO_RANGE, AREF_DIFF, data_to_card);
        comedi_unlock(dev, AnalogOutputChannel.subdevice);
//        m=comedi_data_write(AnalogOutputChannel.board_id, AnalogOutputChannel.subdevice,
//               AnalogOutputChannel.channel, AO_RANGE, AREF_GROUND, data_to_card);
        //rt_printk("Data_to_card is %d; result from rt_comedi_command_data_write is %d \n",data_to_card, m);
        //rt_printk("LOOP %d,-- Loop time: %f12 \n",i, (float)(current_time-old_time));
        //rt_printk("LOOP %d,-- AO Out time: %f12 \n",i, (float)rt_get_time_ns()/1E9 - current_time);
        //rt_printk("LOOP %d,-- AO Out time: %f12 \n",i, (float)rt_get_cpu_time_ns()/1E9 - current_time);
        //rt_printk("Data_to_card is %d \n",data_to_card);
        old_time = current_time;
/*        if (i== 100000)
        {
            sine_loop_running = 0;
            //printf("LOOP -- run: %d %d\n ",keep_on_running,&keep_on_running);
            //printf("RTAI LOOP -- run: %d \n ",i);
            break;
        }
*/
        rt_task_wait_period(); // And waits until the end of the period.

    }
    rt_make_soft_real_time();
    comedi_close(dev);
    rt_task_delete(Sinewaveloop_Task); //Self termination at end.

    pthread_exit(NULL);
    return 0;
 }
Beispiel #19
0
int PLLReferenceGeneration()
 {
    //Initial test function to try out Real time stuff.
    int m, i=0, err, n;
    lsampl_t data_to_card;
    static comedi_t * dev;
    static int OutputFIFOBufferSize;
    static int PLLGenerationBufferSize;
	unsigned int maxdata;
	unsigned int chanlist[16];
	int ret;
    static lsampl_t data[PLLGenerationBufferNPoints]; //this is the buffer used to send data points out
    comedi_cmd cmd;

    dev = comedi_open(device_names[PLLReferenceGenerationChannel.board_number]);

    //Check the size of the output buffer
    OutputFIFOBufferSize = comedi_get_buffer_size(dev, PLLReferenceGenerationChannel.subdevice);
    rt_printk("OutputFIFO Buffer size is %i\n", OutputFIFOBufferSize);

    //Set the actual buffer size that we will be using to half this and the number of data points to one fourth
    //Now configure the output channel using a Comedi instruction
    //BufferSize is initially set to be double the number of PLLGenerationBufferNPoints
    PLLGenerationBufferSize = 2*PLLGenerationBufferNPoints;


	maxdata = comedi_get_maxdata(dev, PLLReferenceGenerationChannel.subdevice, PLLReferenceGenerationChannel.channel);
	rt_printk("PLL Reference channel max data is %i\n", maxdata);

	offset = maxdata / 2;
	amplitude = maxdata - offset;

	memset(&cmd,0,sizeof(cmd));
	cmd.subdev = PLLReferenceGenerationChannel.subdevice;
	cmd.flags = CMDF_WRITE;
	cmd.start_src = TRIG_INT;
	cmd.start_arg = 0;
	cmd.scan_begin_src = TRIG_TIMER;
	cmd.scan_begin_arg = PLLGenMinPulseTime;  //minimum update time for the
	cmd.convert_src = TRIG_NOW;
	cmd.convert_arg = 0;
	cmd.scan_end_src = TRIG_COUNT;
	cmd.scan_end_arg = NCHAN; //only one channel
	cmd.stop_src = TRIG_NONE;
	cmd.stop_arg = 0;

	cmd.chanlist = chanlist;
	cmd.chanlist_len = NCHAN;

	chanlist[0] = CR_PACK(PLLReferenceGenerationChannel.channel, AO_RANGE, AREF_GROUND);

	dds_init(PLLWaveformFrequency, PLLUpdateFrequency);

	err = comedi_command_test(dev, &cmd);
	if (err < 0) {
		comedi_perror("comedi_command_test");
		exit(1);
	}

	err = comedi_command_test(dev, &cmd);
	if (err < 0) {
		comedi_perror("comedi_command_test");
		exit(1);
	}

	if ((err = comedi_command(dev, &cmd)) < 0) {
		comedi_perror("comedi_command");
		exit(1);
	}

	dds_output(data,PLLGenerationBufferNPoints);
	n = PLLGenerationBufferNPoints * sizeof(sampl_t);
	m = write(comedi_fileno(dev), (void *)data, n);
	if(m < 0){
		perror("write");
		exit(1);
	}else if(m < n)
	{
		fprintf(stderr, "failed to preload output buffer with %i bytes, is it too small?\n"
			"See the --write-buffer option of comedi_config\n", n);
		exit(1);
	}

    if(!(PLLRefGen_Task = rt_task_init_schmod(nam2num( "PLLReferenceGeneration" ), // Name
                                        2, // Priority
                                        0, // Stack Size
                                        0, //, // max_msg_size
                                        SCHED_FIFO, // Policy
                                        CPUMAP ))) // cpus_allowed
        {
            printf("ERROR: Cannot initialize pll reference generation task\n");
            exit(1);
        }

    //specify that this is to run on one CPU
    rt_set_runnable_on_cpuid(PLLRefGen_Task, 1);
    //Convert samp_time, which is in nanoseconds, to tick time
    //sampling_interval = nano2count(SAMP_TIME);  //Converts a value from
                                                //nanoseconds to internal count units.
    mlockall(MCL_CURRENT|MCL_FUTURE);
    rt_make_hard_real_time();
    PLLUpdateTime = nano2count(PLLGenerationLoopTime);
    rt_printk("PLL generation update time is %f12 \n",count2nano((float) PLLUpdateTime));
    // Let's make this task periodic..
    expected = rt_get_time() + 100*PLLUpdateTime;



    rt_task_make_periodic(PLLRefGen_Task, expected, PLLUpdateTime); //period in counts
    //rt_task_resume(Sinewaveloop_Task);
    PLLGenerationOn = TRUE;



    // Concurrent function Loop


     //rt_printk("SineWaveAmplitude is is %f \n",SineWaveAmplitude);
     //rt_printk("SineWaveFrequency is %f \n",SineWaveFrequency);
     //rt_printk("sine_loop_running is %d \n",sine_loop_running);
     //rt_printk("SAMP_TIME is %d \n",SAMP_TIME);
     start_time = (float)rt_get_time_ns()/1E9; //in seconds
     old_time = start_time;
     rt_printk("PLLReferenceGenerationChannel board_it is %p \n",PLLReferenceGenerationChannel.board_id);
     rt_printk("PLLReferenceGenerationChannel devicename is %p \n",*(PLLReferenceGenerationChannel.devicename));
     rt_printk("PLLReferenceGenerationChannel boardname is %p \n",*(PLLReferenceGenerationChannel.boardname));
     rt_printk("PLLReferenceGenerationChannel subdevice is %d \n",PLLReferenceGenerationChannel.subdevice);
     rt_printk("PLLReferenceGenerationChannel channel is %d \n",PLLReferenceGenerationChannel.channel);
     OutputValue = 1;
     PLLGenerationBufferSize = comedi_get_buffer_size(dev, PLLReferenceGenerationChannel.subdevice);
     //sine_loop_running = 0;  //set this to 0 for testing
     while(PLLGenerationOn)
     {
        i++; // Count Loops.
        current_time = (float)rt_get_time_ns()/1E9;
        //rt_printk("LOOP %d,-- Period time: %f12 %f12\n",i, current_time - old_time,count2nano((float)sampling_interval)/1E9);
        OutputValue = SineWaveAmplitude*sin(2*PI*SineWaveFrequency*(current_time-start_time));
        //OutputValue = -1*OutputValue;
        //rt_printk("OutputValue is %f12 \n",OutputValue);
        data_to_card = (lsampl_t) nearbyint(((OutputValue - MinOutputVoltage)/OutputRange)*MaxOutputBits);
        //m=rt_comedi_command_data_write(AnalogOutputChannel.board_id, AnalogOutputChannel.subdevice, NCHAN, data_to_card);
        comedi_lock(dev, AnalogOutputChannel.subdevice);
        m=comedi_data_write(dev, AnalogOutputChannel.subdevice, AnalogOutputChannel.channel, AO_RANGE, AREF_DIFF, data_to_card);
        comedi_unlock(dev, AnalogOutputChannel.subdevice);
//        m=comedi_data_write(AnalogOutputChannel.board_id, AnalogOutputChannel.subdevice,
//               AnalogOutputChannel.channel, AO_RANGE, AREF_GROUND, data_to_card);
        //rt_printk("Data_to_card is %d; result from rt_comedi_command_data_write is %d \n",data_to_card, m);
        //rt_printk("LOOP %d,-- AO Out time: %f12 \n",i, (float)rt_get_time_ns()/1E9 - current_time);
        //rt_printk("Data_to_card is %d \n",data_to_card);
        //old_time = current_time;
/*        if (i== 100000)
        {
            sine_loop_running = 0;
            //printf("LOOP -- run: %d %d\n ",keep_on_running,&keep_on_running);
            //printf("RTAI LOOP -- run: %d \n ",i);
            break;
        }
*/
        rt_task_wait_period(); // And waits until the end of the period.

    }
    rt_make_soft_real_time();
    comedi_close(dev);
    rt_task_delete(Sinewaveloop_Task); //Self termination at end.

    pthread_exit(NULL);
    return 0;
 }
Beispiel #20
0
NANO_TIME ticks2nano(TICK_TIME t) { return count2nano(t); }
Beispiel #21
0
int main(int argc, char *argv[])
{
	int sock;
	struct sockaddr_in SPRT_ADDR;
	char buf[200];
	int fd;

	int diff;
	int sample;
	int average;
	int min_diff;
	int max_diff;
	int period;
	int i;
	int cnt;
	RTIME t, svt;
	RTIME expected, exectime[3];
	RT_TASK *task;
	long long max = -1000000000, min = 1000000000;
	struct sample { long long min; long long max; int index, ovrn; } samp;
	double s, sref;

 	if (!(task = rt_task_init_schmod(nam2num("LATCAL"), 0, 0, 0, SCHED_FIFO, 0xF))) {
		printf("CANNOT INIT MASTER LATENCY TASK\n");
		exit(1);
	}

	sock = socket(AF_INET, SOCK_DGRAM, 0);
	bzero(&SPRT_ADDR, sizeof(struct sockaddr_in));
	SPRT_ADDR.sin_family = AF_INET;
	SPRT_ADDR.sin_port = htons(5000);
	SPRT_ADDR.sin_addr.s_addr = inet_addr("127.0.0.1");

	fd = open("echo", O_RDWR | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP);

	printf("\n## RTAI latency calibration tool ##\n");
	printf("# period = %i (ns) \n", PERIOD);
	printf("# average time = %i (s)\n", (int)AVRGTIME);
	printf("# use the FPU\n");
	printf("#%sstart the timer\n", argc == 1 ? " " : " do not ");
	printf("# timer_mode is %s\n", TIMER_MODE ? "periodic" : "oneshot");
	printf("\n");

	rt_sync_async_linux_syscall_server_create(NULL, ASYNC_LINUX_SYSCALL, async_callback, 120);

	if (!(hard_timer_running = rt_is_hard_timer_running())) {
		if (TIMER_MODE) {
			rt_set_periodic_mode();
		} else {
			rt_set_oneshot_mode();
		}
		period = start_rt_timer(nano2count(PERIOD));
	} else {
		period = nano2count(PERIOD);
	}

        for(i = 0; i < MAXDIM; i++) {
                a[i] = b[i] = 3.141592;
        }
	sref = dot(a, b, MAXDIM);
	s = 0.0;

	mlockall(MCL_CURRENT | MCL_FUTURE);

	rt_make_hard_real_time();
	expected = rt_get_time() + 200*period;
	rt_task_make_periodic(task, expected, period);
	svt = rt_get_cpu_time_ns();
	cnt = 0;
	i = 0;
	samp.ovrn = 0;
	while (!end) {
		min_diff = 1000000000;
		max_diff = -1000000000;
		average = 0;

		for (sample = 0; sample < SMPLSXAVRG && !end; sample++) {
			expected += period;
			if (!rt_task_wait_period()) {
				if (TIMER_MODE) {
					diff = (int) ((t = rt_get_cpu_time_ns()) - svt - PERIOD);
					svt = t;
				} else {
					diff = (int) count2nano(rt_get_time() - expected);
				}
			} else {
				samp.ovrn++;
				diff = 0;
				if (TIMER_MODE) {
					svt = rt_get_cpu_time_ns();
				}
			}

			if (diff < min_diff) {
				min_diff = diff;
			}
			if (diff > max_diff) {
				max_diff = diff;
			}
			average += diff;
			s = dot(a, b, MAXDIM);
			if (fabs(s/sref - 1.0) > 1.0e-16) {
				printf("\nDOT PRODUCT RESULT = %lf %lf %lf\n", s, sref, sref - s);
				return 0;
			}
		}
		samp.min = min_diff;
		samp.max = max_diff;
		samp.index = average/SMPLSXAVRG;
		if (max < samp.max) max = samp.max;
		if (min > samp.min) min = samp.min;
		++cnt;
//		printf("* %d - min: %lld/%lld, max: %lld/%lld average: %d <RET to stop> %d *\n", cnt, samp.min, min, samp.max, max, samp.index, samp.ovrn);
		sprintf(buf, "* %d - min: %lld/%lld, max: %lld/%lld average: %d <RET to stop> %d *\n", cnt, samp.min, min, samp.max, max, samp.index, samp.ovrn);
		i = write(STDOUT_FILENO, buf, strlen(buf));
		fdatasync(STDOUT_FILENO);
		i = write(fd, buf, strlen(buf));
		fsync(fd);
		sendto(sock, buf, strlen(buf), 0, (struct sockaddr *)&SPRT_ADDR, sizeof(struct sockaddr_in));
	}

	close(sock);
	close(fd);
	rt_make_soft_real_time();
	if (!hard_timer_running) {
		stop_rt_timer();
	}
	rt_get_exectime(task, exectime);
	if (exectime[1] && exectime[2]) {
		printf("\n>>> S = %g, EXECTIME = %G\n", s, (double)exectime[0]/(double)(exectime[2] - exectime[1]));
	}
	rt_task_delete(task);

	return 0;
}
Beispiel #22
0
int main(int argc, char *argv[])
{
	int diff;
	int sample;
	long average;
	int min_diff;
	int max_diff;
	int period;
	int i;
	RTIME t, svt;
	RTIME expected, exectime[3];
	MBX *mbx;
	RT_TASK *task, *latchk;
	struct sample { long long min; long long max; int index, ovrn; } samp;
	double s = 0.0, sref;
	long long max = -1000000000, min = 1000000000;

	signal(SIGINT, endme);
	signal(SIGKILL, endme);
	signal(SIGTERM, endme);

 	if (!(mbx = rt_mbx_init(nam2num("LATMBX"), 20*sizeof(samp)))) {
		printf("CANNOT CREATE MAILBOX\n");
		exit(1);
	}

 	if (!(task = rt_task_init_schmod(nam2num("LATCAL"), 0, 0, 0, SCHED_FIFO, 0xF))) {
		printf("CANNOT INIT MASTER LATENCY TASK\n");
		exit(1);
	}

	printf("\n## RTAI latency calibration tool ##\n");
	printf("# period = %i (ns) \n", PERIOD);
	printf("# average time = %i (s)\n", (int)AVRGTIME);
	printf("# use the FPU\n");
	printf("#%sstart the timer\n", argc == 1 ? " " : " do not ");
	printf("# timer_mode is %s\n", TIMER_MODE ? "periodic" : "oneshot");
	printf("\n");

	if (!(hard_timer_running = rt_is_hard_timer_running())) {
		if (TIMER_MODE) {
			rt_set_periodic_mode();
		} else {
			rt_set_oneshot_mode();
		}
		period = start_rt_timer(nano2count(PERIOD));
	} else {
		period = nano2count(PERIOD);
	}

	for(i = 0; i < MAXDIM; i++) {
		a[i] = b[i] = 3.141592;
	}
	sref = dot(a, b, MAXDIM);

	mlockall(MCL_CURRENT | MCL_FUTURE);

	rt_make_hard_real_time();
	expected = rt_get_time() + 200*period;
	rt_task_make_periodic(task, expected, period);
	svt = rt_get_cpu_time_ns();
	i = 0;
	samp.ovrn = 0;
	while (!end) {
		min_diff = 1000000000;
		max_diff = -1000000000;
		average = 0;

		for (sample = 0; sample < SMPLSXAVRG && !end; sample++) {
			expected += period;
			if (!rt_task_wait_period()) {
				if (TIMER_MODE) {
					diff = (int) ((t = rt_get_cpu_time_ns()) - svt - PERIOD);
					svt = t;
				} else {
					diff = (int) count2nano(rt_get_time() - expected);
				}
			} else {
				samp.ovrn++;
				diff = 0;
				if (TIMER_MODE) {
					svt = rt_get_cpu_time_ns();
				}
			}
			outb(i = 1 - i, 0x378);

			if (diff < min_diff) {
				min_diff = diff;
			}
			if (diff > max_diff) {
				max_diff = diff;
			}
			average += diff;
			s = dot(a, b, MAXDIM);
			if (fabs((s - sref)/sref) > 1.0e-15) {
				printf("\nDOT PRODUCT RESULT = %20.16e %20.16e %20.16e\n", s, sref, fabs((s - sref)/sref));
				return 0;
			}
		}
		samp.min = min_diff;
		samp.max = max_diff;
		samp.index = average/SMPLSXAVRG;
#if SOLO
		if (max < samp.max) max = samp.max;
		if (min > samp.min) min = samp.min;
		rt_printk("SOLO * min: %lld/%lld, max: %lld/%lld average: %d (%d) <Hit [RETURN] to stop> *\n", samp.min, min, samp.max, max, samp.index, samp.ovrn);
#else
		rt_mbx_send_if(mbx, &samp, sizeof(samp));
		if ((latchk = rt_get_adr(nam2num("LATCHK"))) && (rt_receive_if(latchk, &average) || end)) {
			rt_return(latchk, average);
			break;
		}
#endif
	}

	while (rt_get_adr(nam2num("LATCHK"))) {
		rt_sleep(nano2count(1000000));
	}
	rt_make_soft_real_time();
	if (!hard_timer_running) {
		stop_rt_timer();
	}
	rt_get_exectime(task, exectime);
	if (exectime[1] && exectime[2]) {
		printf("\n>>> S = %g, EXECTIME = %G\n", s, (double)exectime[0]/(double)(exectime[2] - exectime[1]));
	}
	rt_task_delete(task);
	rt_mbx_delete(mbx);

	return 0;
}
Beispiel #23
0
int main(int argc, char *argv[])
{
	RTIME until;
	RT_TASK *task;
	comedi_insn insn[NCHAN];
	unsigned int read_chan[NICHAN]  = { 2, 3, 4, 5, 6 };
	unsigned int write_chan[NOCHAN] = { 0, 1 };
#if !SINGLE_INSN
	comedi_insnlist ilist = { NCHAN, insn };
#endif
#if SIN_FREQ
	lsampl_t sinewave;
	double omega = (2.0*M_PI*SIN_FREQ)/1.0E9;
	double actualtime;
#endif
	lsampl_t *hist;
	lsampl_t data[NCHAN];
	long i, k, n, retval;
	int toggle;
	FILE *fp;
	struct sockaddr_in addr;

	signal(SIGKILL, endme);
	signal(SIGTERM, endme);
	hist = malloc(SAMP_FREQ*RUN_TIME*NCHAN*sizeof(lsampl_t) + 1000);
	memset(hist, 0, SAMP_FREQ*RUN_TIME*NCHAN*sizeof(lsampl_t) + 1000);

	start_rt_timer(0);
	task = rt_task_init_schmod(nam2num("MYTASK"), 1, 0, 0, SCHED_FIFO, 0xF);

	daqnode = 0;
	if (argc == 2 && strstr(argv[1], "RcvNode=")) {
		inet_aton(argv[1] + 8, &addr.sin_addr);
		daqnode = addr.sin_addr.s_addr;
	}
	if (!daqnode) {
		inet_aton("127.0.0.1", &addr.sin_addr);
		daqnode = addr.sin_addr.s_addr;
	}
	while ((daqport = rt_request_port(daqnode)) <= 0 && daqport != -EINVAL);

	mlockall(MCL_CURRENT | MCL_FUTURE);
	printf("COMEDI INSN%s TEST BEGINS: SAMPLING FREQ: %d, RUN TIME: %d, NODE: %x, PORT: %d.\n", SINGLE_INSN ? "" : "LIST", SAMP_FREQ, RUN_TIME, daqnode, daqport);
	rt_make_hard_real_time();

	if (init_board()) {;
		printf("Board initialization failed.\n");
		return 1;
	}

	for (i = 0; i < NICHAN; i++) {
		BUILD_AREAD_INSN(insn[i], subdevai, data[i], 1, read_chan[i], AI_RANGE, AREF_GROUND);
	}
	for (i = 0; i < NOCHAN; i++) {
		BUILD_AWRITE_INSN(insn[NICHAN + i], subdevao, data[NICHAN + i], 1, write_chan[i], AO_RANGE, AREF_GROUND);
	}

	until = rt_get_time();
	for (toggle = n = k = 0; k < SAMP_FREQ*RUN_TIME && !end /*SAMP_FREQ*RUN_TIME && !end*/; k++) {
#if SIN_FREQ
		actualtime = count2nano(rt_get_time());
		sinewave =  (int) (maxdatao/8*sin(omega*actualtime));
		data[NICHAN]     =  sinewave+maxdatao/2;
		data[NICHAN + 1] = -sinewave+maxdatao/2;
#else
		data[NICHAN]     = toggle*maxdatao/2;
		data[NICHAN + 1] = (1 - toggle)*maxdatao/2;
		toggle = 1 - toggle;
#endif

#if SINGLE_INSN
		for (i = 0; i < NCHAN; i++) {
			if ((retval = RT_comedi_do_insn(daqnode, daqport, dev, insn + i)) > 0) {
				 hist[n++] = data[i];
			} else {
				printf("Comedi insn failed # %ld out of %d instructions, retval %ld.\n", i, NCHAN, retval);
				break;
			}
		}
#else
		if ((retval = RT_comedi_do_insnlist(daqnode, daqport, dev, &ilist)) == NCHAN) {
			for (i = 0; i < NCHAN; i++) {
				 hist[n++] = data[i];
			}
		} else {
			printf("Comedi insnlist processed only %lu out of %d instructions.\n", retval, NCHAN);
			break;
		}
#endif
		rt_sleep_until(until += nano2count(SAMP_TIME));
	}

	RT_comedi_cancel(daqnode, daqport, dev, subdevai);
	RT_comedi_cancel(daqnode, daqport, dev, subdevao);
	RT_comedi_data_write(daqnode, daqport, dev, subdevao, 0, 0, AREF_GROUND, 2048);
	RT_comedi_data_write(daqnode, daqport, dev, subdevao, 1, 0, AREF_GROUND, 2048);
	RT_comedi_close(daqnode, daqport, dev);
	printf("COMEDI INSN%s ENDS.\n", SINGLE_INSN ? "" : "LIST");

	fp = fopen("rec.dat", "w");
	for (n = k = 0; k < SAMP_FREQ*RUN_TIME; k++) {
		fprintf(fp, "# %ld: ", k);
		for (i = 0; i < NCHAN; i++) {
			fprintf(fp, "%d\t", hist[n++]);
		}
		fprintf(fp, "\n");
	}
	fclose(fp);
	free(hist);

	stop_rt_timer();
	rt_make_soft_real_time();
	rt_task_delete(task);

	return 0;
}
Beispiel #24
0
int main(void)
{
	RTIME until;
	RT_TASK *task;
	comedi_insn insn[NCHAN];
        unsigned int read_chan[NICHAN]  = { 0 };
        unsigned int write_chan[NOCHAN] = { 0 };
#if !SINGLE_INSN
	comedi_insnlist ilist = { NCHAN, insn };
#endif
#if SIN_FREQ
	lsampl_t sinewave;
	double omega = (2.0*M_PI*SIN_FREQ)/1.0E9;
	double actualtime;
#endif
	lsampl_t *hist;
	lsampl_t data[NCHAN];
	long i, k, n, retval;
	int toggle;
	FILE *fp;

	double tms[2];

#if SINGLE_INSN
	printf("single insn true\n");
#endif
#if SIN_FREQ
	printf(" true\n");
#endif
	signal(SIGKILL, endme);
	signal(SIGTERM, endme);
	hist = malloc(SAMP_FREQ*RUN_TIME*NCHAN*sizeof(lsampl_t) + 1000);
	memset(hist, 0, SAMP_FREQ*RUN_TIME*NCHAN*sizeof(lsampl_t) + 1000);

	start_rt_timer(0);
	task = rt_task_init_schmod(nam2num("MYTASK"), 1, 0, 0, SCHED_FIFO, 0xF);
	printf("COMEDI INSN%s TEST BEGINS: SAMPLING FREQ: %d, RUN TIME: %d.\n", SINGLE_INSN ? "" : "LIST", SAMP_FREQ, RUN_TIME);
	mlockall(MCL_CURRENT | MCL_FUTURE);
	rt_make_hard_real_time();

	if (init_board()) {;
		printf("Board initialization failed.\n");
		return 1;
	}

        for (i = 0; i < NICHAN; i++) {
		BUILD_AREAD_INSN(insn[i], subdevai, data[i], 1, read_chan[i], AI_RANGE, AREF_GROUND);
        }
        for (i = 0; i < NOCHAN; i++) {
		BUILD_AWRITE_INSN(insn[NICHAN + i], subdevao, data[NICHAN + i], 1, write_chan[i], AO_RANGE, AREF_GROUND);
        }
	printf("done building.\n"); fflush (stdout);
	until = rt_get_time();
	for (toggle = n = k = 0; k < SAMP_FREQ*RUN_TIME && !end; k++) {
#if SIN_FREQ
		actualtime = count2nano(rt_get_time());
		if(k<2) tms[k] = actualtime; 
		sinewave =  (int) (maxdatao/8*sin(omega*actualtime));
		data[NICHAN]     =  sinewave+maxdatao/2;
		//data[NICHAN + 1] = -sinewave+maxdatao/2;
#else
		data[NICHAN]     = toggle*maxdatao/2;
		data[NICHAN + 1] = (1 - toggle)*maxdatao/2;
		toggle = 1 - toggle;
#endif
		
#if SINGLE_INSN
		for (i = 0; i < NCHAN; i++) {
			if ((retval = comedi_do_insn(dev, insn + i)) > 0) {
				 hist[n++] = data[i];
			} else {
				printf("Comedi insn failed # %ld out of %d instructions, retval %ld.\n", i, NCHAN, retval);
				break;
			}
		}
#else
		if ((retval = rt_comedi_do_insnlist(dev, &ilist)) == NCHAN) {
			for (i = 0; i < NCHAN; i++) {
				 hist[n++] = data[i];
			}
		} else {
			printf("Comedi insnlist processed only %lu out of %d instructions.\n", retval, NCHAN);
			break;
		}
#endif
		rt_sleep_until(until += nano2count(SAMP_TIME));
	}

	comedi_cancel(dev, subdevai);
	comedi_cancel(dev, subdevao);
	comedi_data_write(dev, subdevao, 0, 0, AREF_GROUND, 2048);
	comedi_data_write(dev, subdevao, 1, 0, AREF_GROUND, 2048);
	comedi_close(dev);
	printf("COMEDI INSN%s ENDS.\n", SINGLE_INSN ? "" : "LIST");
	printf("t1: %g\n", tms[0]);
	printf("t2: %g\n", tms[1]);
	printf("tdiff: %g\n", tms[1]-tms[0]);
	fp = fopen("rec.dat", "w");
	for (n = k = 0; k < SAMP_FREQ*RUN_TIME; k++) {
		fprintf(fp, "# %ld: ", k);
		for (i = 0; i < NCHAN; i++) {
			fprintf(fp, "%d\t", hist[n++]);
		}
		fprintf(fp, "\n");
	}
	fclose(fp);
	free(hist);

	stop_rt_timer();
	rt_make_soft_real_time();
	rt_task_delete(task);

	return 0;
}
Beispiel #25
0
void
fun(long thread)
{

	int diff = 0;
	int i;
	int average;
	int min_diff = 0;
	int max_diff = 0;
	RTIME t, svt;

	/* If we want to make overall statistics */
	/* we have to reset min/max here         */
	if (overall) {
		min_diff =  1000000000;
		max_diff = -1000000000;
	}
#ifdef CONFIG_RTAI_FPU_SUPPORT
	if (use_fpu) {
		for(i = 0; i < MAXDIM; i++) {
			a[i] = b[i] = 3.141592;
		}
	}
	refres = dot(a, b, MAXDIM);
#endif
	svt = rt_get_cpu_time_ns();
	while (1) {

		/* Not overall statistics: reset min/max */
		if (!overall) {
			min_diff =  1000000000;
			max_diff = -1000000000;
		}

		average = 0;
		for (i = 0; i < loops; i++) {
			cpu_used[hard_cpu_id()]++;
			expected += period_counts;
			rt_task_wait_period();

			if (timer_mode) {
				diff = (int) ((t = rt_get_cpu_time_ns()) - svt - period);
				svt = t;
			} else {
				diff = (int) count2nano(rt_get_time() - expected);
			}

			if (diff < min_diff) { min_diff = diff; }
			if (diff > max_diff) { max_diff = diff; }
			average += diff;
#ifdef CONFIG_RTAI_FPU_SUPPORT
			if (use_fpu) {
				dotres = dot(a, b, MAXDIM);
                        	if ((tdif = dotres/refres - 1.0) < 0.0) {
                        		tdif = -tdif;
				}
	                        if (tdif > 1.0e-16) {
      	                          	rt_printk("\nDOT PRODUCT ERROR\n");
                	                return;
                        	}
			}
#endif
		}
		samp.min = min_diff;
		samp.max = max_diff;
		samp.index = average / loops;
		rtf_put(DEBUG_FIFO, &samp, sizeof (samp));
//while(1);
	}
}
static inline void count2timeval(RTIME rt, struct timeval *t)
{
	t->tv_sec = rtai_ulldiv(count2nano(rt), 1000000000, (unsigned long *)&t->tv_usec);
	t->tv_usec /= 1000;
}
void * TestRTAI::rtMethod(void *)
{    
    //////////////////////////////////////////////////
    // Initialize shared memory, RT task, and semaphores.
    
    rtThreadState = RT_THREAD_INIT;
       
    // Switch to use RTAI real-time scheduler
    std::cout << "TestRTAI::rtMethod: Switching to RTAI real-time scheduler..." << std::endl;
    RT_TASK * task = rt_task_init_schmod(
        nam2num("MY_RT_TASK"),    // name
        0,                        // priority
        0,                        // stack size
        0,                        // max_msg_size
        SCHED_FIFO,               // scheduling policy
        0xF                       // CPUs allowed
    );

    if (task == NULL) 
    {
        std::cerr << "TestRTAI::rtMethod: Call to rt_task_init_schmod failed for MY_RT_TASK" << std::endl;
        rtThreadState = RT_THREAD_ERROR;
        return NULL;
    }
    
    rt_allow_nonroot_hrt();
    
    //////////////////////////////////////////////////
    // Start the real time engine...
    
    RTIME tickPeriod = nano2count(rtPeriod_ns);

    std::cout << "TestRTAI::rtMethod: Starting the real-time engine..." << std::endl;

    std::cout << "TestRTAI::rtMethod: Making real-time task periodic, tickPeriod = " << tickPeriod << "..." << std::endl;
    rt_task_make_periodic(task, rt_get_time() + tickPeriod, tickPeriod); 

    std::cout << "TestRTAI::rtMethod: Locking current memory into RAM..." << std::endl;
    mlockall(MCL_CURRENT | MCL_FUTURE);

    std::cout << "TestRTAI::rtMethod: Calling rt_make_hard_read_time()..." << std::endl;
    rt_make_hard_real_time();

    rtThreadState = RT_THREAD_RUNNING;

    //////////////////////////////////////////////////
    // The servo loop.

    bool firstRound = true;

    std::cout << "TestRTAI::rtMethod: starting the servo loop!" << std::endl;
    while (continueRunning) 
    {
        long long const currTime(nano2count(rt_get_cpu_time_ns()));

        if (firstRound)
        {
            std::cout << "TestRTAI::rtmethod: First round" << std::endl;
            firstRound = false;
        }
        else
            std::cout << "TestRTAI::rtmethod: Period = " << (count2nano(currTime - prevTime) / 1e6) << "ms" << std::endl;

        prevTime = currTime;

        rt_task_wait_period();
    }
    
    //////////////////////////////////////////////////
    // Clean up after ourselves.
    
    std::cout << "TestRTAI::rtMethod: Exiting RT thread" << std::endl;
    
    rtThreadState = RT_THREAD_CLEANUP;
    rt_make_soft_real_time();
    rt_task_delete(task);
    return NULL;
}