/******************************************************************************
*
* file       IMX290_spi.c
*
* API for SPI access of the Imager data via FPGA
*
* Target Device: MiniRaman
*
*******************************************************************************/
/* Driver Header files */
#include <ti/drivers/GPIO.h>
#include <ti/drivers/SPI.h>
#include <stdlib.h>
#include <stdbool.h>
#include "IMX290_spi.h"
#include "Board.h"
#include "SRI_Global.h"

SPI_Handle      imx290_spi;
SPI_Transaction imx290_spiTransaction;

/**
 * Initialize SPI interface
 *
 * @return none
 */
extern bool IMX290SpiOpen(void)
{
    SPI_Params imx290_spiParams;

    SPI_Params_init(&imx290_spiParams);
    imx290_spiParams.dataSize = 12;
    imx290_spiParams.transferMode= SPI_MODE_BLOCKING;
    imx290_spiParams.mode = SPI_MASTER;
    imx290_spiParams.bitRate = 4000000;  // 4 MHz is max for the CC2640R2 SPI
    imx290_spiParams.frameFormat = SPI_POL1_PHA1;
    imx290_spi = SPI_open(Board_SPI1, &imx290_spiParams);
    if (imx290_spi == NULL)
    {
       return (false);
    }
    return (true);
}

/**
 * Close SPI interface
 *
 * @return True when successful.
 */
extern void IMX290SpiClose(void)
{
    SPI_close(imx290_spi);
}

/**
 * Clear data from SPI interface
 *
 * @return none
 */
extern void IMX290SpiFlush(void)
{
    uint16_t i;

    for (i = 0; i < SPECTRUM_SIZE; i++)
    {
        spectrum[i] = 0;
    }
}

/**
 * Read from an SPI device
 *
 * @return True when successful.
 */
#include <ti/sysbios/family/arm/m3/Hwi.h>
extern bool IMX290SpiRead(uint16_t *buf, size_t length)
{
    bool transferOK;
    unsigned int key;
    uint16_t* pbuf = &buf[length/2];

    GPIO_clearDio(MINIRAMAN_nFPGA_CS);
    // Enter critical section.
    key = Hwi_disable();
    imx290_spiTransaction.count = length/2;
    imx290_spiTransaction.txBuf = NULL;
    imx290_spiTransaction.rxBuf = buf;
    transferOK = SPI_transfer(imx290_spi, &imx290_spiTransaction);
    imx290_spiTransaction.count = length/2;
    imx290_spiTransaction.txBuf = NULL;
    imx290_spiTransaction.rxBuf = pbuf;
    transferOK = SPI_transfer(imx290_spi, &imx290_spiTransaction);
    // Exit critical section.
    Hwi_restore(key);
    GPIO_setDio(MINIRAMAN_nFPGA_CS);
    return (transferOK);
}


/************************************** DONE *********************************************/
