/*
 * The Clear BSD License
 * Copyright (c) 2013 - 2015, Freescale Semiconductor, Inc.
 * Copyright 2016-2017 NXP
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted (subject to the limitations in the disclaimer below) provided
 *  that the following conditions are met:
 *
 * o Redistributions of source code must retain the above copyright notice, this list
 *   of conditions and the following disclaimer.
 *
 * o Redistributions in binary form must reproduce the above copyright notice, this
 *   list of conditions and the following disclaimer in the documentation and/or
 *   other materials provided with the distribution.
 *
 * o Neither the name of the copyright holder nor the names of its
 *   contributors may be used to endorse or promote products derived from this
 *   software without specific prior written permission.
 *
 * NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY THIS LICENSE.
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
 * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
#include "app.h"

/*******************************************************************************
 * Definitions
 ******************************************************************************/

//volatile HSLSPI_Type *hslspi_base = (HSLSPI_Type *)HSLSPI;


/* 静态分配内存 */
q31_t     gPQFftQ31In[APP_PQ_FFT_SAMPLE_COUNT_MAX*2u];
q31_t     gPQFftQ31Out[APP_PQ_FFT_SAMPLE_COUNT_MAX*2u];
q31_t     gPQFftQ31InOut[APP_PQ_FFT_SAMPLE_COUNT_MAX*2u];
float32_t gPQFftF32In[APP_PQ_FFT_SAMPLE_COUNT_MAX*2u];
float32_t gPQFftF32Out[APP_PQ_FFT_SAMPLE_COUNT_MAX*2u];

float32_t gPQFirF32In[APP_PQ_FIR_SAMPLE_COUNT_240*2u];
float32_t gPQFirF32Out[APP_PQ_FIR_SAMPLE_COUNT_240*2u];

volatile uint32_t  gPQProcCycles[APP_USER_TASK_COUNT];   /* PowerQuad timing cycles. */
volatile uint32_t  gARMProcCycles[APP_USER_TASK_COUNT];  /* ARM CMSIS DSP timing cycles. */



/* for FATFS in SDCard. */
const TCHAR driverNumberBuffer[3] = {SDDISK + '0', ':', '/'};
static const sdmmchost_detect_card_t s_sdCardDetect = /*! @brief SDMMC host detect card configuration */
{
#ifndef BOARD_SD_DETECT_TYPE
    .cdType = kSDMMCHOST_DetectCardByGpioCD,
#else
    .cdType = BOARD_SD_DETECT_TYPE,
#endif
    .cdTimeOut_ms = (~0U),
};

static FATFS g_fileSystem; /* File system object */
//static FIL g_fileObject;   /* File object */
static status_t sdcardWaitCardInsert(void);
FRESULT scan_files(char* path);

char gFatfsPathBuf[256];

/*******************************************************************************
 * Prototypes
 ******************************************************************************/
/* Benchmark Task List. */
void task_pq_fft_128(void);
void task_pq_fft_256(void);
void task_pq_fft_512(void);
void task_pq_mat_add(void);
void task_pq_mat_inv(void);
void task_pq_mat_mul(void);
void task_pq_fir_lowpass(void);
void task_pq_fir_highpass(void);
void task_pq_records(void);

void App_LcdSayHello(void)
{
    //lcd_clear_screen(LCD_COLOR_BLUE);
    uint16_t height;
    uint16_t width;

    BMP_ERR err;

    //err = App_BmpDumpFromFile("MatrixAddition_24b.bmp", &height, &width, NULL);
    //err = App_BmpDumpFromFile("bmp6.bmp", &height, &width, NULL); /* file name error. */
    err = App_BmpDumpFromFile("2:\\Wel24b.bmp", &height, &width, gAppBmpDisplayData);
    lcd_clear_image(gAppBmpDisplayData, height*width*2);
    PRINTF("err: %d\r\n", err);
}

/* LCD显示页面清单 */
void (*cAppLcdDisplayPageFunc[])(void) =
{
    task_pq_fft_128,
    task_pq_fft_256,
    task_pq_fft_512,
    task_pq_mat_add,
    task_pq_mat_inv,
    task_pq_mat_mul,
    task_pq_fir_lowpass,
    task_pq_fir_highpass,
    task_pq_records
};

/*******************************************************************************
 * Code
 ******************************************************************************/
/*!
 * @brief Main function
 */
int main(void)
{

    //char ch;
    //uint32_t i;
    uint32_t keyValuePre, keyValue;

    //FRESULT error;
    //DIR directory; /* Directory object */
    //FILINFO fileInformation;
    //FIL fileObj;
    //char fileLineBuf[100]; /* Line buffer */


    /* Init board hardware. */
    BOARD_InitHardware();
    CLOCK_EnableClock(kCLOCK_InputMux);
    SYSCON_NS->AHBCLKCTRLX[2] |= 1u << 19u; /* enable the AHB clock to access PQ. */

    PRINTF("powerquad lcd demo, %s, %s.\r\n", __DATE__, __TIME__);

    /*
     * For SDCard with SDIO.
     */
    /* attach main clock to SDIF */
    CLOCK_AttachClk(BOARD_SDIF_CLK_ATTACH);
    CLOCK_SetClkDiv(kCLOCK_DivSdioClk, 1U, true);/* need call this function to clear the halt bit in clock divider register */
    CLOCK_SetClkDiv(kCLOCK_DivSdioClk, (uint32_t)(96000000 / FSL_FEATURE_SDIF_MAX_SOURCE_CLOCK + 1U), true);
    if (sdcardWaitCardInsert() != kStatus_Success)
    {
        PRINTF("Please insert the SDCard and reset board.\r\n");
        while (1);
    }
    PRINTF("SDCard is ready.\r\n");

    //if (f_mount(&g_fileSystem, driverNumberBuffer, 0U))
    if (f_mount(&g_fileSystem, driverNumberBuffer, 1u))
    {
        PRINTF("Mount volume failed.\r\n");
        while (1);
    }
    PRINTF("FATFS in SDCard is ready.\r\n");

    /*
     * Prepare the LCD screen.
     */
    lcd_init();
    //lcd_clear_screen(LCD_COLOR_WHITE);
    App_LcdSayHello();
    /*
     * Prepare the user key to switch the lcd page.
     */
    App_InitUserKey();
    keyValue    = APP_USER_TASK_COUNT;
    keyValuePre = APP_USER_TASK_COUNT;


    //PRINTF("func list size: %d.\r\n", sizeof(cAppLcdDisplayPageFunc) / sizeof(cAppLcdDisplayPageFunc[0]) );

    while (1)
    {
        keyValue = App_GetUserKeyValue();
        if (keyValue != keyValuePre)
        {
            App_DeinitUserKey(); /* disable detecting key when changing the lcd display. */
            (*cAppLcdDisplayPageFunc[keyValue])(); /* switch to new page on lcd module. */
            keyValuePre = keyValue;
            App_InitUserKey(); /* enable detecting key for next event. */
        }

        __WFI(); /* sleep when in idle. */
    }

}

static status_t sdcardWaitCardInsert(void)
{
    /* Save host information. */
    g_sd.host.base = SD_HOST_BASEADDR;
    g_sd.host.sourceClock_Hz = 96000000; //SD_HOST_CLK_FREQ;
    /* card detect type */
    g_sd.usrParam.cd = &s_sdCardDetect;
#if defined DEMO_SDCARD_POWER_CTRL_FUNCTION_EXIST
    g_sd.usrParam.pwr = &s_sdCardPwrCtrl;
#endif
    /* SD host init function */
    if (SD_HostInit(&g_sd) != kStatus_Success)
    {
        PRINTF("\r\nSD host init fail\r\n");
        return kStatus_Fail;
    }
    /* power off card */
    SD_PowerOffCard(g_sd.host.base, g_sd.usrParam.pwr);
    /* wait card insert */
    if (SD_WaitCardDetectStatus(SD_HOST_BASEADDR, &s_sdCardDetect, true) == kStatus_Success)
    {
        PRINTF("\r\nCard inserted.\r\n");
        /* power on the card */
        SD_PowerOnCard(g_sd.host.base, g_sd.usrParam.pwr);
    }
    else
    {
        PRINTF("\r\nCard detect fail.\r\n");
        return kStatus_Fail;
    }

    return kStatus_Success;
}

FRESULT scan_files (
    char* path        /* Start node to be scanned (***also used as work area***) */
)
{
    FRESULT res;
    DIR dir;
    UINT i;
    static FILINFO fno;


    res = f_opendir(&dir, path);                       /* Open the directory */
    if (res == FR_OK)
    {
        for (;;)
        {
            res = f_readdir(&dir, &fno);                   /* Read a directory item */
            if (res != FR_OK || fno.fname[0] == 0) break;  /* Break on error or end of dir */
            if (fno.fattrib & AM_DIR) /* It is a directory */
            {
                i = strlen(path);
                sprintf(&path[i], "/%s", fno.fname);
                res = scan_files(path);                    /* Enter the directory */
                if (res != FR_OK) break;
                path[i] = 0;
            } else {                                       /* It is a file. */
                printf("%s/%s\r\n", path, fno.fname);
            }
        }
        f_closedir(&dir);
    }

    return res;
}



/* EOF. */

