/*******************************************************************************
 TEST medi50  Dec 23
 ******************************************************************************/
#include "sdk_common.h"
			
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include "nrf.h"
#include "boards.h"
#include "app_error.h"
#include "nrf_drv_saadc.h"
#include "nrfx_gpiote.h"
#include "app_timer.h"
#include "nrf_drv_timer.h"
#include "nrf_delay.h"
#include "nrf_drv_ppi.h"
#include "ada2200_spi.h"
#include "ble_nus.h"
//#include "fstorage.h"
#include "measurements.h"
#include "meas_pd_imm.h"
#include "mcp4725_i2c.h"
//#include "ad5272_i2c.h"
#include "main_timer.h"
#include "battery_saadc.h"
#include "main.h"
#include "app_raw_main.h"
#include "debug_print.h"
//#define CUSTOM_REF_VOLTAGE_IN_MILLIVOLTS   	600.0f                                     /**< Reference voltage (in milli volts) used by ADC while doing conversion. */
//#define CUSTOM_PRE_SCALING_COMPENSATION    	6.0f                                       /**< The ADC is configured to use VDD with 1/3 prescaling as input. And hence the result of conversion is to be multiplied by 3 to get the actual value of the battery voltage.*/
//#define CUSTOM_ADC_RES_10BITS             	1024.0f                                    /**< Maximum digital value for 10-bit ADC conversion. */
//#define st_c_max																20
///**@brief Macro to convert the result of ADC conversion in millivolts.
// *
// * @param[in]  ADC_VALUE   ADC result.
// *
// * @retval     Result converted to millivolts.
// */
//#define CUSTOM_VOUT_IN_MILLI_VOLTS(ADC_VALUE)\
//				(((((ADC_VALUE) * CUSTOM_REF_VOLTAGE_IN_MILLIVOLTS) / CUSTOM_ADC_RES_10BITS) * CUSTOM_PRE_SCALING_COMPENSATION)*2)


static const uint8_t imm_samples_in_buffer = 8;

//uint32_t	s_cnt;
uint8_t LED_list_imm[4];
//uint8_t PD_list_custom[4];

//uint8_t led_custom_list_a[5]	= {2,3,4,5,6};
//uint8_t pd_custom_list_a[4]	= {5,7,8,10};

//uint8_t led_custom_list_b[5]	= {20,21,22,23,24};
//uint8_t pd_custom_list_b[4]	= {16,14,13,11};

int32_t c_max;
extern volatile bool processing;
extern volatile bool data_tx_in_progress;
extern volatile bool ble_connection_st;

extern uint16_t m_pd_delay_us;
uint32_t c_cnt;
static int8_t 	pd_no 		= -1;
static int8_t 	led_no 		= -1;
static int8_t	buf_no		= 0;

uint16_t sel_led_index0 =0;
uint16_t sel_led_index1 =1;
uint16_t sel_led_index2 =2;
uint16_t sel_led_index3 =3;

//static int8_t	c_max		= 5;
static int32_t	t_ms		= 0;
int16_t	imm_cycle_buff[4][imm_CYCLE_CNT] = 
				{
					{0, 0, 0, 0, 0, 0, 0, 0}, //0
					{0, 0, 0, 0, 0, 0, 0, 0}, //1
					{0, 0, 0, 0, 0, 0, 0, 0}, //2
					{0, 0, 0, 0, 0, 0, 0, 0}  //3
				};	
int16_t	imm_cycle_send_buff[imm_LED_NO] = {0, 0, 0, 0};
uint16_t	bi_imm_cycle_send_buff[imm_LED_NO] = {0, 0, 0, 0};

#define SAMPLES_IN_BUFFER	4095+32
static nrf_saadc_value_t pd_imm_adc_buf[2][SAMPLES_IN_BUFFER];

bool pd_adc_custom_a_start	= false;
bool pd_adc_custom_b_start	= false;
bool pd_adc_custom_c_start	= false;
bool pd_adc_custom_d_start	= false;
bool pd_adc_custom_end		= false;
bool pd_adc_custom_start = false;
bool pd_adc_imm_start = false;
bool pd_adc_imm_running = false;
bool custom_testing = false;

//
bool custom_add_data;
extern bool ble_got_new_data;
extern bool motion_raw_data_enabled;
extern char	ble_tx_buffer[BLE_NUS_MAX_DATA_LEN];
uint8_t imm_bin_buffer[BLE_NUS_MAX_DATA_LEN];					
//add imu
uint8_t order_imm=0;





extern which_cmd_t cmd_type_t;

APP_TIMER_DEF(m_custom_check_loop_timer_id);
//APP_TIMER_DEF(m_custom_send_loop_timer_id);
#if FEATURE_DELAY
#define CUSTOM_SEND_LOOP_INTERVAL 500
#else
#define CUSTOM_SEND_LOOP_INTERVAL 100
#endif
#define CUSTOM_CHECK_LOOP_INTERVAL 1




static nrf_ppi_channel_t	m_ppi_channel;



#if !FEATURE_PRINTF
void imm_ppi_init(void)
{
    ret_code_t err_code;

    err_code = nrf_drv_ppi_init();
    APP_ERROR_CHECK(err_code);

    uint32_t gpiote_event_addr = nrf_drv_gpiote_in_event_addr_get(ADA2200_SYNCO_PIN);	
    uint32_t saadc_sample_task_addr   = nrf_drv_saadc_sample_task_get();

    /* setup ppi channel so that timer compare event is triggering sample task in SAADC */
    err_code = nrf_drv_ppi_channel_alloc(&m_ppi_channel);
    APP_ERROR_CHECK(err_code);

    err_code = nrf_drv_ppi_channel_assign(m_ppi_channel,
                                          gpiote_event_addr,
                                          saadc_sample_task_addr);
    APP_ERROR_CHECK(err_code);
}


void imm_ppi_uninit(void)
{
    ret_code_t err_code;

	err_code = nrf_drv_ppi_uninit();
    APP_ERROR_CHECK(err_code);
}


void imm_sampling_event_enable(void)
{
    ret_code_t err_code = nrf_drv_ppi_channel_enable(m_ppi_channel);
    APP_ERROR_CHECK(err_code);
}


void imm_sampling_event_disable(void)
{
	ret_code_t err_code = nrf_drv_ppi_channel_disable(m_ppi_channel);
	APP_ERROR_CHECK(err_code);
}
#endif


/**@brief Function for handling the ADC interrupt.
 *
 * @details  This function will fetch the conversion result from the ADC, convert the value into
 *           percentage and send it to peer.
 */
static void imm_voltage_handler(nrf_drv_saadc_evt_t const * p_event)	/* PD Voltage reading */
{
	ret_code_t err_code;
	int16_t sum = 0;

	uint32_t custom_clk_delay = m_pd_delay_us/16;
		if(ble_connection_st == 0) {
								//imm_adc_end();
								//custom_send_timer_stop();
								DBG_PRINTF("Custom ADC STOP 1\r\n");
						}
		
			else{			
    if (p_event->type == NRF_DRV_SAADC_EVT_DONE)
    {
		err_code = nrf_drv_saadc_buffer_convert(p_event->data.done.p_buffer, imm_samples_in_buffer + custom_clk_delay);
		APP_ERROR_CHECK(err_code);
		
		if(led_no == -1) {
			led_no = 0;
			pd_no = 0;

			led_on(LED_list_imm[led_no]);
			led_pd_matching_value_set(LED_list_imm[led_no]); /* MCP4725 DAC setting and PD on */

		} else {

			for(uint16_t i = custom_clk_delay; i < custom_clk_delay + imm_samples_in_buffer; i++){
				imm_cycle_buff[buf_no][i-custom_clk_delay] = p_event->data.done.p_buffer[i];
			}
#if FEATURE_PRINTF
			DBG_PRINTF("-----------------Read ADC // led_no = %d(%d), pd_no = %d(%d), buf_no = %d\r\n\r\n", led_no, LED_list_custom[led_no], pd_no,  PD_list_custom[pd_no], buf_no);
#endif

			buf_no++;

			 if(pd_no >=  - 1) {
				//pd_no = 0;



				if(led_no < imm_LED_NO - 1) {
					led_no++;
					led_on(LED_list_imm[led_no]);
					led_pd_matching_value_set(LED_list_imm[led_no]); /* MCP4725 DAC setting and PD on */

				} else if(led_no >= imm_LED_NO - 1) {
					pd_no = -1;
					led_no = -1;
#if FEATURE_PRINTF
					DBG_PRINTF("\r\nEnded\r\n");
#endif
					//imm_adc_end();
						//imm_adc_end_final();

					///////////////////////////////////////////////////////////////////////////////////////////
					uint8_t k =0;
					sum = 0;
				for(uint16_t i = 0; i < 4; i++){
						for(uint16_t j = 0; j < imm_samples_in_buffer; j++){
							sum += imm_cycle_buff[i][j];
						}
						
						imm_cycle_send_buff[k++] = sum;
						sum = 0;
					}
						


					buf_no = 0;

					if(ble_connection_st == 0) {
					
					DBG_PRINTF("Custom ADC STOP 1");
					pd_adc_imm_start=false;
					pd_adc_imm_running=false;
					DBG_PRINTF ("FINISH SEND\r\n");
					processing = false;
					custom_testing = false;
					imm_adc_end_final();
						}
					else {
						char resp[4];
						
						if(cmd_type_t == CMD_UART) {
							//custom_send_timer_stop();
							DBG_PRINTF("value 4: %d,%d,%d,%d  \r\n",imm_cycle_send_buff[0] ,imm_cycle_send_buff[1] ,imm_cycle_send_buff[2] ,imm_cycle_send_buff[3] );
						}else if(cmd_type_t == CMD_BLE) {
								DBG_PRINTF("%d ms \r\n",t_ms);
								DBG_PRINTF("value 4: %d,%d,%d,%d  \r\n",imm_cycle_send_buff[0] ,imm_cycle_send_buff[1] ,imm_cycle_send_buff[2] ,imm_cycle_send_buff[3] );
							 for(uint16_t i = 0; i < 4; i++){
								 bi_imm_cycle_send_buff[i]=(uint16_t)(imm_cycle_send_buff[i]);
							 }
							 sprintf(resp,"rF%01X:", order_imm);
							format_data(imm_bin_buffer, resp,  bi_imm_cycle_send_buff, 4);
						
						
						binary_tx_handler(imm_bin_buffer,6);
						}

//						if(ble_connection_st == 1) {
//							battery_timer_start();
//						}

//						led_off(99);
//						pd_off(99);
						imm_adc_start_init();
					}		
				}
			}
		}
   }
  }
}

void imm_check_loop(void * p_context)	
{
	UNUSED_PARAMETER(p_context);
	imm_check_timer_stop();
	if ( custom_testing == false)
	{
		 DBG_PRINTF("%d ms \r\n",t_ms);
		//	sprintf(custom_tx_buffer, "Measure Time :%d ms \r\n",t_ms);
	}
	else
	{
		t_ms++;
		imm_check_timer_start();
	}
}




void imm_adc_start_init(void)
{
	if (ble_got_new_data ==true)
		{
			pd_adc_imm_start=false;
			pd_adc_imm_running=false;
					DBG_PRINTF ("FINISH SEND\r\n");
						led_off(99);
						pd_off(99);
			processing = false;
		  custom_testing = false;
			imm_adc_end_final();
		}
	
	else if (pd_adc_imm_running==true){
			imm_adc_start();
	}
	
	else if (pd_adc_imm_start==true)
	{ 
//	    custom_testing = false;
//			motion_raw_data_enabled = true;
//			custom_add_data = true;
//			icm42670_main();
			//for(uint8_t i =0; i < imm_LED_NO; i++) {
			LED_list_imm[0] = sel_led_index0;
			LED_list_imm[1] = sel_led_index1;
			LED_list_imm[2] = sel_led_index2;
		  LED_list_imm[3] = sel_led_index3;
//			data_tx_handler(ble_tx_buffer);
			
		  t_ms=0; 
			pd_adc_imm_start=false;
			pd_adc_imm_running=true;
		  custom_testing = true;
//			custom_check_timer_start();	
			c_cnt=0;
//			pd_adc_custom_start=false;
//			pd_adc_custom_a_start=true;
		
			imm_adc_start2();
			imm_check_timer_start();
			c_cnt++;
	}
		
	
	
	
	else
		{
		
	}
}



void imm_adc_start(void)
{
	pd_no		= -1;
	led_no		= -1;
	buf_no		= 0;
	 t_ms=0; 


	for(uint16_t i = 0; i < 4; i++) {
		for(uint16_t j = 0; j < imm_CYCLE_CNT; j++) {
			imm_cycle_buff[i][j] = 0;
		}
	}
if(order_imm>=15){
	order_imm=0;
}
else
{ order_imm++;
}
}


void imm_adc_start2(void) 
{
	imm_adc_start();
	imm_adc_init();
	imm_irq_init();
	imm_ppi_init();
	imm_sampling_event_enable();	

}


void imm_adc_end(void) 
{

	DBG_PRINTF("adc_end\r\n");

	imm_sampling_event_disable();

}

void imm_adc_end_final(void) 
{

	DBG_PRINTF("adc_end_for_good\r\n");

	imm_sampling_event_disable();
	imm_irq_uninit();
	imm_ppi_uninit();
	imm_adc_uninit();
	battery_timer_start();

}






void imm_adc_init(void)
{
#if FEATURE_PRINTF
	DBG_PRINTF("custom_adc_init\r\n");
#endif

	static nrfx_saadc_config_t default_config;
	default_config.resolution			= (nrf_saadc_resolution_t)NRFX_SAADC_CONFIG_RESOLUTION; /* Resolution is 10bits */
	default_config.oversample			= (nrf_saadc_oversample_t)NRFX_SAADC_CONFIG_OVERSAMPLE; /* Over Sampling Disabled */
	default_config.interrupt_priority	= NRFX_SAADC_CONFIG_IRQ_PRIORITY;						/* Interrupt Priority is 0(Highest) */
	default_config.low_power_mode		= NRFX_SAADC_CONFIG_LP_MODE;							/* Low Power Mode is Disabled */

	static nrf_saadc_channel_config_t config;
	config.resistor_p	= NRF_SAADC_RESISTOR_DISABLED;
	config.resistor_n	= NRF_SAADC_RESISTOR_DISABLED;
	config.gain 		= NRF_SAADC_GAIN1_6;
	config.reference	= NRF_SAADC_REFERENCE_INTERNAL;
	config.acq_time 	= NRF_SAADC_ACQTIME_3US;
	config.mode 		= NRF_SAADC_MODE_DIFFERENTIAL;
	config.burst		= NRF_SAADC_BURST_DISABLED;
	config.pin_p		= (nrf_saadc_input_t)(NRF_SAADC_INPUT_AIN0);
	config.pin_n		= (nrf_saadc_input_t)(NRF_SAADC_INPUT_AIN1);
	
	ret_code_t err_code = nrf_drv_saadc_init(&default_config, imm_voltage_handler);
	APP_ERROR_CHECK(err_code);

	err_code = nrf_drv_saadc_channel_init(0, &config);
	APP_ERROR_CHECK(err_code);

	err_code = nrf_drv_saadc_buffer_convert(pd_imm_adc_buf[0], imm_samples_in_buffer + m_pd_delay_us/16);
	APP_ERROR_CHECK(err_code);
}



void imm_adc_uninit(void)
{
#if FEATURE_PRINTF
	DBG_PRINTF("pd_custom_adc_uninit\r\n");
#endif

	nrf_drv_saadc_uninit();
	nrf_drv_saadc_channel_uninit(0);
}


#if !FEATURE_PRINTF
void imm_irq_init(void)
{
    ret_code_t err_code;

	/* Initialize int pin */
	if (!nrfx_gpiote_is_init())
	{
	  err_code = nrfx_gpiote_init();
	  APP_ERROR_CHECK(err_code);
	}

    nrfx_gpiote_in_config_t in_config = NRFX_GPIOTE_CONFIG_IN_SENSE_LOTOHI(true);
    in_config.pull = NRF_GPIO_PIN_PULLDOWN;

    err_code = nrfx_gpiote_in_init(ADA2200_SYNCO_PIN, &in_config, NULL);
    APP_ERROR_CHECK(err_code);

    nrfx_gpiote_in_event_enable(ADA2200_SYNCO_PIN, true);
}


void imm_irq_uninit(void)
{
	nrfx_gpiote_in_event_disable(ADA2200_SYNCO_PIN);
	nrfx_gpiote_in_uninit(ADA2200_SYNCO_PIN);
}
#endif





void imm_check_timer_start(void)
{
	APP_ERROR_CHECK(app_timer_start(m_custom_check_loop_timer_id, APP_TIMER_TICKS(CUSTOM_CHECK_LOOP_INTERVAL), NULL));
}

void imm_check_timer_stop(void)
{
	APP_ERROR_CHECK(app_timer_stop(m_custom_check_loop_timer_id));

}
void imm_check_timer_init(void)
{
    APP_ERROR_CHECK(app_timer_create(&m_custom_check_loop_timer_id, APP_TIMER_MODE_SINGLE_SHOT, imm_check_loop));
}
