#include "my_includes.h"
#include <stdio.h>
#include <stdlib.h>
#include "LCD.h"
#include "LED.h"
#include "FatFileSystem.h"
#include "SDCardDriver.h"



void welcome_led(void){
    int i;
    for(i=0;i<5;i++){
        LED_AllOn();
        usleep(100*1000);
        LED_AllOff();
        usleep(100*1000);
    }
    LED_AllOn();
}

bool test_lcd(void){
    bool bSuccess = FALSE;
    
    if (LCD_Open()){
        LCD_TextOut("DE2-70\nTest\n");
        LCD_Close();
        bSuccess = TRUE;
    }else{
        printf("[LCD] test fail\r\n");
    }
    return bSuccess;

}

bool test_sdcard(void){
    bool bSuccess = FALSE;
    if (Fat_Mount(FAT_SD_CARD)){
        FAT_FILE_HANDLE hFile;
        bSuccess = Fat_FileOpen(&hFile, "test.txt");
        if (bSuccess){
            Fat_FileClose(&hFile);
            printf("[SD]find file test.txt\r\n");
        }else{    
            printf("[SD]cannot file test.txt\r\n");
        }   
        Fat_Unmount();
    }else{
        printf("[SD]sdcard test fail\r\n");
    }
    return bSuccess;
}
/*
bool test_ssram(void){
    bool bSuccess = TRUE;
    alt_u8 *ssram = (alt_u8 *)SSRAM_BASE;
    int i;
    for(i=0;i<1024*2;i++)
        *(ssram + i) = (alt_u8)i;
         
    for(i=0;i<1024*2 && bSuccess;i++){
        if (*(ssram + i) != (alt_u8)i)
            bSuccess = FALSE;
    }        
    return bSuccess;
}*/

bool test_sdram(void){  // OK
    bool bSuccess = TRUE;
    alt_u8 *ssram = (alt_u8 *)SDRAM_BASE;
    alt_u32 start, elapsed;
    start = alt_nticks();
    int i;
    for(i=0;i<1024*1024*2;i++)
        *(ssram + i) = (alt_u8)i;
         
    for(i=0;i<1024*1024*2 && bSuccess;i++){
        if (*(ssram + i) != (alt_u8)i)
            bSuccess = FALSE;
    }        
    elapsed = alt_nticks() - start;
    printf("sdram test, elapsed %d nticks\r\n", elapsed);
    return bSuccess;
}



int main()
{
    DEBUG_Enable();
    printf("\r\n===== DE2-70 production test [3] =====\r\n");
    welcome_led();
    test_lcd();
    test_sdcard();

    if (test_sdram())
        printf("sdram test success\r\n");
    else    
        printf("sdram test fail\r\n");
/*        
    if (test_ssram())
        printf("ssram test success\r\n");
    else    
        printf("ssram test fail\r\n");        
      */  
    while(1){
        welcome_led();
    }        
    return 0;
}
