/*!
 * @file        main.c
 *
 * @brief       Main program body
 *
 * @version     V1.0.2
 *
 * @date        2025-05-15
 *
 * @attention
 *
 *  Copyright (C) 2024-2025 Geehy Semiconductor
 *
 *  You may not use this file except in compliance with the
 *  GEEHY COPYRIGHT NOTICE (GEEHY SOFTWARE PACKAGE LICENSE).
 *
 *  The program is only for reference, which is distributed in the hope
 *  that it will be useful and instructional for customers to develop
 *  their software. Unless required by applicable law or agreed to in
 *  writing, the program is distributed on an "AS IS" BASIS, WITHOUT
 *  ANY WARRANTY OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the GEEHY SOFTWARE PACKAGE LICENSE for the governing permissions
 *  and limitations under the License.
 */

/* Includes */
#include "Board.h"
#include "stdio.h"
#include "apm32e030_gpio.h"
#include "apm32e030_misc.h"
#include "apm32e030_eint.h"
#include "apm32e030_spi.h"
#include "apm32e030_dma.h"

/** @addtogroup Examples
  @{
*/

/** @addtogroup SPI_TwoBoards_Slave
  @{
*/

/** @defgroup SPI_TwoBoards_Slave_Macros Macros
  @{
*/

/* printf function configs to USART1 */
#define DEBUG_USART  USART1

/* Buffer Size */
#define BuffSize 56

/**@} end of group SPI_TwoBoards_Slave_Macros */

/** @defgroup SPI_TwoBoards_Slave_Enumerations Enumerations
  @{
*/

/**@} end of group SPI_TwoBoards_Slave_Enumerations */

/** @defgroup SPI_TwoBoards_Slave_Structures Structures
  @{
*/

/**@} end of group SPI_TwoBoards_Slave_Structures */

/** @defgroup SPI_TwoBoards_Slave_Variables Variables
  @{
*/

/* TX buffer */
uint16_t SPI_Buffer_TX[BuffSize] =
{
    0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0X07,
    0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0X07,
    0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0X07,
    0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0X07,
    0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0X07,
    0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0X07,
    0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0X07,
    0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0X07,
};
/* SPI Receive Buffer */
uint16_t SPI_Buffer_RX[BuffSize] = {0x00};
/**@} end of group SPI_TwoBoards_Slave_Variables */

/** @defgroup SPI_TwoBoards_Slave_Functions Functions
  @{
  */

/* Delay */
void Delay(uint16_t count);
/* SPI Init */
void APM_TINY_SPIInit(void);
/* DMA Init */
void APM_TINY_DMAInit(void);
/* Buffer Compare*/
BOOL BufferCompare(uint16_t* buf1, uint16_t* buf2, uint8_t size);

/*!
 * @brief       Main program
 *
 * @param       None
 *
 * @retval      None
 *
 * @note
 */
int main(void)
{
    uint32_t timeout = 0;

    APM_TINY_LEDInit(LED3);
    APM_TINY_LEDInit(LED2);
    APM_TINY_COMInit(COM1);
    APM_TINY_SPIInit();

    printf("I am Slave\r\n");

    APM_TINY_DMAInit();

    while(DMA_ReadDataNumber(DMA1_CHANNEL_2) > 0)
    {
        timeout++;
        if(timeout > 0xFFFFFF)
        {
            break;
        }
    }

    printf("\r\n");
    for (int i = 0; i < BuffSize; i++)
    {
        if (i % 7 == 0)
        {
            printf("\r\n");
        }
        printf(" %02x ,", SPI_Buffer_RX[i]);
    }
    printf("\r\n");

    /* Compare Buffer */
    if (BufferCompare(SPI_Buffer_TX, SPI_Buffer_RX, BuffSize) == TRUE)
    {
        APM_TINY_LEDOn(LED2);
    }

    for (;;)
    {
        Delay(0xFFFF);
        APM_TINY_LEDToggle(LED3);
    }
}


/*!
 * @brief       SPI Init
 *
 * @param       None
 *
 * @retval      None
 *
 * @note
 */
void APM_TINY_SPIInit(void)
{
    GPIO_Config_T gpioConfig;
    SPI_Config_T spiConfig;
    /* Enable related Clock */
    RCM_EnableAPB2PeriphClock(RCM_APB2_PERIPH_SPI1);
    RCM_EnableAHBPeriphClock(RCM_AHB_PERIPH_GPIOA);
    RCM_EnableAPB2PeriphClock(RCM_APB2_PERIPH_SYSCFG);


    /* config PIN_6  MISO */
    gpioConfig.pin =  GPIO_PIN_6 ;
    gpioConfig.mode = GPIO_MODE_AF;
    gpioConfig.outtype = GPIO_OUT_TYPE_PP;
    gpioConfig.speed = GPIO_SPEED_50MHz;
    GPIO_Config(GPIOA, &gpioConfig);

    /* config PIN_5->SCK , PIN_7->MOSI */
    gpioConfig.pin = GPIO_PIN_5 | GPIO_PIN_7;
    gpioConfig.mode = GPIO_MODE_AF;
    gpioConfig.pupd = GPIO_PUPD_PU;
    gpioConfig.speed = GPIO_SPEED_50MHz;
    GPIO_Config(GPIOA, &gpioConfig);

    /* config PIN_4->NSS */
    gpioConfig.pin = GPIO_PIN_4;
    gpioConfig.mode = GPIO_MODE_IN;
    gpioConfig.pupd = GPIO_PUPD_PU;
    gpioConfig.speed = GPIO_SPEED_50MHz;
    GPIO_Config(GPIOA, &gpioConfig);

    GPIO_ConfigPinAF(GPIOA, GPIO_PIN_SOURCE_5, GPIO_AF_PIN0);
    GPIO_ConfigPinAF(GPIOA, GPIO_PIN_SOURCE_6, GPIO_AF_PIN0);
    GPIO_ConfigPinAF(GPIOA, GPIO_PIN_SOURCE_7, GPIO_AF_PIN0);

    /* SPI RESET */
    SPI_Reset(SPI1);
    SPI_ConfigStructInit(&spiConfig);

    /* SPI configuration */
    /* select slave mode */
    spiConfig.mode = SPI_MODE_SLAVE;
    /* Set Clock polarity is High, but Master is Low */
    spiConfig.polarity  = SPI_CLKPOL_HIGH;
    /* Set First bit */
    spiConfig.firstBit = SPI_FIRST_BIT_MSB;
    /* Enable Software slave control */
    spiConfig.slaveSelect = SPI_SSC_ENABLE;
    /* SPI Clock Phase is 2EDGE, but Master is 1EDGE */
    spiConfig.phase = SPI_CLKPHA_2EDGE;
    /* Set SPI BaudRate divider */
    spiConfig.baudrateDiv = SPI_BAUDRATE_DIV_256;
    /* SPI data length */
    spiConfig.length = SPI_DATA_LENGTH_16B;

    SPI_Config(SPI1, &spiConfig);

    SPI_ConfigFIFOThreshold(SPI1, SPI_RXFIFO_QUARTER);

    SPI_Enable(SPI1);
}

/*!
 * @brief       DMA Init
 *
 * @param       None
 *
 * @retval      None
 *
 * @note
 */
void APM_TINY_DMAInit(void)
{
    /* Enable DMA clock */
    RCM_EnableAHBPeriphClock(RCM_AHB_PERIPH_DMA1);
    /* DMA Configure */
    DMA_Config_T dmaConfig;
    /* size of buffer*/
    dmaConfig.bufferSize = BuffSize;
    /* set memory Data Size*/
    dmaConfig.memoryDataSize = DMA_MEMORY_DATASIZE_HALFWORD;
    /* Set peripheral Data Size*/
    dmaConfig.peripheralDataSize = DMA_PERIPHERAL_DATASIZE_HALFWORD;
    /* Enable Memory Address increase*/
    dmaConfig.memoryInc = DMA_MEMORY_INC_ENABLE;
    /* Disable Peripheral Address increase*/
    dmaConfig.peripheralInc = DMA_PERIPHERAL_INC_DISABLE;
    /* Reset Circular Mode*/
    dmaConfig.circular = DMA_CIRCULAR_DISABLE;
    /* Disable M2M*/
    dmaConfig.memoryTomemory = DMA_M2M_DISABLE;
    /* set priority*/
    dmaConfig.priority = DMA_PRIORITY_LEVEL_HIGHT;
    /* read from memory*/
    dmaConfig.direction = DMA_DIR_MEMORY;
    /* Set memory Address*/
    dmaConfig.memoryAddress = (uint32_t)SPI_Buffer_TX;
    /* Set Peripheral Address*/
    dmaConfig.peripheralAddress = (uint32_t)&SPI1->DATA;

    DMA_Config(DMA1_CHANNEL_3, &dmaConfig);
    /* Clear DMA TF flag*/
    DMA_ClearIntFlag(DMA1_INT_FLAG_TF3);

    /* size of buffer*/
    dmaConfig.bufferSize = BuffSize;
    /* set memory Data Size*/
    dmaConfig.memoryDataSize = DMA_MEMORY_DATASIZE_HALFWORD;
    /* Set peripheral Data Size*/
    dmaConfig.peripheralDataSize = DMA_PERIPHERAL_DATASIZE_HALFWORD;
    /* Enable Memory Address increase*/
    dmaConfig.memoryInc = DMA_MEMORY_INC_ENABLE;
    /* Disable Peripheral Address increase*/
    dmaConfig.peripheralInc = DMA_PERIPHERAL_INC_DISABLE;
    /* Reset Circular Mode*/
    dmaConfig.circular = DMA_CIRCULAR_DISABLE;
    /* Disable M2M*/
    dmaConfig.memoryTomemory = DMA_M2M_DISABLE;
    /* set priority*/
    dmaConfig.priority = DMA_PRIORITY_LEVEL_HIGHT;
    /* read from memory*/
    dmaConfig.direction = DMA_DIR_PERIPHERAL;
    /* Set memory Address*/
    dmaConfig.memoryAddress = (uint32_t)SPI_Buffer_RX;
    /* Set Peripheral Address*/
    dmaConfig.peripheralAddress = (uint32_t)&SPI1->DATA;

    DMA_Config(DMA1_CHANNEL_2, &dmaConfig);
    /* Clear DMA TF flag*/
    DMA_ClearIntFlag(DMA1_INT_FLAG_TF2);

    SPI_EnableDMARxBuffer(SPI1);
    SPI_EnableDMATxBuffer(SPI1);

    DMA_Enable(DMA1_CHANNEL_2);
    DMA_Enable(DMA1_CHANNEL_3);
}

/*!
 * @brief       Delay
 *
 * @param       None
 *
 * @retval      None
 *
 * @note
 */
void Delay(uint16_t count)
{
    volatile uint32_t delay = count;

    while (delay--);
}

/*!
 * @brief       Compares two buffers
 *
 * @param       buf1:    First buffer to be compared
 *
 * @param       buf1:    Second buffer to be compared
 *
 * @param       size:    Buffer size
 *
 * @retval      Return TRUE if buf1 = buf2. If not then return FALSE
 *
 * @note
 */
BOOL BufferCompare(uint16_t* buf1, uint16_t* buf2, uint8_t size)
{
    uint8_t i;

    for (i = 0; i < size; i++)
    {
        if (buf1[i] != buf2[i])
        {
            return FALSE;
        }
    }

    return TRUE;
}

#if defined (__CC_ARM) || defined (__ICCARM__) || (defined(__ARMCC_VERSION) && (__ARMCC_VERSION >= 6010050))

/*!
* @brief       Redirect C Library function printf to serial port.
*              After Redirection, you can use printf function.
*
* @param       ch:  The characters that need to be send.
*
* @param       *f:  pointer to a FILE that can recording all information
*              needed to control a stream
*
* @retval      The characters that need to be send.
*
* @note
*/
int fputc(int ch, FILE* f)
{
    /* send a byte of data to the serial port */
    USART_TxData(DEBUG_USART, (uint8_t)ch);

    /* wait for the data to be send  */
    while (USART_ReadStatusFlag(DEBUG_USART, USART_FLAG_TXBE) == RESET);

    return (ch);
}

#elif defined (__GNUC__)

/*!
* @brief       Redirect C Library function printf to serial port.
*              After Redirection, you can use printf function.
*
* @param       ch:  The characters that need to be send.
*
* @retval      The characters that need to be send.
*
* @note
*/
int __io_putchar(int ch)
{
    /* send a byte of data to the serial port */
    USART_TxData(DEBUG_USART, ch);

    /* wait for the data to be send  */
    while (USART_ReadStatusFlag(DEBUG_USART, USART_FLAG_TXBE) == RESET);

    return ch;
}

/*!
* @brief       Redirect C Library function printf to serial port.
*              After Redirection, you can use printf function.
*
* @param       file:  Meaningless in this function.
*
* @param       *ptr:  Buffer pointer for data to be sent.
*
* @param       len:  Length of data to be sent.
*
* @retval      The characters that need to be send.
*
* @note
*/
int _write(int file, char* ptr, int len)
{
    int i;
    for (i = 0; i < len; i++)
    {
        __io_putchar(*ptr++);
    }

    return len;
}

#else
#warning Not supported compiler type
#endif

/**@} end of group SPI_TwoBoards_Slave_Functions */
/**@} end of group SPI_TwoBoards_Slave */
/**@} end of group Examples */
