static portBASE_TYPE prvTYPECommand( int8_t *pcWriteBuffer, size_t xWriteBufferLen, const int8_t *pcCommandString )
{
int8_t *pcParameter;
portBASE_TYPE xParameterStringLength, xReturn = pdTRUE;
static F_FILE *pxFile = NULL;
int iChar;
size_t xByte;
size_t xColumns = 50U;

	/* Ensure there is always a null terminator after each character written. */
	memset( pcWriteBuffer, 0x00, xWriteBufferLen );

	/* Ensure the buffer leaves space for the \r\n. */
	configASSERT( xWriteBufferLen > ( strlen( cliNEW_LINE ) * 2 ) );
	xWriteBufferLen -= strlen( cliNEW_LINE );

	if( xWriteBufferLen < xColumns )
	{
		/* Ensure the loop that uses xColumns as an end condition does not
		write off the end of the buffer. */
		xColumns = xWriteBufferLen;
	}

	if( pxFile == NULL )
	{
		/* The file has not been opened yet.  Find the file name. */
		pcParameter = ( int8_t * ) FreeRTOS_CLIGetParameter
									(
										pcCommandString,		/* The command string itself. */
										1,						/* Return the first parameter. */
										&xParameterStringLength	/* Store the parameter string length. */
									);

		/* Sanity check something was returned. */
		configASSERT( pcParameter );

		/* Attempt to open the requested file. */
		pxFile = f_open( ( const char * ) pcParameter, "r" );
	}

	if( pxFile != NULL )
	{
		/* Read the next chunk of data from the file. */
		for( xByte = 0; xByte < xColumns; xByte++ )
		{
			iChar = f_getc( pxFile );

			if( iChar == -1 )
			{
				/* No more characters to return. */
				f_close( pxFile );
				pxFile = NULL;
				break;
			}
			else
			{
				pcWriteBuffer[ xByte ] = ( int8_t ) iChar;
			}
		}
	}

	if( pxFile == NULL )
	{
		/* Either the file was not opened, or all the data from the file has
		been returned and the file is now closed. */
		xReturn = pdFALSE;
	}

	strcat( ( char * ) pcWriteBuffer, cliNEW_LINE );

	return xReturn;
}
static portBASE_TYPE prvPerformCopy( int8_t *pcSourceFile,
							int32_t lSourceFileLength,
							int8_t *pcDestinationFile,
							int8_t *pxWriteBuffer,
							size_t xWriteBufferLen )
{
int32_t lBytesRead = 0, lBytesToRead, lBytesRemaining;
F_FILE *pxFile;
portBASE_TYPE xReturn = pdPASS;

	/* NOTE:  Error handling has been omitted for clarity. */

	while( lBytesRead < lSourceFileLength )
	{
		/* How many bytes are left? */
		lBytesRemaining = lSourceFileLength - lBytesRead;

		/* How many bytes should be read this time around the loop.  Can't
		read more bytes than will fit into the buffer. */
		if( lBytesRemaining > ( long ) xWriteBufferLen )
		{
			lBytesToRead = ( long ) xWriteBufferLen;
		}
		else
		{
			lBytesToRead = lBytesRemaining;
		}

		/* Open the source file, seek past the data that has already been
		read from the file, read the next block of data, then close the
		file again so the destination file can be opened. */
		pxFile = f_open( ( const char * ) pcSourceFile, "r" );
		if( pxFile != NULL )
		{
			f_seek( pxFile, lBytesRead, F_SEEK_SET );
			f_read( pxWriteBuffer, lBytesToRead, 1, pxFile );
			f_close( pxFile );
		}
		else
		{
			xReturn = pdFAIL;
			break;
		}

		/* Open the destination file and write the block of data to the end of
		the file. */
		pxFile = f_open( ( const char * ) pcDestinationFile, "a" );
		if( pxFile != NULL )
		{
			f_write( pxWriteBuffer, lBytesToRead, 1, pxFile );
			f_close( pxFile );
		}
		else
		{
			xReturn = pdFAIL;
			break;
		}

		lBytesRead += lBytesToRead;
	}

	return xReturn;
}
示例#3
0
//---------------------------------------------------------------------------------------
//selects the active sample from the folder
void sd_setActiveSample(uint8_t sampleNr)
{
	FRESULT res;
	uint8_t currentSample=0;
	//goto sample directory
	res = f_opendir(&sd_Directory, "/samples");                       /* Open the directory */
    if (res == FR_OK)
    {
		//count .wav files in sample dir
		FILINFO fno;

		while(1)
		{
			res = f_readdir(&sd_Directory, &fno);
			if (res != FR_OK || fno.fname[0] == 0) break;  /* Break on error or end of dir */
			if (fno.fname[0] == '.') continue;             /* Ignore dot entry */

			char *fn = fno.fname; //8.3 format

			if (fno.fattrib & AM_DIR) {                    /* It is a directory */
				continue;									// skip directories
			}else {                                       /* It is a file. */
              //check if .wav file
				//get ext

				int i;
				for(i=0;i<12-3;i++)
				{
					if(fn[i]=='.')
					{
						if( (fn[i+1]=='W') && (fn[i+2]=='A') && (fn[i+3]=='V') )
						{

							if(sampleNr == currentSample)
							{
								//found sample
								char filename[22] = "/samples/";
								memcpy(&filename[9],fn,13);
								filename[21] = 0;

								FRESULT res = f_open((FIL*)&sd_File,filename,FA_OPEN_EXISTING | FA_READ);

								if(res!=FR_OK)
								{
									//file open error... maybe the file does not exist?
									return;
								}
								//copy name
								memcpy(sd_currentSampleName,fn,11);
								sd_currentSampleName[11] = 0;
								//set read pointer to sample data
								sd_currentSampleLength = findDataChunk();

								return;
							}
							currentSample++;
						}
					}
				}

            }
		}

		sd_initOkFlag = 1;
    }
}
示例#4
0
/**
  * @brief  Main program
  * @param  None
  * @retval None
  */
int main(void)
{
  FRESULT res;                                          /* FatFs function common result code */
  uint32_t byteswritten, bytesread;                     /* File write/read counts */
  uint8_t wtext[] = "This is STM32 working with FatFs"; /* File write buffer */
  uint8_t rtext[100];                                   /* File read buffer */
  
  /* STM32F3xx HAL library initialization:
       - Configure the Flash prefetch
       - Configure the Systick to generate an interrupt each 1 msec
       - Set NVIC Group Priority to 4
       - Low Level Initialization
     */
  HAL_Init();
 
  /* Configure the system clock to 64 MHz */
  SystemClock_Config();
  
  
  /*##-1- Link the micro SD disk I/O driver ##################################*/
  if(FATFS_LinkDriver(&SD_Driver, SDPath) == 0)
  {
    /*##-2- Register the file system object to the FatFs module ##############*/
    if(f_mount(&SDFatFs, (TCHAR const*)SDPath, 0) != FR_OK)
    {
      /* FatFs Initialization Error */
      Error_Handler();
    }
    else
    {
      /*##-3- Create a FAT file system (format) on the logical drive #########*/
      /* WARNING: Formatting the uSD card will delete all content on the device */
      if(f_mkfs((TCHAR const*)SDPath, 0, 0) != FR_OK)
      {
        /* FatFs Format Error */
        Error_Handler();
      }
      else
      {       
        /*##-4- Create and Open a new text file object with write access #####*/
        if(f_open(&MyFile, "STM32.TXT", FA_CREATE_ALWAYS | FA_WRITE) != FR_OK)
        {
          /* 'STM32.TXT' file Open for write Error */
          Error_Handler();
        }
        else
        {
          /*##-5- Write data to the text file ################################*/
          res = f_write(&MyFile, wtext, sizeof(wtext), (void *)&byteswritten);

          /*##-6- Close the open text file #################################*/
          if (f_close(&MyFile) != FR_OK )
          {
            Error_Handler();
          }
          
          if((byteswritten == 0) || (res != FR_OK))
          {
            /* 'STM32.TXT' file Write or EOF Error */
            Error_Handler();
          }
          else
          {      
            /*##-7- Open the text file object with read access ###############*/
            if(f_open(&MyFile, "STM32.TXT", FA_READ) != FR_OK)
            {
              /* 'STM32.TXT' file Open for read Error */
              Error_Handler();
            }
            else
            {
              /*##-8- Read data from the text file ###########################*/
              res = f_read(&MyFile, rtext, sizeof(rtext), (UINT*)&bytesread);
              
              if((bytesread == 0) || (res != FR_OK))
              {
                /* 'STM32.TXT' file Read or EOF Error */
                Error_Handler();
              }
              else
              {
                /*##-9- Close the open text file #############################*/
                f_close(&MyFile);
                
                /*##-10- Compare read data with the expected data ############*/
                if((bytesread != byteswritten))
                {                
                  /* Read data is different from the expected data */
                  Error_Handler();
                }
                else
                {
                  /* Success of the demo: no error occurrence */
                }
              }
            }
          }
        }
      }
    }
  }
  
  /*##-11- Unlink the RAM disk I/O driver ####################################*/
  FATFS_UnLinkDriver(SDPath);

  /* Configure LED2 */
  BSP_LED_Init(LED2);
  
  /* Infinite loop */
  while (1)
  {
    /* Success of the demo: no error occurrence */
    BSP_LED_Toggle(LED2);
    HAL_Delay(200);
  }
}
示例#5
0
/* $Procedure ZZDDHF2H ( Private --- DDH Filename to Handle ) */
/* Subroutine */ int zzddhf2h_(char *fname, integer *ftabs, integer *ftamh, 
	integer *ftarc, integer *ftbff, integer *fthan, char *ftnam, integer *
	ftrtm, doublereal *ftmnm, integer *nft, integer *utcst, integer *
	uthan, logical *utlck, integer *utlun, integer *nut, logical *exists, 
	logical *opened, integer *handle, logical *found, doublereal *mnm, 
	ftnlen fname_len, ftnlen ftnam_len)
{
    /* System generated locals */
    olist o__1;
    cllist cl__1;
    inlist ioin__1;

    /* Builtin functions */
    integer s_cmp(char *, char *, ftnlen, ftnlen), f_inqu(inlist *), f_open(
	    olist *), f_clos(cllist *);

    /* Local variables */
    integer unit;
    extern doublereal zzddhmnm_(integer *);
    extern /* Subroutine */ int zzddhgtu_(integer *, integer *, logical *, 
	    integer *, integer *, integer *), zzddhrmu_(integer *, integer *, 
	    integer *, integer *, logical *, integer *, integer *);
    integer i__;
    extern /* Subroutine */ int chkin_(char *, ftnlen);
    integer rchar;
    extern /* Subroutine */ int errch_(char *, char *, ftnlen, ftnlen);
    extern integer rtrim_(char *, ftnlen);
    extern logical failed_(void);
    extern integer isrchi_(integer *, integer *, integer *);
    logical locopn;
    extern /* Subroutine */ int sigerr_(char *, ftnlen);
    integer uindex;
    logical locexs;
    extern /* Subroutine */ int chkout_(char *, ftnlen), setmsg_(char *, 
	    ftnlen);
    integer iostat;
    extern /* Subroutine */ int errint_(char *, integer *, ftnlen);
    extern logical return_(void);

/* $ Abstract */

/*     SPICE Private routine intended solely for the support of SPICE */
/*     routines.  Users should not call this routine directly due */
/*     to the volatile nature of this routine. */

/*     Convert filename to a handle. */

/* $ Disclaimer */

/*     THIS SOFTWARE AND ANY RELATED MATERIALS WERE CREATED BY THE */
/*     CALIFORNIA INSTITUTE OF TECHNOLOGY (CALTECH) UNDER A U.S. */
/*     GOVERNMENT CONTRACT WITH THE NATIONAL AERONAUTICS AND SPACE */
/*     ADMINISTRATION (NASA). THE SOFTWARE IS TECHNOLOGY AND SOFTWARE */
/*     PUBLICLY AVAILABLE UNDER U.S. EXPORT LAWS AND IS PROVIDED "AS-IS" */
/*     TO THE RECIPIENT WITHOUT WARRANTY OF ANY KIND, INCLUDING ANY */
/*     WARRANTIES OF PERFORMANCE OR MERCHANTABILITY OR FITNESS FOR A */
/*     PARTICULAR USE OR PURPOSE (AS SET FORTH IN UNITED STATES UCC */
/*     SECTIONS 2312-2313) OR FOR ANY PURPOSE WHATSOEVER, FOR THE */
/*     SOFTWARE AND RELATED MATERIALS, HOWEVER USED. */

/*     IN NO EVENT SHALL CALTECH, ITS JET PROPULSION LABORATORY, OR NASA */
/*     BE LIABLE FOR ANY DAMAGES AND/OR COSTS, INCLUDING, BUT NOT */
/*     LIMITED TO, INCIDENTAL OR CONSEQUENTIAL DAMAGES OF ANY KIND, */
/*     INCLUDING ECONOMIC DAMAGE OR INJURY TO PROPERTY AND LOST PROFITS, */
/*     REGARDLESS OF WHETHER CALTECH, JPL, OR NASA BE ADVISED, HAVE */
/*     REASON TO KNOW, OR, IN FACT, SHALL KNOW OF THE POSSIBILITY. */

/*     RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF */
/*     THE SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY */
/*     CALTECH AND NASA FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE */
/*     ACTIONS OF RECIPIENT IN THE USE OF THE SOFTWARE. */

/* $ Required_Reading */

/*     None. */

/* $ Keywords */

/*     PRIVATE */

/* $ Declarations */

/* $ Abstract */

/*     Parameter declarations for the DAF/DAS handle manager. */

/* $ Disclaimer */

/*     THIS SOFTWARE AND ANY RELATED MATERIALS WERE CREATED BY THE */
/*     CALIFORNIA INSTITUTE OF TECHNOLOGY (CALTECH) UNDER A U.S. */
/*     GOVERNMENT CONTRACT WITH THE NATIONAL AERONAUTICS AND SPACE */
/*     ADMINISTRATION (NASA). THE SOFTWARE IS TECHNOLOGY AND SOFTWARE */
/*     PUBLICLY AVAILABLE UNDER U.S. EXPORT LAWS AND IS PROVIDED "AS-IS" */
/*     TO THE RECIPIENT WITHOUT WARRANTY OF ANY KIND, INCLUDING ANY */
/*     WARRANTIES OF PERFORMANCE OR MERCHANTABILITY OR FITNESS FOR A */
/*     PARTICULAR USE OR PURPOSE (AS SET FORTH IN UNITED STATES UCC */
/*     SECTIONS 2312-2313) OR FOR ANY PURPOSE WHATSOEVER, FOR THE */
/*     SOFTWARE AND RELATED MATERIALS, HOWEVER USED. */

/*     IN NO EVENT SHALL CALTECH, ITS JET PROPULSION LABORATORY, OR NASA */
/*     BE LIABLE FOR ANY DAMAGES AND/OR COSTS, INCLUDING, BUT NOT */
/*     LIMITED TO, INCIDENTAL OR CONSEQUENTIAL DAMAGES OF ANY KIND, */
/*     INCLUDING ECONOMIC DAMAGE OR INJURY TO PROPERTY AND LOST PROFITS, */
/*     REGARDLESS OF WHETHER CALTECH, JPL, OR NASA BE ADVISED, HAVE */
/*     REASON TO KNOW, OR, IN FACT, SHALL KNOW OF THE POSSIBILITY. */

/*     RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF */
/*     THE SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY */
/*     CALTECH AND NASA FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE */
/*     ACTIONS OF RECIPIENT IN THE USE OF THE SOFTWARE. */

/* $ Required_Reading */

/*     DAF, DAS */

/* $ Keywords */

/*     PRIVATE */

/* $ Particulars */

/*     This include file contains parameters defining limits and */
/*     integer codes that are utilized in the DAF/DAS handle manager */
/*     routines. */

/* $ Restrictions */

/*     None. */

/* $ Author_and_Institution */

/*     F.S. Turner       (JPL) */

/* $ Literature_References */

/*     None. */

/* $ Version */

/* -    SPICELIB Version 2.5.0, 10-MAR-2014 (BVS) */

/*        Updated for SUN-SOLARIS-64BIT-INTEL. */

/* -    SPICELIB Version 2.4.0, 10-MAR-2014 (BVS) */

/*        Updated for PC-LINUX-64BIT-IFORT. */

/* -    SPICELIB Version 2.3.0, 10-MAR-2014 (BVS) */

/*        Updated for PC-CYGWIN-GFORTRAN. */

/* -    SPICELIB Version 2.2.0, 10-MAR-2014 (BVS) */

/*        Updated for PC-CYGWIN-64BIT-GFORTRAN. */

/* -    SPICELIB Version 2.1.0, 10-MAR-2014 (BVS) */

/*        Updated for PC-CYGWIN-64BIT-GCC_C. */

/* -    SPICELIB Version 2.0.0, 12-APR-2012 (BVS) */

/*        Increased FTSIZE (from 1000 to 5000). */

/* -    SPICELIB Version 1.20.0, 13-MAY-2010 (BVS) */

/*        Updated for SUN-SOLARIS-INTEL. */

/* -    SPICELIB Version 1.19.0, 13-MAY-2010 (BVS) */

/*        Updated for SUN-SOLARIS-INTEL-CC_C. */

/* -    SPICELIB Version 1.18.0, 13-MAY-2010 (BVS) */

/*        Updated for SUN-SOLARIS-INTEL-64BIT-CC_C. */

/* -    SPICELIB Version 1.17.0, 13-MAY-2010 (BVS) */

/*        Updated for SUN-SOLARIS-64BIT-NATIVE_C. */

/* -    SPICELIB Version 1.16.0, 13-MAY-2010 (BVS) */

/*        Updated for PC-WINDOWS-64BIT-IFORT. */

/* -    SPICELIB Version 1.15.0, 13-MAY-2010 (BVS) */

/*        Updated for PC-LINUX-64BIT-GFORTRAN. */

/* -    SPICELIB Version 1.14.0, 13-MAY-2010 (BVS) */

/*        Updated for PC-64BIT-MS_C. */

/* -    SPICELIB Version 1.13.0, 13-MAY-2010 (BVS) */

/*        Updated for MAC-OSX-64BIT-INTEL_C. */

/* -    SPICELIB Version 1.12.0, 13-MAY-2010 (BVS) */

/*        Updated for MAC-OSX-64BIT-IFORT. */

/* -    SPICELIB Version 1.11.0, 13-MAY-2010 (BVS) */

/*        Updated for MAC-OSX-64BIT-GFORTRAN. */

/* -    SPICELIB Version 1.10.0, 18-MAR-2009 (BVS) */

/*        Updated for PC-LINUX-GFORTRAN. */

/* -    SPICELIB Version 1.9.0, 18-MAR-2009 (BVS) */

/*        Updated for MAC-OSX-GFORTRAN. */

/* -    SPICELIB Version 1.8.0, 19-FEB-2008 (BVS) */

/*        Updated for PC-LINUX-IFORT. */

/* -    SPICELIB Version 1.7.0, 14-NOV-2006 (BVS) */

/*        Updated for PC-LINUX-64BIT-GCC_C. */

/* -    SPICELIB Version 1.6.0, 14-NOV-2006 (BVS) */

/*        Updated for MAC-OSX-INTEL_C. */

/* -    SPICELIB Version 1.5.0, 14-NOV-2006 (BVS) */

/*        Updated for MAC-OSX-IFORT. */

/* -    SPICELIB Version 1.4.0, 14-NOV-2006 (BVS) */

/*        Updated for PC-WINDOWS-IFORT. */

/* -    SPICELIB Version 1.3.0, 26-OCT-2005 (BVS) */

/*        Updated for SUN-SOLARIS-64BIT-GCC_C. */

/* -    SPICELIB Version 1.2.0, 03-JAN-2005 (BVS) */

/*        Updated for PC-CYGWIN_C. */

/* -    SPICELIB Version 1.1.0, 03-JAN-2005 (BVS) */

/*        Updated for PC-CYGWIN. */

/* -    SPICELIB Version 1.0.1, 17-JUL-2002 */

/*        Added MAC-OSX environments. */

/* -    SPICELIB Version 1.0.0, 07-NOV-2001 */

/* -& */

/*     Unit and file table size parameters. */

/*     FTSIZE     is the maximum number of files (DAS and DAF) that a */
/*                user may have open simultaneously. */


/*     RSVUNT     is the number of units protected from being locked */
/*                to a particular handle by ZZDDHHLU. */


/*     SCRUNT     is the number of units protected for use by scratch */
/*                files. */


/*     UTSIZE     is the maximum number of logical units this manager */
/*                will utilize at one time. */


/*     Access method enumeration.  These parameters are used to */
/*     identify which access method is associated with a particular */
/*     handle.  They need to be synchronized with the STRAMH array */
/*     defined in ZZDDHGSD in the following fashion: */

/*        STRAMH ( READ   ) = 'READ' */
/*        STRAMH ( WRITE  ) = 'WRITE' */
/*        STRAMH ( SCRTCH ) = 'SCRATCH' */
/*        STRAMH ( NEW    ) = 'NEW' */

/*     These values are used in the file table variable FTAMH. */


/*     Binary file format enumeration.  These parameters are used to */
/*     identify which binary file format is associated with a */
/*     particular handle.  They need to be synchronized with the STRBFF */
/*     array defined in ZZDDHGSD in the following fashion: */

/*        STRBFF ( BIGI3E ) = 'BIG-IEEE' */
/*        STRBFF ( LTLI3E ) = 'LTL-IEEE' */
/*        STRBFF ( VAXGFL ) = 'VAX-GFLT' */
/*        STRBFF ( VAXDFL ) = 'VAX-DFLT' */

/*     These values are used in the file table variable FTBFF. */


/*     Some random string lengths... more documentation required. */
/*     For now this will have to suffice. */


/*     Architecture enumeration.  These parameters are used to identify */
/*     which file architecture is associated with a particular handle. */
/*     They need to be synchronized with the STRARC array defined in */
/*     ZZDDHGSD in the following fashion: */

/*        STRARC ( DAF ) = 'DAF' */
/*        STRARC ( DAS ) = 'DAS' */

/*     These values will be used in the file table variable FTARC. */


/*     For the following environments, record length is measured in */
/*     characters (bytes) with eight characters per double precision */
/*     number. */

/*     Environment: Sun, Sun FORTRAN */
/*     Source:      Sun Fortran Programmer's Guide */

/*     Environment: PC, MS FORTRAN */
/*     Source:      Microsoft Fortran Optimizing Compiler User's Guide */

/*     Environment: Macintosh, Language Systems FORTRAN */
/*     Source:      Language Systems FORTRAN Reference Manual, */
/*                  Version 1.2, page 12-7 */

/*     Environment: PC/Linux, g77 */
/*     Source:      Determined by experiment. */

/*     Environment: PC, Lahey F77 EM/32 Version 4.0 */
/*     Source:      Lahey F77 EM/32 Language Reference Manual, */
/*                  page 144 */

/*     Environment: HP-UX 9000/750, FORTRAN/9000 Series 700 computers */
/*     Source:      FORTRAN/9000 Reference-Series 700 Computers, */
/*                  page 5-110 */

/*     Environment: NeXT Mach OS (Black Hardware), */
/*                  Absoft Fortran Version 3.2 */
/*     Source:      NAIF Program */


/*     The following parameter defines the size of a string used */
/*     to store a filenames on this target platform. */


/*     The following parameter controls the size of the character record */
/*     buffer used to read data from non-native files. */

/* $ Brief_I/O */

/*     VARIABLE  I/O  DESCRIPTION */
/*     --------  ---  -------------------------------------------------- */
/*     FNAME      I   Name of the file to convert to a handle. */
/*     FTABS, */
/*     FTAMH, */
/*     FTARC, */
/*     FTBFF, */
/*     FTHAN, */
/*     FTNAM, */
/*     FTRTM, */
/*     FTMNM      I   File table. */
/*     NFT        I   Number of entries in the file table. */
/*     UTCST, */
/*     UTHAN, */
/*     UTLCK, */
/*     UTLUN     I/O  Unit table. */
/*     NUT       I/O  Number of entries in the unit table. */
/*     EXISTS     O   Logical indicating if FNAME exists. */
/*     OPENED     O   Logical indicating if FNAME is opened. */
/*     HANDLE     O   Handle associated with FNAME. */
/*     FOUND      O   Logical indicating if FNAME's HANDLE was found. */
/*     MNM        O   Unique DP (Magic NuMber) associated with FNAME. */

/* $ Detailed_Input */

/*     FNAME      is the name of the file to locate in the file table. */

/*     FTABS, */
/*     FTAMH, */
/*     FTARC, */
/*     FTBFF, */
/*     FTHAN, */
/*     FTNAM, */
/*     FTRTM, */
/*     FTMNM      are the arrays respectively containing the absolute */
/*                value of the handle, access method, architecture, */
/*                binary file format, handle, name, RTRIM and */
/*                magic number columns of the file table. */

/*     NFT        is the number of entries in the file table. */

/*     UTCST, */
/*     UTHAN, */
/*     UTLCK, */
/*     UTLUN      are the arrays respectively containing the cost, */
/*                handle, locked, and logical unit columns of the unit */
/*                table. */

/*     NUT        is the number of entries in the unit table. */

/* $ Detailed_Output */

/*     UTCST, */
/*     UTHAN, */
/*     UTLCK, */
/*     UTLUN      are the arrays respectively containing the cost, */
/*                handle, locked, and logical unit columns of the unit */
/*                table.  If ZZDDHF2H requires a logical unit, then */
/*                it will borrow one from the unit table.  Depending */
/*                on the state of the table passed in from the caller */
/*                one of three possible scenarios may occur (Recall */
/*                that 'zero-cost' rows are ones whose units are */
/*                reserved with RESLUN and not currently connected */
/*                to any file.) */

/*                   A 'zero-cost' row exists in the table, in */
/*                   which case the row is used temporarily and */
/*                   may be removed depending on the number of entries */
/*                   in the file table (NFT). */

/*                   The unit table is full (NUT=UTSIZE), in which */
/*                   case the unit with the lowest cost that is not */
/*                   locked to its handle will be disconnected, used, */
/*                   and then returned to the table as a 'zero-cost' */
/*                   row before returning to the caller. */

/*                   The unit table is not full (NUT<UTSIZE) and there */
/*                   are no 'zero-cost' rows.  In this case NUT is */
/*                   temporarily increased by one, and the new row */
/*                   is used.  After this routine no longer requires */
/*                   the unit, depending on the number of entries in */
/*                   the file table (NFT) the row may be left in the */
/*                   table as a 'zero-handle' row or removed entirely. */

/*                In the event an error is signaled, the contents of the */
/*                unit table are placed into a usable state before */
/*                returning to the caller. */

/*     NUT        is the number of entries in the unit table. Since */
/*                this routine borrows a unit from the unit table, which */
/*                may involve allocation of a new unit, this value may */
/*                change. */

/*     EXISTS     is a logical if set to TRUE, indicates that FNAME */
/*                exists.  If FALSE, FNAME does not exist.  In the event */
/*                an exception is signaled the value is undefined. */

/*     OPENED     is a logical if set to TRUE, indicates that FNAME */
/*                is opened and attached to a logical unit.  If FALSE, */
/*                FNAME is not attached to a unit.  In the event an */
/*                exception is signaled the value is undefined. */

/*     HANDLE     is the handle in the file table associated with */
/*                FNAME.  If FOUND is FALSE, then HANDLE is returned as */
/*                0. */

/*     FOUND      is a logical if TRUE indicates that FNAME was found */
/*                in the file table.  If FALSE indicates that it was not */
/*                located. */

/*     MNM        is a unique (enough) DP number -- the Magic NuMber -- */
/*                associated with FNAME computed by this examining the */
/*                file contents. */

/* $ Parameters */

/*     None. */

/* $ Exceptions */

/*     1) If any of the INQUIRE statments this routine performs fail, */
/*        the error SPICE(INQUIREFAILED) is signaled. FOUND is set to */
/*        FALSE and HANDLE to 0. */

/*     2) If the attempt to open FNAME fails, then SPICE(FILEOPENFAILED) */
/*        is signaled. FOUND is set to FALSE, and HANDLE to 0. */

/*     3) If FNAME is determined not to be loaded into the file table */
/*        then FOUND is set to FALSE and HANDLE is set to 0. */

/* $ Files */

/*     If the file named by FNAME is not connected to a logical unit, */
/*     this routine will open it for direct access to complete its */
/*     examination. */

/* $ Particulars */

/*     This routine encapsulates the logic necessary to determine if */
/*     a particular filename names a file already loaded into the */
/*     DAF/DAS handle manager.  If it discovers the file is loaded, */
/*     the routine returns the handle to the caller. */

/* $ Examples */

/*     See ZZDDHFNH for sample usage. */

/* $ Restrictions */

/*     None. */

/* $ Literature_References */

/*     None. */

/* $ Author_and_Institution */

/*     F.S. Turner     (JPL) */
/*     E.D. Wright     (JPL) */
/*     B.V. Semenov    (JPL) */

/* $ Version */

/* -    SPICELIB Version 3.0.0, 26-APR-2012 (BVS) */

/*        Changed calling sequence to include FTMNM and MNM. Change */
/*        algorithm to compute MNM and use it to bypass n^2 INQUIREs */
/*        for files opened for READ access, if possible. */

/* -    SPICELIB Version 2.0.1, 24-APR-2003 (EDW) */

/*        Added MAC-OSX-F77 to the list of platforms */
/*        that require READONLY to read write protected */
/*        kernels. */

/* -    SPICELIB Version 2.0.0, 05-AUG-2002 (FST) */

/*        Bug fix: this module was updated to allow proper loading */
/*        of read-only files on VAX environments. */

/* -    SPICELIB Version 1.0.0, 04-OCT-2001 (FST) */


/* -& */
/* $ Revisions */

/* -    SPICELIB Version 2.0.0, 05-AUG-2002 (FST) */

/*        An OPEN statement that is exercised by this module under */
/*        certain circumstances, failed to pass the non-standard */
/*        READONLY option for the VAX environments.  This had the */
/*        undesirable side-effect of not permitting files available */
/*        only for READ access to be opened. */

/*        This file was promoted from a standard portable module */
/*        to a master file. */

/* -& */

/*     SPICELIB Functions */


/*     Local Variables */


/*     Standard SPICE error handling. */

    if (return_()) {
	return 0;
    } else {
	chkin_("ZZDDHF2H", (ftnlen)8);
    }

/*     First check to see if FNAME is blank.  If so, set FOUND to .FALSE. */
/*     and return.  ZZDDHOPN prevents any blank filenames from being */
/*     loaded into the file table. */

    if (s_cmp(fname, " ", fname_len, (ftnlen)1) == 0) {
	*found = FALSE_;
	*handle = 0;
	*opened = FALSE_;
	*exists = FALSE_;
	chkout_("ZZDDHF2H", (ftnlen)8);
	return 0;
    }

/*     Start by trimming the file name in preparation for the INQUIRE. */

    rchar = rtrim_(fname, fname_len);

/*     Now INQUIRE on the input file FNAME. */

    ioin__1.inerr = 1;
    ioin__1.infilen = rchar;
    ioin__1.infile = fname;
    ioin__1.inex = &locexs;
    ioin__1.inopen = &locopn;
    ioin__1.innum = &unit;
    ioin__1.innamed = 0;
    ioin__1.inname = 0;
    ioin__1.inacc = 0;
    ioin__1.inseq = 0;
    ioin__1.indir = 0;
    ioin__1.infmt = 0;
    ioin__1.inform = 0;
    ioin__1.inunf = 0;
    ioin__1.inrecl = 0;
    ioin__1.innrec = 0;
    ioin__1.inblank = 0;
    iostat = f_inqu(&ioin__1);

/*     Check IOSTAT for failure. */

    if (iostat != 0) {
	*found = FALSE_;
	*handle = 0;
	setmsg_("INQUIRE failed. Value of IOSTAT was #.", (ftnlen)38);
	errint_("#", &iostat, (ftnlen)1);
	sigerr_("SPICE(INQUIREFAILED)", (ftnlen)20);
	chkout_("ZZDDHF2H", (ftnlen)8);
	return 0;
    }

/*     First, set some of the output arguments.  Remember, some */
/*     systems consider non-existant files as open.  Compensate for */
/*     this unusual behavior. */

    *exists = locexs;
    *opened = locopn && *exists;

/*     Now check to see if the file exists.  If it does not, then */
/*     set FOUND to false and HANDLE to 0 as non-existant files */
/*     can not possibly be present in the file table. */

    if (! (*exists)) {
	*found = FALSE_;
	*handle = 0;
	chkout_("ZZDDHF2H", (ftnlen)8);
	return 0;
    }

/*     Now check to see if the file is opened.  If it is, we need to */
/*     determine whether or not the logical unit to which it is */
/*     attached is present in the unit table. */

    if (*opened) {

/*        Since the file is opened, see if we can find its unit */
/*        in the unit table. */

	uindex = isrchi_(&unit, nut, utlun);

/*        When UINDEX is 0, the file is opened, but not by */
/*        the DAF/DAS handle manager.  Set FOUND to FALSE, HANDLE */
/*        to 0, and return to the caller. */

	if (uindex == 0) {
	    *handle = 0;
	    *found = FALSE_;
	    chkout_("ZZDDHF2H", (ftnlen)8);
	    return 0;
	}

/*        If we end up here, then we found UNIT in the unit table. */
/*        Set FOUND to TRUE if the handle associated with UNIT is */
/*        non-zero. */

	*handle = uthan[uindex - 1];
	*found = *handle != 0;
	chkout_("ZZDDHF2H", (ftnlen)8);
	return 0;
    }

/*     At this point, we took action for all simple cases.  Now */
/*     we need to find out if FNAME is one of the files in the */
/*     file table that isn't open.  To determine this, we open FNAME, */
/*     and then INQUIRE on every file in the table.  To do this, we */
/*     need a unit. Get one. */

    zzddhgtu_(utcst, uthan, utlck, utlun, nut, &uindex);
    if (failed_()) {
	*handle = 0;
	*found = FALSE_;
	chkout_("ZZDDHF2H", (ftnlen)8);
	return 0;
    }

/*     Now open the file (which we know exists and isn't open). Since */
/*     we effectively are just borrowing this unit, we are not going to */
/*     set UTHAN or UTCST from the defaults that ZZDDHGTU sets up. */

    o__1.oerr = 1;
    o__1.ounit = utlun[uindex - 1];
    o__1.ofnmlen = rchar;
    o__1.ofnm = fname;
    o__1.orl = 1024;
    o__1.osta = "OLD";
    o__1.oacc = "DIRECT";
    o__1.ofm = 0;
    o__1.oblnk = 0;
    iostat = f_open(&o__1);

/*     Check IOSTAT. */

    if (iostat != 0) {

/*        Since an error has occurred, set FOUND to false and HANDLE */
/*        to 0. */

	*found = FALSE_;
	*handle = 0;

/*        Close the unit and remove it from the unit table. */

	cl__1.cerr = 0;
	cl__1.cunit = utlun[uindex - 1];
	cl__1.csta = 0;
	f_clos(&cl__1);
	zzddhrmu_(&uindex, nft, utcst, uthan, utlck, utlun, nut);

/*        Signal the error and return. */

	setmsg_("Attempt to open file '#' failed. Value of IOSTAT was #.", (
		ftnlen)55);
	errch_("#", fname, (ftnlen)1, fname_len);
	errint_("#", &iostat, (ftnlen)1);
	sigerr_("SPICE(FILEOPENFAILED)", (ftnlen)21);
	chkout_("ZZDDHF2H", (ftnlen)8);
	return 0;
    }

/*     Get a unique enough DP number -- the Magic NuMber (MNM) ;) -- for */
/*     this file. */

    *mnm = zzddhmnm_(&utlun[uindex - 1]);

/*     Now loop through all the files in the file table. Unfortunately */
/*     we have no other choice. */

    i__ = 1;
    *found = FALSE_;
    while(i__ <= *nft && ! (*found)) {

/*        If this file's magic number is non-zero and is different from */
/*        the magic number of the currently checked, opened-for-READ */
/*        file, we will declare that these files are not the same file */
/*        and will skip INQUIRE. In all other cases we will do INQUIRE */
/*        and check UNITs. */

	if (*mnm != 0. && (*mnm != ftmnm[i__ - 1] && ftamh[i__ - 1] == 1)) {

/*           These files are not the same file. Clear IOSTAT and set */
/*           UNIT to not match the UNIT of the input file. */

	    iostat = 0;
	    unit = utlun[uindex - 1] + 1;
	} else {

/*           Do the INQUIRE. ;( */

	    ioin__1.inerr = 1;
	    ioin__1.infilen = ftrtm[i__ - 1];
	    ioin__1.infile = ftnam + (i__ - 1) * ftnam_len;
	    ioin__1.inex = &locexs;
	    ioin__1.inopen = &locopn;
	    ioin__1.innum = &unit;
	    ioin__1.innamed = 0;
	    ioin__1.inname = 0;
	    ioin__1.inacc = 0;
	    ioin__1.inseq = 0;
	    ioin__1.indir = 0;
	    ioin__1.infmt = 0;
	    ioin__1.inform = 0;
	    ioin__1.inunf = 0;
	    ioin__1.inrecl = 0;
	    ioin__1.innrec = 0;
	    ioin__1.inblank = 0;
	    iostat = f_inqu(&ioin__1);
	}

/*        Check IOSTAT. */

	if (iostat != 0) {

/*           Since we have an error condition, set FOUND to FALSE */
/*           and HANDLE to 0. */

	    *found = FALSE_;
	    *handle = 0;

/*           Close the unit and clean up the unit table. */

	    cl__1.cerr = 0;
	    cl__1.cunit = utlun[uindex - 1];
	    cl__1.csta = 0;
	    f_clos(&cl__1);
	    zzddhrmu_(&uindex, nft, utcst, uthan, utlck, utlun, nut);

/*           Signal the error and return. */

	    setmsg_("INQUIRE failed. Value of IOSTAT was #.", (ftnlen)38);
	    errint_("#", &iostat, (ftnlen)1);
	    sigerr_("SPICE(INQUIREFAILED)", (ftnlen)20);
	    chkout_("ZZDDHF2H", (ftnlen)8);
	    return 0;
	}

/*        Now check to see if FILE exists, is currently open. and */
/*        its UNIT matches UTLUN(UINDEX). */

	if (locexs && locopn && unit == utlun[uindex - 1]) {
	    *handle = fthan[i__ - 1];
	    *found = TRUE_;

/*        Otherwise, continue searching. */

	} else {
	    ++i__;
	}
    }

/*     Check to see if we found the file in the file table. */

    if (! (*found)) {
	*handle = 0;
    }

/*     Close the unit and clean up the unit table. */

    cl__1.cerr = 0;
    cl__1.cunit = utlun[uindex - 1];
    cl__1.csta = 0;
    f_clos(&cl__1);
    zzddhrmu_(&uindex, nft, utcst, uthan, utlck, utlun, nut);
    chkout_("ZZDDHF2H", (ftnlen)8);
    return 0;
} /* zzddhf2h_ */
示例#6
0
/**
  * @brief  Save the image frame into a file
  * @param  Storage path
  * @param  file_name 
  * @retval Status 0 = Sucess, !0 :error
  */
static uint8_t Save_Bmp_To_File (uint8_t *path , uint8_t *file_name)
{
  RTC_TimeTypeDef   RTC_TimeStructure;
  RTC_DateTypeDef   RTC_DateStructure;
  uint32_t i = 0 ,j = 0 , Index;

  FIL file;

  for ( i = 0 ; i < IMAGE_COLUMN_SIZE; i++)
  {
    for ( j= 0 ; j < 2 * IMAGE_LINE_SIZE; j++)
    {
      ImageBuffer.SrcData[j + (2 * IMAGE_LINE_SIZE * i)] = ImageBuffer.RawData[j + (2 * IMAGE_LINE_SIZE * ( IMAGE_COLUMN_SIZE- 1 - i))];
    }
  }


  /* Convert RGB16 image to RGB24 */
  RGB16toRGB24(ImageBuffer.DestData, ImageBuffer.SrcData, 1);

  /* Update file name */
  strcpy((char *)ImageBuffer.ImageName , (char *)path),
  strcat ((char *)ImageBuffer.ImageName, "/");

  if ( RTC_Error == 0)
  {
    RTC_GetTime(RTC_Format_BIN, &RTC_TimeStructure);
    RTC_GetDate(RTC_Format_BIN, &RTC_DateStructure);

    sprintf((char *)file_name, "Camera_%02d%02d%d%02d%02d%02d.bmp", RTC_DateStructure.RTC_Date,
            RTC_DateStructure.RTC_Month,
            RTC_DateStructure.RTC_Year + 2000,
            RTC_TimeStructure.RTC_Hours,
            RTC_TimeStructure.RTC_Minutes,
            RTC_TimeStructure.RTC_Seconds);
  }
  else
  {
    /* Wait until one RNG number is ready */
    while(RNG_GetFlagStatus(RNG_FLAG_DRDY)== RESET)
    {
    }
    RecoveryImageCounter = (uint32_t )(RNG_GetRandomNumber() & 0x7FFFFFFF) ;
    sprintf((char *)file_name, "Camera_%014d.bmp", (int)RecoveryImageCounter);
  }

  strcat ((char *)ImageBuffer.ImageName, (char *)file_name);


  /* Can not create file */
  if (f_open(&file, (char *)ImageBuffer.ImageName, FA_CREATE_NEW | FA_WRITE) != FR_OK)
  {
    return 0;
  }

  /* Write the received data into the file */
  if (f_write(&file, (char*)ImageBuffer.ImageHeader, RGB_HEADER_SIZE, (UINT*)&Index))
  {
    f_close(&file);
    return 0;
  }

  if (f_write(&file, (char*)ImageBuffer.DestData, MAX_IMAGE_SIZE, (UINT*)&Index))
  {
    f_close(&file);
    return 0;
  }
  /* Close file */
  f_close(&file);
  return 1 ;
}
示例#7
0
void cmd_sdiotest(void) {
  uint32_t i = 0;
  FRESULT err = 0;
  bool_t format = FALSE;


  chThdSleepMilliseconds(100);

  if (!sdioConnect ()) {
    sdioDebug ("   FAIL\r\n ");
    return;
  }

  if (TRUE) {
    sdioDebug ("OK\r\n");
    sdioDebug ("*** Card CSD content is: ");
    sdioDebug ("%X %X %X %X \r\n", (&SDCD1)->csd[3], (&SDCD1)->csd[2],
        (&SDCD1)->csd[1], (&SDCD1)->csd[0]);


    sdioDebug ("capacity = %d sectors of 512 bytes = %d Mo\r\n",
        SDCD1.capacity, SDCD1.capacity / 2048);

    sdioDebug ("Single aligned read...");
    chThdSleepMilliseconds(100);
    if (sdcRead(&SDCD1, 0, inbuf, 1))
      goto error;
    sdioDebug (" OK\r\n");
    chThdSleepMilliseconds(100);


    sdioDebug ("Single unaligned read...");
    chThdSleepMilliseconds(100);
    if (sdcRead(&SDCD1, 0, inbuf + 1, 1))
      goto error;
    if (sdcRead(&SDCD1, 0, inbuf + 2, 1))
      goto error;
    if (sdcRead(&SDCD1, 0, inbuf + 3, 1))
      goto error;
    sdioDebug (" OK\r\n");
    chThdSleepMilliseconds(100);


    sdioDebug ("Multiple aligned reads...");
    chThdSleepMilliseconds(100);
    fillbuffers(0x55);
    /* fill reference buffer from SD card */
    if (sdcRead(&SDCD1, 0, inbuf, SDC_BURST_SIZE))
      goto error;
    for (i=0; i<1000; i++){
      if (sdcRead(&SDCD1, 0, outbuf, SDC_BURST_SIZE))
        goto error;
      if (memcmp(inbuf, outbuf, SDC_BURST_SIZE * MMCSD_BLOCK_SIZE) != 0)
        goto error;
    }
    sdioDebug (" OK\r\n");
    chThdSleepMilliseconds(100);


    sdioDebug ("Multiple unaligned reads...");
    chThdSleepMilliseconds(100);
    fillbuffers(0x55);
    /* fill reference buffer from SD card */
    if (sdcRead(&SDCD1, 0, inbuf + 1, SDC_BURST_SIZE))
      goto error;
    for (i=0; i<1000; i++){
      if (sdcRead(&SDCD1, 0, outbuf + 1, SDC_BURST_SIZE))
        goto error;
      if (memcmp(inbuf, outbuf, SDC_BURST_SIZE * MMCSD_BLOCK_SIZE) != 0)
        goto error;
    }
    sdioDebug (" OK\r\n");
    chThdSleepMilliseconds(100);

#if SDC_DATA_DESTRUCTIVE_TEST
    if (format) {

      sdioDebug ("Single aligned write...");
      chThdSleepMilliseconds(100);
      fillbuffer(0xAA, inbuf);
      if (sdcWrite(&SDCD1, 0, inbuf, 1))
        goto error;
      fillbuffer(0, outbuf);
      if (sdcRead(&SDCD1, 0, outbuf, 1))
        goto error;
      if (memcmp(inbuf, outbuf, MMCSD_BLOCK_SIZE) != 0)
        goto error;
      sdioDebug (" OK\r\n");

      sdioDebug ("Running badblocks at 0x10000 offset...");
      chThdSleepMilliseconds(100);
      if(badblocks(0x10000, 0x11000, SDC_BURST_SIZE, 0xAA))
        goto error;
      sdioDebug (" OK\r\n");
    } else {

    }
#endif /* !SDC_DATA_DESTRUCTIVE_TEST */


    /**
     * Now perform some FS tests.
     */

    DWORD clusters=0;
    FATFS *fsp=NULL;
    FIL FileObject;
    uint32_t bytes_written=0;
    uint32_t bytes_read=0;
    FILINFO fno ;
#if _USE_LFN
    char lfn[_MAX_LFN + 1];
    fno.lfname = lfn;
    fno.lfsize = sizeof lfn;
#endif

    const uint8_t teststring[] = {"This is test file\r\n"} ;
    /* FS object.*/
    static FATFS SDC_FS;




#if SDC_DATA_DESTRUCTIVE_TEST
    if (format) {
      sdioDebug ("Formatting... ");
      chThdSleepMilliseconds(100);

      sdioDebug ("Register working area for filesystem... ");
      chThdSleepMilliseconds(100);
      err = f_mount(0, &SDC_FS);
      if (err != FR_OK){
        goto error;
      }
      else{
        sdioDebug ("OK\r\n");
      }
    }

    if (format) {
      sdioDebug ("f_mkfs starting ... ");
      chThdSleepMilliseconds(100);
      err = f_mkfs (0,0,0);
      if (err != FR_OK){
        goto error;
      }  else {
        sdioDebug ("OK\r\n");
      }
    }
#endif /* SDC_DATA_DESTRUCTIVE_TEST */


    sdioDebug ("get free space on filesystem... ");
    chThdSleepMilliseconds(100);
    err =  f_getfree(NULL, &clusters, &fsp);

    if (err != FR_OK)
      goto error;

    sdioDebug ("OK\r\n");
    sdioDebug ("FS: %lu free clusters, %lu sectors per cluster, %lu bytes free\r\n",
        clusters, (uint32_t)SDC_FS.csize,
        clusters * (uint32_t)SDC_FS.csize * (uint32_t)MMCSD_BLOCK_SIZE);


    sdioDebug ("Create file \"chtest.txt\"... ");
    chThdSleepMilliseconds(100);
    err = f_open(&FileObject, "chtest.txt", FA_WRITE | FA_OPEN_ALWAYS);
    if (err != FR_OK) {
      goto error;
    }
    sdioDebug ("OK\r\n");
    sdioDebug ("Write some data in it... ");
    chThdSleepMilliseconds(100);
    err = f_write(&FileObject, teststring, sizeof(teststring), (void *)&bytes_written);
    if (err != FR_OK) {
      goto error;
    }
    else
      sdioDebug ("OK\r\n");

    sdioDebug ("Close file \"chtest.txt\"... ");
    err = f_close(&FileObject);
    if (err != FR_OK) {
      goto error;
    }
    else
      sdioDebug ("OK\r\n");


    sdioDebug ("Check file size \"chtest.txt\"... ");
    chThdSleepMilliseconds(10);
    err = f_stat("chtest.txt", &fno);
    chThdSleepMilliseconds(100);
    if (err != FR_OK) {
      goto error;
    } else {
      if (fno.fsize == sizeof(teststring)) {
        sdioDebug ("OK\r\n");
      }
      else
        goto error;
    }


    sdioDebug ("Check file content \"chtest.txt\"... ");
    err = f_open(&FileObject, "chtest.txt", FA_READ | FA_OPEN_EXISTING);
    chThdSleepMilliseconds(100);
    if (err != FR_OK) {
      goto error;
    }
    uint8_t buf[sizeof(teststring)];
    err = f_read(&FileObject, buf, sizeof(teststring), (void *)&bytes_read);
    if (err != FR_OK) {
      goto error;
    } else {
      if (memcmp(teststring, buf, sizeof(teststring)) != 0){
        goto error;
      } else {
        sdioDebug ("OK\r\n");
      }
    }

    {
      FILINFO fno;
      DIR dir;
      //    char *fn;   /* This function is assuming non-Unicode cfg. */
#if _USE_LFN
      char lfn[_MAX_LFN + 1];
      fno.lfname = lfn;
      fno.lfsize = sizeof lfn;
#endif
      const char *path = "";
      FRESULT res =0;

      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.fname[0] == '.') continue;             /* Ignore dot entry */
#if _USE_LFN
          // fn = fno.lfname;
#else
          // fn = fno.fname;
#endif
          /* It is a file. */
          //chprintf(chp, "readdir %s/%s\r\n", path, fn);
        }
      }
    }

    sdioDebug ("Umount filesystem... ");
    f_mount(0, NULL);
    sdioDebug ("OK\r\n");

    sdioDebug ("Disconnecting from SDIO...");
    chThdSleepMilliseconds(100);
    if (!sdioDisconnect())
      goto error;
    sdioDebug (" OK\r\n");
    sdioDebug ("------------------------------------------------------\r\n");
    sdioDebug ("All tests passed successfully.\r\n");
    chThdSleepMilliseconds(100);


    sdioDisconnect();
    return;
  }
error:
  sdioDebug ("SDC error [%d] occurs\r\n", err);
  sdioDisconnect();
}
示例#8
0
u8 mf_open(u8*path,u8 mode)
{
	u8 res;
	res=f_open(&file,(const TCHAR*)path,mode);//打开文件夹
	return res;
} 
示例#9
0
int main() {
	FIL Filin, Filout;			/* File object needed for each open file */
	UINT bw;
	char line[80];
	char *ptr, *ptr2;
	long p1, p2, p3;
	BYTE res, b1, *bp;
	//UINT s1, s2, cnt, blen = sizeof Buff;
	DWORD ofs, sect = 0;
	BYTE buffer[4096];
	char buff[256];
	UINT br;
	//FATFS *fs;
	//RTC rtc;

 
	int i, j, l, k, hardware=1;
	char msg[100];
	k=hardware;
	if(hardware){
	for(i=0;i<400;i++)	
		for(j=0;j<400;j++)
			LED = 0;
	}
 
	 res = f_mount(&FatSD, "", 0);		/* Give a work area to the default drive */
/*
	res = disk_status(MMC);		
     snprintf(msg,100, "Status : %d\n", res);
	send_uart(msg);
*/
    // Initialise media
    //disk_initialize(MMC);
/*
    res = disk_status(MMC);		
     snprintf(msg,100, "Status : %d\n", res);
	send_uart(msg);
   */  
    
 
   
 	//snprintf(msg,100, "Mount response: %d\n", res);
	//send_uart(msg);
  
	//res |= f_mkfs("0:", 1, 1);
   	//disk_read(MMC, FatSD.win, 0, 1);
   	//FatSD.winsect = 1;
   	//res = move_window(&FatSD, 0);

        
   	      
	//snprintf(msg,100, "mkfs response: %d\n", res);
	//send_uart(msg);
    /*         	
	res = disk_status(MMC);		
     snprintf(msg,100, "Status : %d\n", res);
	send_uart(msg);
*/
	//res = f_open(&Filout, "test.txt", FA_WRITE | FA_CREATE_ALWAYS);
	//res = f_open(&Filin, "test.txt", FA_READ);
	//snprintf(msg,100, "Open response: %d\n", res);
	//send_uart(msg);

    
	/*disk_read(MMC,Buff,0,1);
		for(i = 0; i<512; i++){
			snprintf(msg,100, "%02X", Buff[i]);
			send_uart(msg);
		}
	*/ 
	//if ( res == FR_OK) {	/* Create a file */
	//		send_uart("open file");
			
			//res = f_write(&Filout, "It works!\r\n", 11, &bw);	/* Write data to the file */
			//snprintf(msg,100, "Write response: %d\n", res);
			//res = f_close(&Filout);
			
			//send_uart(msg);
			
			//snprintf(msg,100, "F Close response: %d\n", res);
			//send_uart(msg);

	//	if (bw == 11) {		/* Lights green LED if data written well */
	//		LED = 1;	/* Set PB4 high */
	//	}
	//}  

	
	//res = disk_status(MMC);		
    // snprintf(msg,100, "\nStatus : %d\n", res);
	//send_uart(msg);
	//while(1);
	/*
	disk_ioctl(1, GET_SECTOR_COUNT, &p2);
	snprintf(msg,100, "Drive size: %lu sectors\n", p2);
	send_uart(msg);

	res = f_getlabel(ptr2, (char*)Buff, (DWORD*)&p1);
				//if (res) { put_rc(res); break; }
				Buff[0] ? snprintf(msg,100, "Volume name is %s\n", Buff) : snprintf(msg,100, "No volume label\n");
				send_uart(msg);
				//xprintf(Buff[0] ? PSTR("Volume name is %s\n") : PSTR("No volume label\n"), Buff);
				//xprintf(PSTR("Volume S/N is %04X-%04X\n"), (WORD)((DWORD)p1 >> 16), (WORD)(p1 & 0xFFFF));*/  
  
	while(1){
	send_uart("\nWelocme to FatF for Patmos\n");
	send_uart("Options are:\n");
	send_uart("O [r/w] [filename] [content if writemode]\n");
	send_uart("l for file and dir structure\n");
	send_uart("Opening a file in readmode will print the content to terminal\n");
	send_uart("Write mode is not implemented\n");
	send_uart("use ^M (ctrl-V) + enter to terminate input\n");
	
	ptr = line;
	get_line(ptr, sizeof line);
	switch (*ptr++) {

		case 'T' :
			while (*ptr == ' ') ptr++;

			/* Quick test space */

			break;
		case 'O' :
		case 'o' :
			while (*ptr == ' ') ptr++;
			switch(*ptr++){
				case 'R' :
				case 'r' :
					while (*ptr == ' ') ptr++;
					res = f_open(&Filin, ptr, FA_READ);
					res = f_read(&Filin, buffer, sizeof(buffer), &br);	/* read data from the file */	
					res = f_close(&Filin);								/* Close the file */
					send_uart("\nThis is the content of the file: \n\n");
					for(i=0; i < br; i++){
   					snprintf(msg,100, "%c", buffer[i]);
					send_uart(msg);
					}
					send_uart("\n\n"); 
					break;

				case 'W' : 
				case 'w' : 
					//ptr = line;
					//send_uart("Enter filename:\n");
					//get_line(ptr, sizeof line);
					res = f_open(&Filout, "newtest.txt", FA_WRITE | FA_CREATE_ALWAYS);
					snprintf(msg,100, "\nOpen response : %d\n", res);
					send_uart(msg);
					//res = f_open(&Filout, ptr, FA_WRITE | FA_CREATE_ALWAYS);
					//res = f_open(&Filin, ptr, FA_READ);
					//&Filout, "It works!\r\n", 11, &bw)
					//ptr = line;
					//send_uart("Enter content:\n" 	);
					//get_line(ptr, sizeof line);
					res = f_write(&Filout, "It works!\r\n", 11, &bw);
					snprintf(msg,100, "\nWrite response : %d\n", res);
					send_uart(msg);
					//res = f_write(&Filout, ptr, sizeof(line), &br);	/* read data from the file */	
					res = f_close(&Filout);								/* Close the file */

			}
			break;
		case 'l' :
		case 'L' :
			strcpy(buff, "/");
        	res = scan_files(buff);
        	break;
		}

	}   
	  
	
	for (;;) {
		if(k==0){
		for(l=0; l<10; l++){
			for(i=0;i<2000;i++)	
				for(j=0;j<2000;j++)
					LED = 1;
			for(i=0;i<2000;i++)	
				for(j=0;j<2000;j++){
					LED = 0;
					}
		}
		for(i=0;i<2000;i++)	
			for(j=0;j<2000;j++)
				for(l=0;l<20;l++)
					LED = 0;
		}
	}    
	
	return 0;
}
示例#10
0
文件: wavePlayer.c 项目: ADTL/ARMWork
void playWaveFile(void)
{

	uint8_t st;
	UINT btr;
	WAVFILE* wf;

	uint32_t temp, offset=44, cnt;

	ui_clearUserArea();
	ui_drawTitleBar("Play Wave File");
	ui_drawBottomBar("Stop", pause?"Play":"Pause", "Exit");
	ui_sethandler((pfn)wavePlayEventHandler);

	cx=3; cy=UI_TBARHEIGHT+3;

	if (playerThread) {
		lcd_puts("File Already Playing!");
		return;
	}

	st=f_open(&f1, "audio.wav", FA_READ);

	if (st) {
		lcd_puts("Invalid file");
		return;
	}

	st=f_read(&f1, buf, 1024, &btr);

	wf=(WAVFILE*)&buf[0];

	if (wf->riffSignature != WAVE_HEAD_RIFF || wf->fmtSignature != WAVE_HEAD_FMT || wf->format!=0x01) {
		lcd_puts("This is a not a wave file!");
		return;
	}

	xprintf("Number of channels=%d\nSample Rate=%ld\nNumber of Bits=%d\n", wf->numChannels, wf->sampleRate, wf->numBits);

	temp=READ_UINT32(&buf[36]);

	if (temp==WAVE_HEAD_DATA)
	{
		// Got 'data' chunk, ready to play
		waveSampleLength=READ_UINT32(&buf[40]);
		lcd_puts("No Metadata. Ready to play.\n");
		offset=44;
	}
	else if (temp==WAVE_META_LIST)
	{
		uint32_t msize;
		lcd_puts("File has metadata:");
		msize=READ_UINT32(&buf[40]);
		offset=52+msize;
		xprintf("%ld bytes.\nActual Data starts at offset:%ld\n", msize, offset);

		cnt=0;
		temp=READ_UINT32(&buf[44+cnt]);

		// Tag Reading Supported only on Audacity Output
		if (temp==WAVE_META_INFO)
		{
			cnt+=4;
			do
			{
				temp=READ_UINT32(&buf[44+cnt]);

				switch (temp)
				{
					case WAVE_META_INAM:
						cnt+=4;
						temp=READ_UINT32(&buf[44+cnt]);
						cnt+=4;
						xprintf("Name: %s\n", &buf[44+cnt]);
						cnt+=temp;
						break;

					case WAVE_META_IART:
						cnt+=4;
						temp=READ_UINT32(&buf[44+cnt]);
						cnt+=4;
						xprintf("Artist: %s\n", &buf[44+cnt]);
						cnt+=temp;
						break;

					case WAVE_META_ICMT:
						cnt+=4;
						temp=READ_UINT32(&buf[44+cnt]);
						cnt+=4;
						xprintf("Composer: %s\n", &buf[44+cnt]);
						cnt+=temp;
						break;

					case WAVE_META_ICRD:
						cnt+=4;
						temp=READ_UINT32(&buf[44+cnt]);
						cnt+=4;
						xprintf("Release Yr: %s\n", &buf[44+cnt]);
						cnt+=temp;
						break;

					default:
						cnt+=8;			// Token+Size (4 bytes each)
						break;
				}

			} while (cnt < msize);
			waveSampleLength=READ_UINT32(&buf[offset-4]);
			lcd_puts("Ready To Play.\n");
		}
	}

	codec_i2s_init(wf->sampleRate, wf->numBits);

	xprintf("Sample Length:%ld bytes", waveSampleLength);

	bytesToPlay=waveSampleLength;

	f_lseek(&f1, offset);

	playerThread=chThdCreateStatic(waThread3, sizeof(waThread3), NORMALPRIO+2, wavePlayerThread, NULL);
}
示例#11
0
int burnAPP(TCHAR *path) {
   int errorcode = 0;
   unsigned char *buf = (unsigned char *)0x80000000;
   unsigned char *buftemp = buf;
   unsigned char headbuf[512];
   unsigned int rdlen;
   APPHEADER *header = (APPHEADER * )headbuf;
   FIL file;
   FRESULT fret;
   int ret;
   char disbuf[32];
   unsigned int  percent = 0, percentold = 0;
   unsigned int  filesize, count;
   APPPACKHEAD *apppackhead = (APPPACKHEAD * )(buf + 32);
   APPSETCTION *appsection1 = &(apppackhead->appsec1);
   APPSETCTION *appsection2 = &(apppackhead->appsec2);
   fret = f_open(&file, path, FA_READ);
   if (fret != FR_OK) {
      errorcode = BURNAPP_READERROR;
      return errorcode;
   }
   filesize = file.fsize;
   if ((filesize > APP_MAX_SIZE) || (filesize <= 1024)) {
      errorcode = BURNAPP_FILE_ERROR;
      goto ERROR;
   }

   count = DIVUP(filesize, 512);
   memset(headbuf, 0, sizeof headbuf);
   statBarPrint(0, "reading");
   delay(300);
   for (int i = 0; i < count; i++, buftemp+=512) {
      fret = f_read(&file, buftemp, 512, &rdlen);
      if (fret != FR_OK)  goto ERROR;
      for (int j = 0; j < 256; j++) {
         buftemp[j] ^= ProgramTable[j];
         buftemp[j + 256] ^= ProgramTable[j];
      }
      if (i == 0) {
        /*
         if ((buftemp[0] != 'T') || (buftemp[1] != 'H') || (buftemp[2] != 'J')) {
            errorcode = BURNAPP_FILE_ERROR;
            goto ERROR;
         }
         if ((buftemp[10] != 'A') || (buftemp[11] != 'R') || (buftemp[12] != 'A')) {
            errorcode = BURNAPP_FILE_ERROR;
            goto ERROR;
         }
        */
         apppackhead = (APPPACKHEAD * )(buftemp + 32);
         appsection1 = &(apppackhead->appsec1);
         appsection2 = &(apppackhead->appsec2);
         if ((apppackhead->secflag & 0x01) &&
             ((appsection1->imageaddr + appsection1->imageSize) > (filesize - 16))) {
            errorcode = BURNAPP_FILE_ERROR;
            goto ERROR;
         }
         if ((apppackhead->secflag & 0x02) &&
             ((appsection2->imageaddr + appsection2->imageSize) > (filesize - 16))) {
            errorcode = BURNAPP_FILE_ERROR;
            goto ERROR;
         }
      } else {
         percent = i * 100 / count;
         if (percent / 5 != percentold / 5) {
            sprintf(disbuf, "%d%%", percent);
            statBarPrint(0, disbuf);
            percentold = percent;
         }
      }
   }
   MD5_CTX md5context;
   unsigned char decrypt[16];
   statBarPrint(0, "processing please waite");
   MD5Init(& md5context);
   MD5Update(& md5context, buf, filesize-16);
   MD5Final(& md5context, decrypt);
   if (memcmp(buf + filesize - 16, decrypt, 16)) {
      errorcode = BURNAPP_FILE_ERROR;
      goto ERROR;
   }
   statBarPrint(0, "write file please waite");
   delay(300);
   header->magic = APP_MAGIC_NO;
   header->secflag = apppackhead->secflag;
   if (apppackhead->secflag & 0x01) {
      header->appsec1.imageaddr = APP_BEGIN_SECTOR;
      header->appsec1.imageSize = DIVUP(appsection1->imageSize, 512);
      header->appsec1.imageRevPrefix = appsection1->imageRevPrefix;
      header->appsec1.imageMainRev = appsection1->imageMainRev;
      header->appsec1.imageMidRev = appsection1->imageMidRev;
      header->appsec1.imageMinRev = appsection1->imageMinRev;
   }
   if (apppackhead->secflag & 0x02) {
      header->appsec2.imageaddr = BAG_BEGIN_SETCTOR;
      header->appsec2.imageSize = DIVUP(appsection2->imageSize, 512);
      header->appsec2.imageRevPrefix = appsection2->imageRevPrefix;
      header->appsec2.imageMainRev = appsection2->imageMainRev;
      header->appsec2.imageMidRev = appsection2->imageMidRev;
      header->appsec2.imageMinRev = appsection2->imageMinRev;
   }
   ret = MMCSDP_Write(mmcsdctr, headbuf, APP_HEAD_SECTOR, 1);
   if (FALSE == ret) {
      errorcode = BURNAPP_WRITEERROR;
      goto ERROR;
   }
   if (apppackhead->secflag & 0x01) {
      ret = MMCSDP_Write(mmcsdctr, (void *)(buf + appsection1->imageaddr), header->appsec1.imageaddr, header->appsec1.imageSize);
      if (FALSE == ret) {
         errorcode = BURNAPP_WRITEERROR;
         goto ERROR;
      }
      header->magic = APP_MAGIC_OK;
   }
   if (apppackhead->secflag & 0x02) {
      ret = MMCSDP_Write(mmcsdctr, (void *)(buf + appsection2->imageaddr), header->appsec2.imageaddr, header->appsec2.imageSize);
      if (FALSE == ret) {
         errorcode = BURNAPP_WRITEERROR;
         goto ERROR;
      }
   }
   MMCSDP_Write(mmcsdctr, headbuf, APP_HEAD_SECTOR, 1);
   return 0;
ERROR:
   f_close(&file);
   return errorcode;
}
示例#12
0
BOOL burnBootloader(const TCHAR *path) {
   unsigned char *buf = (unsigned char *)0x80000000;
   unsigned int rdlen;
   FIL file;
   FRESULT fret;
   int ret;
   if (!strendwith(path, ".MBT")) {
      return FALSE;
   }
   fret = f_open(&file, path, FA_READ);
   if (fret != FR_OK) {
      return FALSE;
   }
   if (file.fsize > 109 * 1024) { //109KB
      goto ERROR;
   }
  
   memset(buf, 0, 512);
   memcpy(buf, emmcheader, sizeof emmcheader);
   *(unsigned int *)(buf + 512) = file.fsize;
   *(unsigned int *)(buf + 512 + 4) = BOOTLOADER_ENTRY;
   fret = f_read(&file, buf + 512 + 8, file.fsize, &rdlen);
   if (fret != FR_OK) {
      goto ERROR;
   }
   if (rdlen != file.fsize) {
      goto ERROR;
   }
   //memset(buf,0,file.fsize+8+512);
   ret = MMCSDP_Write(mmcsdctr, buf, BOOTLOADER_BEGIN_SECTOR, DIVUP(file.fsize + 8 + 512,512));
   if (FALSE == ret) {
      goto ERROR;
   }
   
   long long flashid;
   spiFlashReadId(&flashid);
   if ((flashid!=0)&&(flashid!=-1L)){
      unsigned char flashstatus = spiFlashReadStatus();
      if(!(flashstatus & 0x01)){
         spiFlashSwitch256PageSize();
         flashstatus = spiFlashReadStatus();
         if(!(flashstatus & 0x01)){
           goto ERROR;
         }
      }
   }
   unsigned int flashwcont = DIVUP(file.fsize+8,256);
   unsigned int byteswapcont = DIVUP(file.fsize+8,4);
   if ((flashid!=0)&&(flashid!=-1L)) {
      statBarPrint(0, "found dataflash chip ,burn to dataflash");
      for(int i=0;i<byteswapcont;i++){
         *(unsigned int *)(buf+512+4*i) = htonl(*(unsigned int *)(buf+512+4*i));
      }
      delay(500);
      unsigned char percent1 = 0,percent2 = 0;
      char checkbuf[256];
      for (int i=0;i<flashwcont;i++) {
         ret = spiFlashPageWrite(256*i,(void *)(buf + 512+256*i),256 );
         percent1 = (i+1)*100/flashwcont;
         if(percent1/5 != percent2/5){
            percent2 = percent1;
            char  printbuf[200]; 
            sprintf(printbuf,"dataflash write percent %d%%",percent2);
            statBarPrint(0, printbuf);
         }
         if (FALSE==ret) {
            statBarPrint(1, "data flash write  error");
            delay(1000);
            goto ERROR;
         }
         delay(45);
         spiFlashRead(256*i,checkbuf,256);
         if(memcmp(checkbuf,(void *)(buf + 512+256*i),256)!=0){
           statBarPrint(1, "data flash write check error");
           delay(500);
           goto ERROR;
         }
      } 
   } 
   f_close(&file);
   return TRUE;
ERROR:
   f_close(&file);
   return FALSE;
}
示例#13
0
/**
  * @brief  IAP Read all flash memory.
  * @param  None
  * @retval None
  */
void COMMAND_Upload(void)
{
  __IO uint32_t address = APPLICATION_ADDRESS;
  __IO uint32_t counterread = 0x00;
  uint32_t tmpcounter = 0x00, indexoffset = 0x00;
  FlagStatus readoutstatus = SET;
  uint16_t byteswritten;

  /* Get the read out protection status */
  readoutstatus = FLASH_If_ReadOutProtectionStatus();
  if(readoutstatus == RESET)
  {
    /* Remove UPLOAD file if it exists on flash disk */
    f_unlink(UPLOAD_FILENAME);

    /* Init written byte counter */
    indexoffset = (APPLICATION_ADDRESS - USER_FLASH_STARTADDRESS);

    /* Open binary file to write on it */
    if(( Appli_state == APPLICATION_READY) && (f_open(&MyFile, UPLOAD_FILENAME, FA_CREATE_ALWAYS | FA_WRITE) == FR_OK))
    {
      /* Upload On Going: Turn LED4 On and LED3 Off */
      BSP_LED_On(LED4);
      BSP_LED_Off(LED3);

      /* Read flash memory */
      while ((indexoffset < USER_FLASH_SIZE) && ( Appli_state == APPLICATION_READY))
      {
        for(counterread = 0; counterread < BUFFER_SIZE; counterread++)
        {
          /* Check the read bytes versus the end of flash */
          if(indexoffset + counterread < USER_FLASH_SIZE)
          {
            tmpcounter = counterread;
            RAM_Buf[tmpcounter] = (*(uint8_t*)(address++));
          }
          /* In this case all flash was read */
          else
          {
            break;
          }
        }

        /* Write buffer to file */
        f_write (&MyFile, RAM_Buf, BUFFER_SIZE, (void *)&byteswritten);

        /* Number of byte written  */
        indexoffset = indexoffset + counterread;
      }

      /* Turn LED1 On: Upload Done */
      BSP_LED_Off(LED4);
      BSP_LED_Off(LED2);
      BSP_LED_On(LED1);

      /* Close file and filesystem */
      f_close(&MyFile);
      f_mount(0, 0, 0);
    }
    /* Keep These LEDS OFF when Device connected */
    BSP_LED_Off(LED2);
    BSP_LED_Off(LED3);
  }
  else
  {
    /* Message ROP active: Turn LED2 On and Toggle LED3 in infinite loop */
    BSP_LED_On(LED2);
    Fail_Handler();
  }
}