#include "minios7.h"
#include <stdlib.h>
#include <stdio.h>
#include "MFS.h"

#define  printf printCom1
#define  Print printCom1


#define _DISK_A     0
#define _DISK_B     1
#define _Test_Length 1024
#define _Test_Loop   1

char far sFileData[5000],sStandardData[5000];

#define BUFSIZE 1024       /* read/write buffer size */
#define SERVICE 10000      /* define the service port for Server */
#define SOCKETS 32         /* define the maximum number of sockets */
#define QLEN    SOCKETS-1  /* maximum connection queue length */

int es;       /* flag to run ES (service loop) */
//fd_set rfds;  /* set of socket file descriptors for reading */
int c3Toc2=1,c2Toc3=0, iLength,er;
unsigned char item2,item3,item4;
int c3Head=0,c4Head=0,c2Head=0;
int RS_232 =0,RS_485=0;
long c3Index=0,c4Index=0,c2Index=0;
uchar Rdata[2048],C2Buf[1024],C3Buf[1024],C4Buf[1024],CBuf[1024];
#define BUFFER_SIZE (500)

char *keyname[]=
{
"UP:","LEFT:","DOWN:","CR:","RIGHT:","BS:","3:","6:","9:","0:","SHIFT:","DOT(.):","1:",
"4:","7:","8:","5:","2:","F1:","F2:","F3:","F6:","F5:","F4:"
};

int inc_flag[]=
{
18,19,20,23,22,21,12,13,14,17,16,15,6,7,8,11,10,9,0,1,2,5,4,3
};




unsigned char cIP_Net[4];     
unsigned char cGateway_Net[4];     
unsigned char cMask_Net[4];     
int needConfigIP=1;



int Test_WritingSpeed(int EnableWriteVerify)
{
    /*
    Test item: Writing speed (calls WriteFile)
    Description:  
        Create a file "Speed.txt". 
    */
    
    int iFileHandle,i;
    int iRet,iFaile=0;
    long lLastTimeTicks,lTimeDiff;
    
    Print (" before  mfs_EnableWriteVerify");

    if(EnableWriteVerify) mfs_EnableWriteVerify();
    else                  mfs_DisableWriteVerify();
    
    Print (" after  mfs_EnableWriteVerify");
    if((iFileHandle=mfs_OpenFile(_DISK_A, "Speed.txt", "w"))>0)
    {
        Print("OpenFile() : A:Speed.txt ok, File handle=%d.....\r\n", iFileHandle);

        //Prepare data: 0,1,2,...,8,9,0,1,....
        for(i=0;i<_Test_Length;i++)
            sFileData[i]='0'+i%10;
        
        lLastTimeTicks=GetTimeTicks();
        for(i=0;i<_Test_Loop;i++)
        {
            iRet=mfs_WriteFile(iFileHandle,sFileData,_Test_Length);
            if(iRet<=0)
            {
                //
                Print("Loop%d Write data failed! Error code=%d\r\n",i, iRet);
                Print(" _Test_Length= %d\r\n",_Test_Length);
                
                 //for(i=0;i<_Test_Length;i++)
            		//Print (" %c" ,sFileData[i]
                
                iFaile=1;
                return  iRet;
                //break;
            }
            Print(".");
        }
        lTimeDiff=GetTimeTicks()-lLastTimeTicks;
        
        iRet=mfs_CloseFile(iFileHandle);
        if(iRet==NoError)
        {
            Print("\n\rCloseFile(): A:Speed.txt ok.\n\r");
            if(iFaile==0)
            {
                Print("\n\rTest result=ok. WriteFile %ld Bytes takes %ldms(%5.1fKB/Sec)\n\r",
                      (long)_Test_Loop*(long)_Test_Length,
                      lTimeDiff,
                      (float)_Test_Loop*(float)_Test_Length/lTimeDiff); 
            }
            else Print("\n\rTest result=failed!\n\r");
        }
        else
        {
            Print("\n\rCloseFile(): A:Speed.txt failed! Error code=%d\r\n", iRet);
            Print("\n\rTest result=failed!\n\r");
            return  iRet;
        } 
    }
    else
    {
        Print("OpenFile(): A:Speed.txt failed! Error:%d\r\n", iFileHandle);
        Print("\n\rTest result=failed!\n\r");
    }
    return  0;
}


int Test_ReadingSpeed(void)
{
    /*
    Test item: Reading speed (calls ReadFile)
    Description:  
        Read data from A:Speed.txt and check its correction.
        "Speed.txt" should be created advanced by TestWritingSpeed().
    */
    int iFileHandle,i,j;
    int iRet,iFaile=0;
    long lLastTimeTicks,lTimeDiff;
    
    //Prepare standard data: 0,1,2,...,8,9,0,1,.... 
    for(i=0;i<_Test_Length;i++)
        sStandardData[i]='0'+i%10;
       
    if((iFileHandle=mfs_OpenFile(_DISK_A, "Speed.txt", "r"))>0)
    {
        Print("OpenFile() : A:Speed.txt ok, File handle=%d.....\r\n", iFileHandle);
        
        lLastTimeTicks=GetTimeTicks();
        for(i=0;i<_Test_Loop;i++)
        {
            memset(sFileData,0,_Test_Length);
            
            iRet=mfs_ReadFile(iFileHandle,sFileData,_Test_Length);
            if(iRet<=0)
            {
                Print("Loop%d Read data failed! Error code=%u\r\n",i, iRet);
                iFaile=1;
                return  iRet;
                //break;
            }
            else if(memcmp(sFileData,sStandardData,_Test_Length)!=NoError)
            {
                Print("Loop%d, Compare data failed! Error code=%u\r\n",i, iRet);
                Print("Standard :File\n\r");                
                for(j=0;j<_Test_Length;j++)
                {
                    if(sStandardData[j]!=sFileData[j])
                    Print("{Data[%d] %c:%c [%02d]:[%02d]} \n\r",j,sStandardData[j],sFileData[j],sStandardData[j],sFileData[j]);
                }
                Print("\n\r");
                iFaile=1;
                return  iRet;
                break;
            }
            else Print(".");
        }
        
        if(i==_Test_Loop)
        {
            lTimeDiff=GetTimeTicks()-lLastTimeTicks;
            iRet=mfs_CloseFile(iFileHandle);
            if(iRet==NoError)
            {
                Print("\n\rCloseFile(): A:Speed.txt ok.\n\r");
                if(iFaile==0)
                {
                    Print("\n\rTest result=ok. ReadFile %ld Bytes takes %ldms(%5.1fKB/Sec)\n\r",
                          (long)_Test_Loop*(long)_Test_Length,
                          lTimeDiff,
                          (float)_Test_Loop*(float)_Test_Length/lTimeDiff); 
                }
                else Print("\n\rTest result=failed!\n\r");
            }
            else
            {
                Print("\n\rCloseFile(): A:Speed.txt failed! Error code=%d\r\n", iRet);
                Print("\n\rTest result=failed!\n\r");
                return  -1;
            }
        }
        else
        {
            Print("\n\rTest result=failed!\n\r");
            return  -2;
        }
    }
    else
    {
        Print("OpenFile(): A:Speed.txt failed! Error:%d\r\n", iFileHandle);
        Print("\n\rTest result=failed!\n\r");
        return  -3;
    }
    return  0;
}

int Test_Dir(void)
{
    int i,iRet,iFileno,iDisk;
    char FileName[20];
    FILE_DATA fdata;
    
    for(iDisk=_DISK_A;iDisk<=_DISK_B;iDisk++)
    {
        if(iDisk==_DISK_A) Print("DiskA file list:\n\r");
        if(iDisk==_DISK_B) Print("DiskB file list:\n\r");
        
        if((iFileno=mfs_GetFileNo(iDisk))>=0)
        {
            for(i=0;i<iFileno;i++)
            {
                iRet=mfs_GetFileInfoByNo(iDisk,i,(FILE_DATA *) &fdata);
                if(iRet==NoError)
                {
                    memset(FileName, 0x0, 14);
                    memcpy(FileName,fdata.fname, 12);
                    
                    Print("%d)%12s    %4ld bytes\r\n",i,FileName, fdata.size);
                }
            }  
            
            Print("\r\nThere are %d File(s)\r\n", iFileno);
            
            Print("%12lu bytes used\r\n", mfs_GetUsedSize(iDisk));
            Print("%12lu bytes free\r\n", mfs_GetFreeSize(iDisk));
            Print("%12lu bytes bad\r\n", mfs_GetBadSzie(iDisk));              
             if (iFileno!=0)
             {
             	return iFileno;
             	Print(" iFileno= %d \r\n",iFileno);
              }
             	
            	
        }
        else 
        {
            Print("GetFileNo() failed! Error code= %d\r\n", iFileno);            
             	
            Print(" iFileno= %d \r\n",iFileno);
            return -5;
        }
        return 0;
    }
}

int test_MFS(void)
{
	int i, iRet;
	
	
            
		        	
	Print (" test 4 ");
	iRet=mfs_Init();		
	if (iRet!=64)
	{
		Print (" test 3 ");
		iRet=mfs_ResetFlash();
		//LCD_PutsAt(0,0,"MFS Init fail",0);
		Print (" test 2 ");
		//Print("MFS Init fail, iRet=%d\r\n", iRet);
		//return iRet;
		
	}
	else
	{
		Print (" test1 ");
		
	}
		iRet=-1;
		iRet=Test_WritingSpeed(0);
		Print (" test ");
		Delay(100);
		if (iRet!=0)
		{
			LCD_PutsAt(0,0,"MFS Write fail",0);		
			Print("MFS write fail, iRet=%d\r\n", iRet);
			return iRet;
		}
		else
		{
			iRet=-1;
			iRet=Test_ReadingSpeed();
			Delay(100);
			if (iRet!=0)
			{
				LCD_PutsAt(0,0,"MFS Read fail",0);		
				Print("MFS read fail, iRet=%d\r\n", iRet);
				return iRet;
			}
			else
			{
				Print("After Test_ReadingSpeed OK, iRet=%d\r\n", iRet);
				mfs_DeleteAllFiles(_DISK_A);
            			mfs_DeleteAllFiles(_DISK_B);
            			Delay(100);
            			iRet=-1;
            			iRet=Test_Dir();
            			if (iRet!=0)
				{
					LCD_PutsAt(0,0,"MFS Del fail",0);		
					Print("MFS clear/Dir fail, iRet=%d\r\n", iRet);
					return iRet;
				}
				else
				{
					return 0;
				}
            			
				
			}
		}
		
	//}
	
}



/*
{
	int status[24]={0},sts;
	while(1)
  	{
  		while(1)
      	{
	  		for(i=0 ;i <24 ;i++)
			{
				if((sts=ReadKeyStatus(idx)) != status[idx])
				
				
				
			}
		}
	}
	
}
*/


void do_KeyPAD(void)
{
  int y=1,i,idx=0,sts;
  int j=0,z=0;
  int status[24]={0},temp;
  
  
  LCD_Clear();
  LCD_PutsAt(0,0,"Press KEY test",0);
	LCD_Hline(0,127,14,1);
	LCD_Hline(0,127,15,1);
	LCD_UpdateGraphic();
  while(1)
  {
    //for(i=0 ;i <24 ;i++)
    for(j=0 ;j <24 ;j++)
    {
      LCD_PutsAt(0,y,"                ",0);
      LCD_Gotoxy(0,y);
      i=inc_flag[j];
      //idx=i;
      LCD_Puts(keyname[i],0);
      //*i=inc_flag[j];
      //LCD_Puts(keyname[i],0);
      while(1)
      {
         z=inc_flag[idx];
        if((sts=ReadKeyStatus(z)) != status[z])
        {
     			status[z]=sts;
    			if(sts)
		    	{
		    	  //if(idx == inc_flag[j]) break;
               if(idx == inc_flag[i]) break;
            }
        }
        idx++;
        if(idx > 23) idx =0;
        temp = ReadKey();
      }
      LCD_Puts(" OK",0);
      y++;
      if(y > 3) y =1;
    }
    LCD_Clear();
    LCD_PutsAt(0,0,"KEY test OK",0);
    break;
    /*
    for(i=0 ;i <26 ;i++)
    {
      LCD_PutsAt(0,y,"                ",0);
      LCD_Gotoxy(0,y);
      LCD_Puts(keyCH[i],0);
      while(1)
      {
        if(IsKey())
        {
          temp = ReadKey();
          if(temp == 65+i)
          {
            LCD_Putch(65+i,0);
            break;
          }
        }
      }
      LCD_Puts(" OK",0);
      y++;
      if(y > 3) y =1;
    }
    break;
    */
  }
}

/*
{
	int status[24]={0},sts;
	while(1)
  	{
  		while(1)
      	{
	  		for(i=0 ;i <24 ;i++)
			{
				if((sts=ReadKeyStatus(idx)) != status[idx])
				
				
				
			}
		}
	}
	
}
*/

void ClearEEP(int block)
{
	int aa,i;
	int err=0;
	unsigned char v0;
	
	unsigned char buf[256],str[256];
	for(i=0;i<256;i++)
		buf[i]=0xff;
	EE_WriteEnable();
	//for(aa=0;aa<256;aa++)
	//{
		EE_MultiWrite_A(block,0,256,buf);
	//}
	EE_WriteProtect();
	for(aa=0;aa<256;aa++)
	{
		EE_MultiRead(block,aa,1,&v0);
		if(v0!=0xff)
			err=1;
		//printf("[%d][%02X][%02X]\n",block,aa,v0);
	}
	if(err==1)
	{
		sprintf(str,"EEPROM Error %d",block);
		LCD_PutsAt(0,3,str,0);
		Delay(100);
		RestoreCom1();
		exit(0);
	}
	else
	{
		sprintf(str,"EEPROM %d/64 OK",block+1);
		LCD_PutsAt(0,3,str,0);		
	}
	
}
