/*
 * np_driver_spi.c
 *
 *  Created on: July 14, 2016
 *      Author: Alan.Lin
 *
 *  Copyright: NexPack Ltd.
 */

#include "np_config.h"
#include "spis.h"
#include "np_driver_spi.h"
#include "np_app_spi.h"

int driver_spi_slave_initial(void){
	uint8_t spis_req_value = 0x10;
	//IO INITIAL
	MXC_IOMAN->spis_req = spis_req_value;
	//IO initial IS OK
	if(spis_req_value != MXC_IOMAN->spis_ack){
		return E_BUSY;
	}
	CLKMAN_SetClkScale((clkman_clk_t)(CLKMAN_CLK_SPIS), CLKMAN_SCALE_DIV_1);

	//spis function intial
	MXC_SPIS->gen_ctrl = 0;
	MXC_SPIS->gen_ctrl = (MXC_F_SPIS_GEN_CTRL_SPI_SLAVE_EN | MXC_F_SPIS_GEN_CTRL_TX_FIFO_EN |
	        				MXC_F_SPIS_GEN_CTRL_RX_FIFO_EN |(0x01 << MXC_F_SPIS_GEN_CTRL_SPI_MODE_POS));

	MXC_SPIS_FIFO->tx_8[0] = '$';	//keep first TX byte of next communication is '$'.Meaningless on here

	MXC_SPIS->fifo_ctrl &= (~MXC_F_SPIS_FIFO_CTRL_RX_FIFO_AF_LVL);
	MXC_SPIS->fifo_ctrl |=  (0x0 << MXC_F_SPIS_FIFO_CTRL_RX_FIFO_AF_LVL_POS);

    MXC_SPIS->inten = MXC_F_SPIS_INTEN_RX_FIFO_AF;// | MXC_F_SPIS_INTEN_TX_FIFO_AE;
	NVIC_EnableIRQ(SPIS_IRQn);

	return E_NO_ERROR;
}

void np_driver_spis_put_byte_to_tx_buff(uint8_t t_tx_byte){
	MXC_SPIS_FIFO->tx_8[0] = t_tx_byte;
}

//------------------------interrupt function---------------------------------
void SPIS_IRQHandler(void){
	uint32_t spis_int_flags = MXC_SPIS->intfl;

	if (spis_int_flags & MXC_F_SPIS_INTFL_RX_FIFO_AF) {
		// Check for data
		while(MXC_SPIS->fifo_stat & MXC_F_SPIS_FIFO_STAT_RX_FIFO_USED) {
			np_app_spis_message(MXC_SPIS_FIFO->rx_8[0]);
		}
		MXC_SPIS->intfl = MXC_F_SPIS_INTFL_RX_FIFO_AF;
	}
}
