#include <stdio.h>
#include <string.h>
#include "main.h"

#include "nrf_gpio.h"
#include "app_util_platform.h"
#include "app_error.h"
//#include "bsp.h"
//#include "app_timer.h"
#include "nrf_drv_clock.h"
#include "nrf_delay.h"
#include "nrf_log.h"
#include "nrf_log_ctrl.h"
#include "app_timer.h"

#include "ble_imp.h"
#include "adc.h"
#include "pwm.h"

bool DIP_state[6] = {false}; 
uint8_t DIP_code = 0;

/* DMX512 Tripple buffering */
volatile struct DMX512 DMX512_buffers = {
	.DMX512_buffer_0 = {0},
	.DMX512_buffer_1 = {0},
	.DMX512_buffer_2 = {0},
	/* DMX512 Buffers pointers */
	.DMX512_read = DMX512_buffers.DMX512_buffer_0,
	.DMX512_read_prev = DMX512_buffers.DMX512_buffer_1,
	.DMX512_write = DMX512_buffers.DMX512_buffer_1,
	.DMX512_write_prev = DMX512_buffers.DMX512_buffer_2,
};

void init_gpio( void )
{
	/* LEDs */
	nrf_gpio_cfg_output(17);	// LED 2 - RED - Advertising
	//nrf_gpio_cfg_output(18);	// LED 1 - GREEN - First channel
	/* Power enable */
	nrf_gpio_cfg_output(26); 

	/* Second PWM connector as time debug port */
	#ifdef DEBUG_TIME
		nrf_gpio_cfg_output(8);
		nrf_gpio_cfg_output(9);
		nrf_gpio_cfg_output(10);
		nrf_gpio_cfg_output(11);
		nrf_gpio_cfg_output(12);
		nrf_gpio_cfg_output(13);
		nrf_gpio_cfg_output(14);
		nrf_gpio_cfg_output(15);
	#endif

	/* DIP pins */
	nrf_gpio_cfg_input(16,NRF_GPIO_PIN_NOPULL);
	nrf_gpio_cfg_input(22,NRF_GPIO_PIN_NOPULL);
	nrf_gpio_cfg_input(23,NRF_GPIO_PIN_NOPULL);
	nrf_gpio_cfg_input(24,NRF_GPIO_PIN_NOPULL);
	nrf_gpio_cfg_input(27,NRF_GPIO_PIN_NOPULL);
	nrf_gpio_cfg_input(28,NRF_GPIO_PIN_NOPULL);

	/* Button */
	nrf_gpio_cfg_input(25,NRF_GPIO_PIN_NOPULL);

	/* Enable power output */
	nrf_gpio_pin_write(26, true);

	/* Sampling DIP */
	DIP_state[0] = !nrf_gpio_pin_read(27);
	DIP_state[1] = !nrf_gpio_pin_read(28);
	DIP_state[2] = !nrf_gpio_pin_read(22);
	DIP_state[3] = !nrf_gpio_pin_read(23);
	DIP_state[4] = !nrf_gpio_pin_read(24);
	DIP_state[5] = !nrf_gpio_pin_read(16);

	DIP_code = DIP_state[0] | (DIP_state[1]<<1) | (DIP_state[2]<<2) | (DIP_state[3]<<3) | (DIP_state[4]<<4) | (DIP_state[5]<<5);
}
int main(void)
{
	ret_code_t err_code;
	err_code = NRF_LOG_INIT(NULL);
	APP_ERROR_CHECK(err_code);

	init_gpio();
	init_PWM();
	init_BLE();

	init_ADC();

	while (true)
	{
//		uint32_t err_code = sd_app_evt_wait();
//		APP_ERROR_CHECK(err_code);
	}
}


/** @} */
