Example #1
0
/* 
 * Fetch data from a mbox.Wait for at most timeout millisecs
 * Return -1 if timed out otherwise time spent waiting.
 */ 
u32_t sys_arch_mbox_fetch(sys_mbox_t mbox, void **data, u32_t timeout)
{
	void *d;
	cyg_tick_count_t end_time = 0, start_time = 0;
	if (timeout) {
		start_time = cyg_current_time();
		d = cyg_mbox_timed_get(mbox, start_time + msec_to_tick(timeout));
		end_time = cyg_current_time();

		if (d == NULL)
			return SYS_ARCH_TIMEOUT;
	} else {
		d = cyg_mbox_get(mbox);
	}

	if (data) {
		if (d == (void *)&dummy_msg)
			*data = NULL;
		else
			*data = d;
	}

	return tick_to_msec(end_time - start_time);	
}
Example #2
0
/**
   sample sw thread

    @param data: input data for sw thread
*/
void sampling_sw_thread (cyg_addrword_t data){

  //unsigned int thread_number = (unsigned int) data;
    int from, to;
    int done;
    int i;
    int new_message = FALSE;
    int message = 1;
    int message_to_deliver = FALSE;
    timing_t time_start_s = 0, time_stop_s = 0, time_sampling_sw = 0;
    int number_of_measurements_s = 0;
    
    while (42) {

      // 1) if there is no message to delivered, check for new message
      while (message_to_deliver == FALSE && new_message == FALSE){

            message = (int) cyg_mbox_get( mb_sampling_handle[0] );
            if (message > 0 && message <= number_of_blocks){
 
	      //printf("\n[Sampling Thread No. %d] Nachricht %d erhalten", (int) thread_number, message);
	          new_message = TRUE;
		  time_start_s = gettime();
            }
      }

 #ifdef USE_CACHE  
       XCache_EnableDCache( 0xF0000000 );
#endif     

      // 2) if a new message has arrived, sample the particles
      while (new_message == TRUE){

	  new_message = FALSE;

    	  from = (message - 1) * block_size;
          to   = from + block_size - 1;
          if ((N - 1) < to)
	       to = N - 1; 
      
          // sample particles
          for (i=from; i<=to; i++){
          
                  // predict particle
                  prediction (&particles[i]);
          }

          message_to_deliver = TRUE;
      }

#ifdef USE_CACHE  
       XCache_EnableDCache( 0xF0000000 );
#endif
  
      time_stop_s = gettime();
    
      // 3) if a message should be delivered, deliver it
      while ( message_to_deliver == TRUE){

            done = cyg_mbox_tryput( mb_sampling_done_handle[0], ( void * ) message );
           if (done > 0){
	     //printf("\n[Sampling Thread No. %d] Nachricht %d geschickt", (int) thread_number, message);
              message_to_deliver = FALSE;
              time_sampling_sw = calc_timediff( time_start_s, time_stop_s );
              number_of_measurements_s++;
              //diag_printf("\nSampling SW: %d, \tmessage %d, \ttime: %d", number_of_measurements_s, message, time_sampling_sw);
           }
      }
          
   }
}
Example #3
0
/**
   observation sw thread

    @param data: input data for sw thread
*/
void observation_sw_thread (cyg_addrword_t data){


  //unsigned int thread_number = (unsigned int) data;
    int from, to;
    int done;
    int i;
    int new_message = FALSE;
    int message = 1;
    int message_to_deliver = FALSE;
    int number_of_measurements_o = 0;
    //int sum_of_measurements_o = 0;
    //int average_of_measurements_o = 0;
    timing_t time_start_o = 0, time_stop_o = 0, time_observation_sw = 0;
    
    while (42) {

      // 1) if there is no message to delivered, check for new message
      while (message_to_deliver == FALSE && new_message == FALSE){

            message = (int) cyg_mbox_get( mb_sampling_done_handle[0] );
            if (message > 0 && message <= (N/block_size)){
                 
	          new_message = TRUE;
                  time_start_o = gettime();      
                  //printf("\n[Observation Thread No. %d] Nachricht %d erhalten", (int) thread_number, message);
                  //diag_printf("\n[Observation] Nachricht %d erhalten", message);
            }
      }


      // 2) if a new message has arrived, sample the particles
      new_message = FALSE;

      from = (message - 1) * block_size;
      to   = from + block_size - 1;
      if ((N - 1) < to)
	       to = N - 1; 

#ifdef USE_CACHE  
       XCache_EnableDCache( 0xF0000000 );
#endif

      //printf("\nOBSERVATION");
      
      // extract observations
      for (i=from; i<=to; i++){
          
            extract_observation(&particles[i], &observations[i]);
      }

      message_to_deliver = TRUE;


#ifdef USE_CACHE  
       XCache_EnableDCache( 0xF0000000 );
#endif
  
      time_stop_o = gettime();

      // 3) if a message should be delivered, deliver it
      while ( message_to_deliver == TRUE){

           done = cyg_mbox_tryput( mb_importance_handle[0], ( void * ) message );
              
           if (done > 0){
  
              message_to_deliver = FALSE;
              time_observation_sw = calc_timediff( time_start_o, time_stop_o );
              number_of_measurements_o++;
              //sum_of_measurements_o += time_observation_sw;
              //average_of_measurements_o = sum_of_measurements_o / number_of_measurements_o;
              //diag_printf("\nObservation SW: %d, \tmessage %d, \ttime: %d", 
              //         number_of_measurements_o, (message-1), time_observation_sw);
              //printf("\n[Observation Thread No. %d] Nachricht %d geschickt", (int) thread_number, message);
           }
      }
      
          
   }
}
Example #4
0
/**
    get new measurement
  !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  !!!!!  U S E R    F U N C T I O N  !!!!!
  !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

*/
void get_new_measurement(void){

		int i, j, k, l;
		int16 re, im;
		
		//unsigned char byte_buffer[1];
		//int counter = 0;
		// fill measurement buffer with next bytes of audio input file

		// (a) shift old values
		//memcpy(&measurement[MEASUREMENT_BUFFER/2], &measurement[0], (MEASUREMENT_BUFFER/2));
		// (b) get new sound data
		//receive_sound_frame(measurement, (MEASUREMENT_BUFFER/2));		
		
		#ifndef STORE_AUDIO
			receive_sound_frame(measurement, MEASUREMENT_BUFFER);
			//printf("\nload next frame");
		#else
			memcpy(measurement, &sound_frames[current_audio_frame*MEASUREMENT_BUFFER], MEASUREMENT_BUFFER);
			current_audio_frame++;
			if (MAX_FRAMES <= current_audio_frame)
			{
				//printf("\nload %d frames", MAX_FRAMES);
				current_audio_frame = 0;
				// load first frames
				for(i=0; i<MAX_FRAMES-1; i++)
				{
					receive_sound_frame(&sound_frames[i*MEASUREMENT_BUFFER],
						MEASUREMENT_BUFFER);		
 				}
			}
		#endif
		memcpy(output, measurement, MEASUREMENT_BUFFER);

		event_found = FALSE;
		// spectral center (sc)
		//complex_number sc, sc_old;
		//sc_old.re = 0; sc_old.im = 0; sc.re = 0; sc.im = 0;

		// find first two beats
		//printf("\ninterval min: %ld ", interval_min);
		//for(i=0;i<NUM_INITIAL_BEATS;i++) printf("\n%d. initial beat: %ld", i, initial_beats[i]);
		if (initial_phase == TRUE )
		{
			//printf("\ninitial phase");
			int16 samples[OBSERVATION_LENGTH];
			//observation obs;
			complex_number obs[OBSERVATION_LENGTH];

			int max_amplitude = 0, max_frequency = 0, current_amplitude;
			int max_amplitude_total = 0, max_frequency_total = 0;
			int16 max_sample_value = 0, max_sample_value_total = 0;
			long int position = 0;

			event_found = FALSE;

			// check current measurement frame
			for (i=0; i<MEASUREMENT_BUFFER/(OBSERVATION_LENGTH); i++)
			{

				memcpy(samples, &measurement[i*OBSERVATION_LENGTH], (OBSERVATION_LENGTH*sizeof(int16)));

				//change Little Endian <-> Big Endian
				max_sample_value = 0;
				for (j=0; j<OBSERVATION_LENGTH; j++)
				{
					samples[j] = ntohl(samples[j]);
					if (ABS(samples[j]) > max_sample_value)
					{
						max_sample_value = ABS(samples[j]);
					}
				}

				for (j=0; j<OBSERVATION_LENGTH; j++)
				{
					obs[j].re = 111;
					obs[j].im = 222;				
				}

				#ifdef USE_CACHE
					XCache_EnableDCache( 0xF0000000 );
				#endif 

				// fft
				//fft_analysis_try (samples, OBSERVATION_LENGTH, obs, sample_rate);
				// -a: send message: sample address (input)
				while (cyg_mbox_tryput( *mb_fft_start_handle, (void *) samples ) == 0)
				{
				}

				// -b: send message: observations address (output)
				while (cyg_mbox_tryput( *mb_fft_start_handle, (void *) obs ) == 0)
				{
				}

				// -c: receive message (fft done)
				while (cyg_mbox_get( *mb_fft_done_handle ) == 0)
				{
				}

				#ifdef USE_CACHE
					XCache_EnableDCache( 0xF0000000 );
				#endif

				
				// find spectral center (sc)
				/*sc.re = 32000; sc.im = 32000; 
				for (j=1;j<((OBSERVATION_LENGTH/2)-1);j++)
				{
				}*/

 

				// max amplitude, frequency
				//for (j=0; j<OBSERVATION_LENGTH; j++)
				/*printf("\n\nSAMPLES\n");
				for (j=0; j<OBSERVATION_LENGTH; j++)
				{
					printf("\n%d", samples[j]);
				}

				printf("\n\nFFT RESULTS\n");*/
				for (j=0; j<OBSERVATION_LENGTH; j++)
				{

					
					// i. calculate current amplitude
					re = (int16) obs[j].re;
					im = (int16) obs[j].im;
					current_amplitude = (re*re) + (im*im);
					current_amplitude = sqrt(current_amplitude);

					// ii. max amplitude
					if (current_amplitude > max_amplitude)
					{

						max_amplitude = current_amplitude;
						// calculate max frequency
						max_frequency = j*(sample_rate/2);
						max_frequency /= (OBSERVATION_LENGTH);
					}
					//printf("\n%d", current_amplitude);
				}

				//printf("\nmax frequency %d, \tmax amplitude: %d", max_frequency, max_amplitude);

				// likelihood for 'beat' (frequency > 100 => amplitude)
				if (max_frequency>100 && max_frequency<5000 && max_amplitude_total<max_amplitude)//<5000
				{
					max_amplitude_total = max_amplitude;
					max_frequency_total = max_frequency;
					max_sample_value_total = max_sample_value;
					position = interval_min + i*OBSERVATION_LENGTH - (OBSERVATION_LENGTH/2);
				}
			}

			//printf("\n!!!!!!!max frequency %d, \tmax amplitude: %d", max_frequency_total, max_amplitude_total);

			// analyse if event was found
			if (max_frequency_total>100 && max_amplitude_total>50 && 
				max_frequency_total<5000 && max_sample_value_total>5000){

				//printf("\nEVENT FOUND at position %ld", position);
				event_found = TRUE;
				event_position = position;
				event_salience = max_amplitude_total;
			}

			// init particle filter if needed;
			
			if (event_found == TRUE) // new beat
			{

				int beat_ind = 0;
				while (initial_beats[beat_ind]>0 && beat_ind<(NUM_INITIAL_BEATS-1))
				{
					beat_ind++;
				}	
				
				// 'beat_ind' is the current initial beat
				initial_beats[beat_ind] = event_position;
				if ((beat_ind>0 && initial_beats[beat_ind] - initial_beats[beat_ind-1] < bytespersecond/5))
				{
					event_found = FALSE;
					initial_beats[beat_ind] = 0;
					return;
				}
				//printf("\n%d. beat at position: %ld", beat_ind, event_position);

				// if last initial beat found: extract hypothesises
				if (beat_ind == (NUM_INITIAL_BEATS-1))
				{					

					// if last initial beat => initialize particles with extracted hypothesis
					// number of possibilities to create hypothesis for beats 
					// mathematical reasoning to calcualate the number of possibilities
					int num_hypothesis = (NUM_INITIAL_BEATS*NUM_INITIAL_BEATS)
						- (((NUM_INITIAL_BEATS+1)*NUM_INITIAL_BEATS)/2);

					// generic algorithm to calcualte all possibilities for tempo hypothesises
					// i: current initial beat
					// j: other initial beats before current initial beat
					// k: current hypothesis [0,...,num_hypothesis-1]
					// l: current particle position: (N/num_hypothesis) particles per hypothesis
					k = 0;
					for (i=NUM_INITIAL_BEATS-1; i>=0;i--)
					{
						
						for (j=i-1; j>=0;j--)
						{

							for(l=(k*N)/num_hypothesis; l<MIN((((k+1)*N)/num_hypothesis),N);l++)
							{
								// init particle according to hypothesis
								particles[l].tempo = (int)initial_beats[i] 
									- initial_beats[j];
								if((5*particles[l].tempo)<bytespersecond)
								{
									//printf("\ndifference short, set to default value");
									particles[l].tempo = bytespersecond/5;
								}
								particles[l].last_beat = initial_beats[i];
								particles[l].next_beat = initial_beats[i] 
									+ particles[l].tempo;
								particles[l].w		= 100;
								particles[l].likelihood	= 100;
							}
							//printf("\n%d. hypothesis: tempo = %d,\tlast beat: %ld", 
							//	(k+1),(int)(initial_beats[i]-initial_beats[j]),
							//	initial_beats[i]);
							k++;
						}
					}		
				}

				/*if (first_beat_pos <= 0)
				{
				
					first_beat_pos = event_position;
					printf("\n1st beat at position: %ld", first_beat_pos);

				}
				else
				{
				
					if (second_beat_pos <= 0 && (event_position - first_beat_pos > (bytespersecond/5)))
					{
	
						second_beat_pos = event_position;
						printf("\n2nd beat at position: %ld (init particles, tempo: %ld)", 
							second_beat_pos, (second_beat_pos -
							first_beat_pos));
						
						// init particles
						for (i=0; i<N; i++)
						{

							particles[i].tempo = second_beat_pos - first_beat_pos;	
							particles[i].last_beat = second_beat_pos;
							particles[i].next_beat = second_beat_pos 
									+ particles[i].tempo;
							particles[i].last_event_time	= second_beat_pos;
							particles[i].w			= PF_GRANULARITY/N;
							particles[i].likelihood		= 100;
						}
					}
				}*/
				//last_event_found = TRUE;
			}
			/*else
			{
				last_event_found = FALSE;
			}*/

		}

		//int16 sample_value = 0;
	
		// make short-time Fourier transformation for the incoming sound data
		/*fft_analysis (measurement, (MEASUREMENT_BUFFER/2), fft_window, sample_rate);
		// real, and imaginary component

		// debug: find max frequency
		double amplitude_max = 0; int max_freq = 0;
		for(i = 0; i < (sample_rate/(2*FREQUENCY_HOPPING)); i++){

			if (amplitude_max < fft_window[i]){

				max_freq  = i*FREQUENCY_HOPPING;
				amplitude_max = fft_window[i];
			}
		}

		event_found = FALSE;
		// extract events
		if (max_freq > 100 && amplitude_max > 60){
			//if (last_event_found == FALSE){

				printf("\nevent found!!!!!!!!!!!");
				// event found
				event_found = TRUE;
				event_position = interval_min + (MEASUREMENT_BUFFER/4);
				event_salience = amplitude_max;
			//}
		} 
		else
		{
			
			last_event_found = FALSE;
		}


		// init particle filter if needed;
		if (first_beat_pos <= 0 || second_beat_pos <= 0 ){ // init still needed

			
			if (event_found == TRUE && last_event_found == FALSE){ // new beat

				if (first_beat_pos <= 0){
				
					first_beat_pos = event_position;
					printf("\n1st beat at position: %d", (int)(first_beat_pos/10000));

				} else {
				
					if (second_beat_pos <= 0){
	
						second_beat_pos = event_position;
						printf("\n2nd beat at position: %d (init particles, tempo: %d)", 
							(int)(second_beat_pos/10000), (int)((second_beat_pos -
							first_beat_pos)/10000));
						// init particles
						for (i=0; i<N; i++){

							particles[i].tempo		= second_beat_pos - first_beat_pos;
							particles[i].last_beat 		= second_beat_pos;
							particles[i].next_beat 		= second_beat_pos 
									+ particles[i].tempo;
							particles[i].last_event_time	= second_beat_pos;
							particles[i].w			= PF_GRANULARITY/N;
							particles[i].likelihood		= 100;
						}
					}
				}
			}
		}

		if (event_found == TRUE) {last_event_found = TRUE; }
		*/

 		// calculate 'energy' in buffer
		//int16 output_value = max_ind;
		//for(i = 0; i < MEASUREMENT_BUFFER/2; i++) memcpy(&output[2*i], &output_value, 2);

		/*
		// debug: print sample values to screen
		for(i = 0; i < MEASUREMENT_BUFFER/2; i++){
			
			double result = fft_window[i];
			memcpy(&sample_value, &measurement[2*i], 2);
			if (interval_min > bytespersecond && interval_min < bytespersecond+1000)
				printf("\n%f", 1.0*sample_value);
			//if (i>0) result *= 8;
			if (result > 32767){printf("\nFFT value to high ( < 32768), but it is %f", result); result = 32767;}
			if (result<-32768){printf("\nFFT value to high ( >= -32768), but it is %f", result); result=-32768;}
			sample_value = (signed short int)result;
			//printf("\n sample value: %d", sample_value);
			//memcpy(&measurement[2*i], &sample_value, 2);			
			//printf("\nA[%d] = %d", i, sample_value]);
		}*/


		// TRY START: CHANGE CHANGE CHANGE
		/*event_found = FALSE;
		long int energy = 0;
		char current_sample[2];

		// calculate 'energy' in buffer
		int16 max_value = 0;

		for (i=0; i<MEASUREMENT_BUFFER/2; i++){
	
			current_sample[1] = measurement[(2*i) + 1]; 
			current_sample[0] = measurement[(i*2)];
			memcpy(&sample_value, current_sample, 2);

			if (ABS(sample_value) > max_value) max_value = ABS(sample_value);

			energy += (sample_value * sample_value);			
		}

		max_amplitude = max_value;

		// adjust energy change
		long int value = sqrt(sqrt(energy-last_energy));// / 2;
                //long int value = (energy-last_energy)/80000;
		sample_value = value;

		if (value > 32767){

			sample_value = 32768;
			printf("\nenergy change too high (%d > 32767)", value);
		} else if (value < -32768) {

			sample_value = -32768;
			printf("\nenergy change too high (%d < -32768)", value);
		}

		if (max_value < 15000 || sample_value == 0) {

			sample_value = 0;
			last_event_found = FALSE;
			//energy = 0;
		} else {

			if (last_event_found == FALSE){

				event_found = TRUE;
				last_event_found = TRUE;
				event_position = interval_min + (MEASUREMENT_BUFFER/2);
				event_salience = ABS(sample_value);
			
				//printf("\nEvent found: position = %d, salience = %d", event_position, event_salience);
                         }
			
		}

		last_energy = energy;*/

		// debug: write energy into file
		/*for (i=0; i<MEASUREMENT_BUFFER/2; i++){
		
			memcpy(current_sample, &sample_value, 2);
			measurement[(2*i) + 1] = current_sample[0]; 
			measurement[(i*2)] = current_sample[1];
		}*/

		// TRY TRY TRY
		//fft_calc(measurement, MEASUREMENT_BUFFER/2);

		// TRY END: CHANGE CHANGE CHANGE

		/*
		char current_sample[2];
		int16 sample_value;
		long int left_max = 0, right_max=0; int s;
		event_found = FALSE;

		// calcualte left sum
		for (s=0; s<MEASUREMENT_BUFFER/4; s++){
		
			current_sample[0] = measurement[(2*s) + 1]; 
			current_sample[1] = measurement[(2*s)];
			memcpy(&sample_value, current_sample, 2);
			
			if (ABS(sample_value) > left_max)
				
				left_max = ABS(sample_value);
		}

		// calculate right sum
		for (s=MEASUREMENT_BUFFER/4; s<MEASUREMENT_BUFFER/2; s++){
		
			current_sample[0] = measurement[(2*s) + 1]; 
			current_sample[1] = measurement[(2*s)];
			memcpy(&sample_value, current_sample, 2);
			
			if (ABS(sample_value) > right_max)
				
				right_max = ABS(sample_value);
		}
		
		if ((left_max > 0) && (((4.0 * right_max) / (1.0 * left_max)) > 4.5) && ((right_max + left_max) > 40000)){
			event_found = TRUE;
			event_position = interval_min + (MEASUREMENT_BUFFER/2);
			if (left_max > 0)
				event_salience = (4*right_max) / left_max;
			else
				event_salience = 2;
			
			printf("\nEvent found: position = %d, salience = %d", event_position, event_salience);
		}
		

	}*/

	//for (i=0; i<MEASUREMENT_BUFFER; i++) fwrite(&measurement[i],1,(BUFFSIZE-1),outputstream);

}
void threadCommunicationTX_func(cyg_addrword_t data) {

	unsigned char *msg_rec;
	char msgToSend3[3] = {0};
	char msgToSend4[4] = {0};
	char msgToSend5[5] = {0};
	char msgToSend6[6] = {0};
	int erro = 0;

	for (;;) {
		erro = 0;
		msg_rec = cyg_mbox_get(mbComTX); // verificar qual a mensagem que a thread de interface enviou

		cyg_mutex_lock(&escritaScreen_mutex); //mutex para bloquear o recurso de escrita no ecra
		printf("recebi msg da thread interface!\n");
		cyg_mutex_unlock(&escritaScreen_mutex); //desbloquear a escrita no ecra

		switch(msg_rec[0]){
			case CRLG:
				printf("recebi CRLG da thread interface!\n");
				msgToSend3[0] = SOM;
				msgToSend3[1] = CRLG;
				msgToSend3[2] = EOM;
				if(send_buffer(msgToSend3, 3) != 0) {
					erro = 1;
					printf("erro a enviar mensagem\n");
				}		
				break;
			case ARLG:
				printf("recebi ARLG da thread interface!\n");
				msgToSend6[0] = SOM;
				msgToSend6[1] = ARLG;
				msgToSend6[2] = msg_rec[1];
				msgToSend6[3] = msg_rec[2];
				msgToSend6[4] = msg_rec[3];
				msgToSend6[5] = EOM;
				printf("novo relogio: %d %d %d\n", (int)msg_rec[1], msg_rec[2], msg_rec[3]);
				if(send_buffer(msgToSend6, 6) != 0) {
					erro = 1;
					printf("erro a enviar mensagem\n");
				}
				break;
			case CTEL:
				printf("recebi CTEL da thread interface!\n");
				msgToSend3[0] = SOM;
				msgToSend3[1] = CTEL;
				msgToSend3[2] = EOM;
				if(send_buffer(msgToSend3, 3) != 0) {
					erro = 1;
					printf("erro a enviar mensagem\n");
				}
				break;
			case CPAR:
				printf("recebi CPAR da thread interface!\n");
				msgToSend3[0] = SOM;
				msgToSend3[1] = CPAR;
				msgToSend3[2] = EOM;
				if(send_buffer(msgToSend3, 3) != 0) {
					erro = 1;
					printf("erro a enviar mensagem\n");
				}
				break;
			case MPMN:
				printf("recebi MPMN da thread interface!\n");
				msgToSend4[0] = SOM;
				msgToSend4[1] = MPMN;
				msgToSend4[2] = msg_rec[1];
				msgToSend4[3] = EOM;
				printf("novo pm: %d\n", msgToSend4[2]);
				if(send_buffer(msgToSend4, 4) != 0) {
					erro = 1;
					printf("erro a enviar mensagem\n");
				}
				break;
			case CALA:
				printf("recebi CALA da thread interface!\n");
				msgToSend3[0] = SOM;
				msgToSend3[1] = CALA;
				msgToSend3[2] = EOM;
				if(send_buffer(msgToSend3, 3) != 0) {
					erro = 1;
					printf("erro a enviar mensagem\n");
				}				 
				break;
			case DALR:
				printf("recebi DALR da thread interface!\n");
				msgToSend6[0] = SOM;
				msgToSend6[1] = DALR;
				msgToSend6[2] = msg_rec[1];
				msgToSend6[3] = msg_rec[2];
				msgToSend6[4] = msg_rec[3];
				msgToSend6[5] = EOM;
				printf("novo alarme relogio: %d %d %d\n", (int)msg_rec[1], msg_rec[2], msg_rec[3]);
				if(send_buffer(msgToSend6, 6) != 0) {
					erro = 1;
					printf("erro a enviar mensagem\n");
				}
				break;
			case DALT:
				printf("recebi DALT da thread interface!\n");
				msgToSend4[0] = SOM;
				msgToSend4[1] = DALT;
				msgToSend4[2] = msg_rec[1];
				msgToSend4[3] = EOM;
				printf("novo alarme temperatura: %d", (int)msg_rec[1]);
				if(send_buffer(msgToSend4, 4) != 0) {
					erro = 1;
					printf("erro a enviar mensagem\n");
				}
				break;
			case DALL:
				printf("recebi DALL da thread interface!\n");
				msgToSend4[0] = SOM;
				msgToSend4[1] = DALL;
				msgToSend4[2] = msg_rec[1];
				msgToSend4[3] = EOM;
				if(send_buffer(msgToSend4, 4) != 0) {
					erro = 1;
					printf("erro a enviar mensagem\n");
				}
				break;
			case AALA:
				printf("recebi AALA da thread interface!\n");
				msgToSend3[0] = SOM;
				msgToSend3[1] = AALA;
				msgToSend3[2] = EOM;
				if(send_buffer(msgToSend3, 3) != 0) {
					erro = 1;
					printf("erro a enviar mensagem\n");
				}
				break;
			case IREG:
				printf("recebi IREG da thread interface!\n");
				msgToSend3[0] = SOM;
				msgToSend3[1] = IREG;
				msgToSend3[2] = EOM;
				if(send_buffer(msgToSend3, 3) != 0) {
					erro = 1;
					printf("erro a enviar mensagem\n");
				}				 
				break;
			case TRGC:
				printf("recebi TRGC da thread interface!\n");
				msgToSend4[0] = SOM;
				msgToSend4[1] = TRGC;
				msgToSend4[2] = msg_rec[1];
				msgToSend4[3] = EOM;
				if(send_buffer(msgToSend4, 4) != 0) {
					erro = 1;
					printf("erro a enviar mensagem\n");
				}				 
				break;
			case TRGI:
				printf("recebi TRGI da thread interface!\n");
				msgToSend5[0] = SOM;
				msgToSend5[1] = TRGI;
				msgToSend5[2] = msg_rec[1];
				msgToSend5[3] = msg_rec[2];
				msgToSend5[4] = EOM;
				if(send_buffer(msgToSend5, 5) != 0) {
					erro = 1;
					printf("erro a enviar mensagem\n");
				}				 
				break;
			default:
				break;
		}
	}
}
Example #6
0
int main( int argc, char *argv[] )
{

    unsigned int i, start_count = 0, done_count = 0, j;
    timing_t t_start = 0, t_stop = 0, t_gen = 0, t_sort = 0, t_merge =
                                       0, t_check = 0, t_tmp;

    printf( "-------------------------------------------------------\n"
            "ReconOS hardware multithreading case study (sort)\n"
            "(c) Computer Engineering Group, University of Paderborn\n\n"
            "eCos, single-threaded hardware version (" __FILE__ ")\n"
            "Compiled on " __DATE__ ", " __TIME__ ".\n"
            "-------------------------------------------------------\n\n" );

#ifdef USE_CACHE
    printf( "enabling data cache for external ram\n" );
    XCache_EnableDCache( 0x80000000 );
#else
    printf( "data cache disabled\n" );
    XCache_DisableDCache(  );
#endif

    data = buf_a;

    //----------------------------------
    //-- GENERATE DATA
    //----------------------------------
    printf( "Generating data..." );
    t_start = gettime(  );
    generate_data( data, SIZE );
    t_stop = gettime(  );
    t_gen = calc_timediff_ms( t_start, t_stop );
    printf( "done\n" );

#ifdef USE_CACHE
    // flush cache contents - the hardware can only read from main memory
    // TODO: storing could be more efficient
    printf( "Flushing cache..." );
    XCache_EnableDCache( 0x80000000 );
    printf( "done\n" );
#endif

    //----------------------------------
    //-- SORT DATA
    //----------------------------------
    // create mail boxes for 'start' and 'complete' messages
    cyg_mbox_create( &mb_start_handle, &mb_start );
    cyg_mbox_create( &mb_done_handle, &mb_done );
    // create sorting thread
    reconos_hwthread_create( 16,                                               // priority
                             0,                                                // entry data (not needed)
                             "MT_HW_SORT",                                     // thread name
                             hwthread_sorter_stack,                            // stack
                             STACK_SIZE,                                       // stack size
                             &hwthread_sorter_handle,                          // thread handle
                             &hwthread_sorter,                                 // thread object
                             (void*)UPBHWR_OSIF_0_BASEADDR,
                             XPAR_OPB_INTC_0_OSIF_0_INTERRUPT_INTR+1,
                             //                         ( void * ) XPAR_PLB_RECONOS_SLOT_0_BASEADDR,      // base address
                             //                         XPAR_OPB_INTC_0_PLB_RECONOS_SLOT_0_INTERRUPT_INTR + 1,     // interrupt
                             hwthread_sorter_resources,                        // resource array
                             2,                                                 // number of resources
                             0xFFFFFFFF, 0xFFFFFFFF
                           );
    cyg_thread_resume( hwthread_sorter_handle );

    printf( "Sorting data..." );
    i = 0;
    while ( done_count < SIZE / N ) {
        t_start = gettime(  );
        // if we have something to distribute,
        // put as many as possile into the start mailbox
        while ( start_count < SIZE / N ) {
            if ( cyg_mbox_tryput( mb_start_handle, ( void * ) &data[i] ) ==
                    true ) {
                start_count++;
                i += N;
            } else {                                                           // mailbox full
                break;
            }
        }
        t_stop = gettime(  );
        t_sort += calc_timediff_ms( t_start, t_stop );
        // see whether anybody's done
        t_start = gettime(  );
        if ( ( t_tmp = ( timing_t ) cyg_mbox_get( mb_done_handle ) ) != 0 ) {
            done_count++;
        } else {
            printf( "cyg_mbox_get returned NULL!\n" );
        }
        t_stop = gettime(  );
        t_sort += calc_timediff_ms( t_start, t_stop );
    }
    printf( "done\n" );


#ifdef USE_CACHE
    // flush cache contents
    // TODO: invalidating would suffice
    printf( "Flushing cache..." );
    XCache_EnableDCache( 0x80000000 );
    printf( "done\n" );
#endif


    //----------------------------------
    //-- MERGE DATA
    //----------------------------------
    printf( "Merging data..." );
    t_start = gettime(  );
    data = recursive_merge( data, buf_b, SIZE, N, simple_merge );
    t_stop = gettime(  );
    t_merge = calc_timediff_ms( t_start, t_stop );
    printf( "done\n" );

    //----------------------------------
    //-- CHECK DATA
    //----------------------------------
    printf( "Checking sorted data..." );
    t_start = gettime(  );
    if ( check_data( data, SIZE ) != 0 )
        printf( "CHECK FAILED!\n" );
    else
        printf( "check successful.\n" );
    t_stop = gettime(  );
    t_check = calc_timediff_ms( t_start, t_stop );

    printf( "\nRunning times (size: %d words):\n"
            "\tGenerate data: %d ms\n"
            "\tSort data    : %d ms\n"
            "\tMerge data   : %d ms\n"
            "\tCheck data   : %d ms\n"
            "\nTotal computation time (sort & merge): %d ms\n",
            SIZE, t_gen, t_sort, t_merge, t_check, t_sort + t_merge );


    return 0;

}
Example #7
0
/**
   preResampling sw thread. Waits for all importance_done messages, normalizes the particle weights,
   calls iteration_done function and finally sends messages to the resampling message box.
*/
void preResampling_thread (cyg_addrword_t data){

  int message = 1;
  int i, done;
  int message_delivered = FALSE;
  int * messages = (int *) malloc(sizeof(int)*(number_of_blocks));
  //int * messages = (int *) malloc(sizeof(int)*N);
  timing_t time_start = 0, time_stop = 0, time_particle_filter = 0;
  int number_of_measurements = 0;
  timing_t t_start = 0, t_stop = 0, t_result_1 = 0, t_result;

  for (i=0; i<number_of_blocks; i++){
     
       messages[i] = FALSE;
  }


  while (42){

      // 1) check, if all messages are received to message box
      //    If this is not true, get the next message
      while (!all_messages_received(messages, number_of_blocks) ){

          message = (int) cyg_mbox_get( mb_importance_done_handle[0] );

          if (message > 0){
  
              messages[message-1] = TRUE;
	  }
      }
      //printf("\n[Resampling Switch] alle Nachrichten erhalten");

      t_start = gettime();

      // set messages back to 'not received'
      for (i=0; i<number_of_blocks; i++){
     
           messages[i] = FALSE;
      }

#ifdef USE_CACHE
      XCache_EnableDCache( 0xF0000000 );
#endif


#ifdef OBSERVATION_DEBUG             
            // debug: check, if observation is correct
            i = 0;     
            observation * obs1 = &observations[i];
            observation obs2;
            extract_observation(&particles[i], &obs2);            

            if (obs1->no_tracking_needed != obs2.no_tracking_needed)
            {
                  diag_printf("\nparticle[%d] \tno_tracking_needed - hw=%d sw=%d", 
                          i, obs1->no_tracking_needed, obs2.no_tracking_needed);
                  diag_printf("\nparticle[%d] \told_likelihood - hw=%d sw=%d", 
                          i, obs1->old_likelihood, obs2.old_likelihood);
            } 
            else if (obs1->no_tracking_needed == FALSE)
            {
                  int j;
                  for(j=0;j<OBSERVATION_LENGTH;j++)
                  {
                       if ((ABS(obs2.fft[j].re-obs1->fft[j].re)>1)||(ABS(obs2.fft[j].im-obs1->fft[j].im)>1))
                       {
                             diag_printf("\nobservation[%d].fft[%d].re - hw=%d sw=%d",
                                i,j,(int)obs1->fft[j].re,(int)obs2.fft[j].re);
                             diag_printf("\nobservation[%d].fft[%d].im - hw=%d sw=%d",
                                i,j,(int)obs1->fft[j].im,(int)obs2.fft[j].im);
                       }                  
                  }
            }
            // debug end
#endif


#ifdef IMPORTANCE_DEBUG2
      // TODO: remove debug
      // debug: check if likelihood is calculated correctly
      int sw_likelihood, difference;
      for (i=0; i<N; i++){
          
          if (observations[i].no_tracking_needed == FALSE) {
		//printf("\nreceived hw results. get sw results");
                sw_likelihood = likelihood(&particles[i], &observations[i], NULL);
                // difference between likelihood calculated in sw and likelihood calculated in hw
                difference = particles[i].w - sw_likelihood;
                //if (difference > 1 || difference < -1) 
                diag_printf("\nlikelihood[%d]: sw = %d; hw = %d", i, sw_likelihood, particles[i].w);
         }
      }  
      // debug end
      if (particles[i].w <= 0) particles[i].w = 1;
#endif

      // 2) calls iteration_done user function
      iteration_done(particles, observations, ref_data, N);

      // 3) normalize particle weights 
      normalize_particle_weights();

      t_stop = gettime();
      t_result_1 = calc_timediff(t_start, t_stop);
      //printf("\nNormalize weights + iteration done: %d", t_result_1);;

      // calculate time for one particle filter loop
      time_stop = gettime();
      time_particle_filter = calc_timediff( time_start, time_stop );
      if (number_of_measurements > 0)
	 //printf("\n%d \t%d", number_of_measurements, time_particle_filter);
         printf("\n%d", time_particle_filter);
	 //diag_printf("\n%d \t%d", number_of_measurements, time_particle_filter);
      time_start = gettime();
      number_of_measurements++;

      t_start = gettime();
      

      // 4) calculate Resampling Function U
      calculate_resampling_function();

      t_stop = gettime();
      t_result = calc_timediff(t_start, t_stop);
      t_result += t_result_1;
      //printf("\nPreresampling: %d", t_result);


#ifdef USE_CACHE 
       XCache_EnableDCache( 0xF0000000 );
#endif
   
      

      // 5) send all messages to sw/hw message box
      for (message=1; message<=number_of_blocks; message++){

           
	   message_delivered = FALSE;
	   while (message_delivered == FALSE){

		done = cyg_mbox_tryput( mb_resampling_handle[0], ( void * ) message );

	     if (done > 0){
	         //diag_printf("\n[Resampling Switch] Nachricht %d an Reampling weitergeleitet", message);
                  message_delivered = TRUE;   
             }
	      
	  }
      } 
          
      //printf("\n[Sampling Switch] alle Nachrichten geschickt");   
  }
}