#include <atmel_start.h>
#include <hal_gpio.h>
#include <hal_delay.h>
#include <arm_math.h>

// ----------------------------------------------------------------------
// Header Files
// ----------------------------------------------------------------------
#include "interrupt_handlers.h"
#include "ethercat/ethercat_e54.h"
#include "ethercat/ethercat_slave_def.h"
#include "utilities.h"
#include "spi_slave_dma_config.h"

volatile uint8_t spi_master_tx_complete = 0;
volatile uint8_t spi_master_rx_complete = 0;
/* IO descriptor for SPI master */
struct io_descriptor *io_spi_master;

#define SLAVE_BUFFER_SIZE	32

#define CONF_SERCOM_4_TRANSMIT_DMA_CHANNEL 2
#define CONF_SERCOM_4_RECEIVE_DMA_CHANNEL 3

static uint8_t rx_buffer[SLAVE_BUFFER_SIZE] = {0};
static uint8_t tx_buffer[SLAVE_BUFFER_SIZE] =  {31,30,29,28,27,26,25,24,23,22,21,20,19,18,
												17,16,15,14,13,12,11,10,9,8,7,6,5,4,3,2,1,0};

/* DMA Transfer complete callback for SPI master TX */
static void spi_master_tx_complete_cb(struct _dma_resource *resource)
{
	/* Transfer completed */
	delay_us(CONF_DELAY_US);
	gpio_set_pin_level(SPI_CS, true);
	spi_master_tx_complete = true;
}

/* DMA Transfer complete callback for SPI master RX */
static void spi_master_rx_complete_cb(struct _dma_resource *resource)
{
	/* Transfer completed */
	gpio_set_pin_level(SPI_CS, true);
	spi_master_rx_complete = true;
}

/* SPI master IO and Callback Initialization  */
void spi_master_slave_IF_init(void)
{
	spi_m_dma_get_io_descriptor(&SPI_MS_IF, &io_spi_master);
	spi_m_dma_register_callback(&SPI_MS_IF, SPI_M_DMA_CB_TX_DONE, spi_master_tx_complete_cb);
	//spi_m_dma_register_callback(&SPI_MS_IF, SPI_M_DMA_CB_RX_DONE, spi_master_rx_complete_cb);
}

/* Start SPI master data transfer */
void spi_master_tx(uint8_t *buffer, uint8_t length)
{
	spi_m_dma_enable(&SPI_MS_IF);
	gpio_set_pin_level(SPI_CS, false);
	//io_write(io_spi_master, buffer, length);
	spi_m_dma_transfer(&SPI_MS_IF,tx_buffer,rx_buffer,SLAVE_BUFFER_SIZE);
	
}


void enable_NVIC_IRQ(void)
{
	NVIC_EnableIRQ(TC7_IRQn);	 // TC7: TC_ECAT

}

void dummy_transfer(void)
{
	
	ram_buffer[ram_wr_start] =		((uint16_t)tx_buffer[1]<<8) | (tx_buffer[0]);
	ram_buffer[ram_wr_start+1] =	((uint16_t)tx_buffer[2]<<8) | (tx_buffer[1]);
	ram_buffer[ram_wr_start+2] =	((uint16_t)tx_buffer[4]<<8) | (tx_buffer[3]);

}

int main(void)
{
	/* Initializes MCU, drivers and middleware */
	//__disable_irq();
	atmel_start_init();
	spi_master_slave_IF_init();
	configure_ethercat_dma_descriptors();	
	ethercat_update();
	
	//ext_irq_register(nDRV_RESET, HW_current_limit_detect_callback);
	enable_NVIC_IRQ();
	dummy_transfer();
		
	/* Replace with your application code */
	while (1) {
		delay_ms(1000);
		tx_buffer[0] += 1;
		tx_buffer[SLAVE_BUFFER_SIZE-1] += 1;
		spi_master_tx(tx_buffer, SLAVE_BUFFER_SIZE);
		dummy_transfer();
	
	}
}




