/*
 * pScope.c
 *
 *  Created on: Jun 8, 2024
 *      Author: Fausto Stella
 */


#include "pScope.h"
#include "trace.h"
#include "main.h"

pScope_handler_typedef pS;
void pScope_var_collector(void);

//uint32_t tmp;

int downsampling_counter;


void pScope_task(void){

	if(DMA_RX->CNDTR==0){

		DMA1->IFCR=(3<< ((DMA_RX_STREAM_N-1)<<1));
		DMA_RX->CCR&=~1;
		DMA_RX->CNDTR=4;
		DMA_RX->CCR|=1;
		pS.State_in=(unsigned char)*((unsigned char*) &pS.data_in_vector[0]);


		switch(pS.State_in){


		case 0x1:


			pS.out_variables_address[pS.N_out_variables]= pS.all_variables_address[ (pS.data_in_vector[0])>>8 ];
			pS.N_out_variables++;

			*((uint8_t*)&pS.data_out_vector[pS.N_out_variables])=0x55;
			pS.DMA_NDTR_out=pS.N_out_variables*4+1;

			break;
		case 0x2:

			pS.downsampling= pS.data_in_vector[0]>>8;

			break;


		case 0xA:
			pS.flag_out_streaming_eable=1;
			break;

		case 0xFE:
			pS.N_out_variables=0;
			pS.flag_out_streaming_eable=0;
			break;


		default:

			break;

		}
	}


	if(pS.flag_out_streaming_eable){

		downsampling_counter--;
		if(downsampling_counter<=0){
		for (unsigned int kk=0;kk<pS.N_out_variables;kk++){
			pS.data_out_vector[kk] = *pS.out_variables_address[kk];
		}
		DMA1->IFCR=((DMA_TX_STREAM_N-1)<<1);
		DMA_TX->CCR&=~1;
		DMA_TX->CNDTR=pS.DMA_NDTR_out;
		DMA_TX->CCR|=1;
		downsampling_counter=pS.downsampling;
		}
	}
}

void pScope_init(void)
{


	pS.downsampling=1;

	DMA_TX->CPAR= ( (uint32_t) (&(USART_PS1->TDR)));
	DMA_TX->CMAR= (uint32_t)(&pS.data_out_vector[0]);
	DMA_TX->CCR|=(1<<7);
	USART_PS1->CR3|=(1<<7);

	DMA_RX->CPAR= ( (uint32_t) (&(USART_PS1->RDR)));
	DMA_RX->CMAR=(uint32_t)(&pS.data_in_vector[0]);
	USART_PS1->CR3|=(1<<6);


	pScope_var_collector();


}




