Beispiel #1
0
void ScreenShot(){
	unsigned char bmpHeader[] = {
		0x42, 0x4D, 0x36, 0x65, 0x04, 0x00, 0x00, 0x00,
		0x00, 0x00, 0x36, 0x00, 0x00, 0x00, 0x28, 0x00,
		0x00, 0x00, 0x90, 0x01, 0x00, 0x00, 0xF0, 0x00,
		0x00, 0x00, 0x01, 0x00, 0x18, 0x00, 0x00, 0x00,
		0x00, 0x00, 0x00, 0x65, 0x04, 0x00, 0x00, 0x00,
		0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
		0x00, 0x00, 0x00, 0x00, 0x00, 0x00
		};

	File myFile;
	wchar_t tmp[_MAX_LFN];
	static int top_count = 0;
	static int bot_count = 0;
	unsigned int written = 0;
	char* bmp_cache; char* bmp_ptr;
	uint8_t (*screen_ptr) [SCREEN_HEIGHT][BYTES_PER_PIXEL];

	f_mkdir (L"Screenshot");

	do{
		swprintf(tmp, _MAX_LFN, L"/Screenshot/top_screen_%d.bmp", top_count++);
		if(f_open(&myFile, tmp, FA_READ | FA_OPEN_EXISTING) != FR_OK) break;
		f_close(&myFile);
	}while(1);

	if(f_open(&myFile, tmp, FA_WRITE | FA_CREATE_ALWAYS) == FR_OK){
		unsigned int bmp_size = TOP_SCREEN_WIDTH*SCREEN_HEIGHT*3;
		bmp_cache = (char*)malloc(bmp_size + 0x36);
		bmp_ptr = bmp_cache;
		*(unsigned int*)(bmpHeader+0x02) = bmp_size + 0x36;
		*(unsigned int*)(bmpHeader+0x12) = TOP_SCREEN_WIDTH;
		*(unsigned int*)(bmpHeader+0x16) = SCREEN_HEIGHT;
		*(unsigned int*)(bmpHeader+0x22) = bmp_size;
		f_write(&myFile, bmpHeader, 0x36, &written);
		screen_ptr = (void*)TOP_SCREEN;
		for(int y = 0; y < SCREEN_HEIGHT; y++){
			for(int x = 0; x < TOP_SCREEN_WIDTH; x++){
				memcpy(bmp_ptr, screen_ptr[x][y], 3);
				bmp_ptr += 3;
			}
		}
		f_write(&myFile, bmp_cache, bmp_size + 0x36, &written);
		free(bmp_cache);
		f_close(&myFile);
	}

	do{
		swprintf(tmp, _MAX_LFN, L"/Screenshot/bot_screen_%d.bmp", bot_count++);
		if(f_open(&myFile, tmp, FA_READ | FA_OPEN_EXISTING) != FR_OK) break;
		f_close(&myFile);
	}while(1);

	if(f_open(&myFile, tmp, FA_WRITE | FA_CREATE_ALWAYS) == FR_OK){
		unsigned int bmp_size = BOT_SCREEN_WIDTH*SCREEN_HEIGHT*3;
		bmp_cache = (char*)malloc(bmp_size + 0x36);
		bmp_ptr = bmp_cache;
		*(unsigned int*)(bmpHeader+0x02) = bmp_size + 0x36;
		*(unsigned int*)(bmpHeader+0x12) = BOT_SCREEN_WIDTH;
		*(unsigned int*)(bmpHeader+0x16) = SCREEN_HEIGHT;
		*(unsigned int*)(bmpHeader+0x22) = bmp_size;
		f_write(&myFile, bmpHeader, 0x36, &written);
		screen_ptr = (void*)BOT_SCREEN;
		for(int y = 0; y < SCREEN_HEIGHT; y++){
			for(int x = 0; x < BOT_SCREEN_WIDTH; x++){
				memcpy(bmp_ptr, screen_ptr[x][y], 3);
				bmp_ptr += 3;
			}
		}
		f_write(&myFile, bmp_cache, bmp_size + 0x36, &written);
		free(bmp_cache);
		f_close(&myFile);
	}

}
Beispiel #2
0
/*
 *  ======== taskFxn ========
 *  Task to perform a file copy
 *
 *  Task tries to open an existing file inputfile[]. If the file doesn't
 *  exist, create one and write some known content into it.
 *  The contents of the inputfile[] are then copied to an output file
 *  outputfile[]. Once completed, the contents of the output file are
 *  printed onto the system console (stdout).
 *
 *  Task for this function is created statically. See the project's .cfg file.
 */
Void taskFxn(UArg arg0, UArg arg1)
{
    FRESULT fresult;
    SDSPI_Handle sdspiHandle;
    SDSPI_Params sdspiParams;

    /* Variables for the CIO functions */
    FIL src, dst;

    /* Variables to keep track of the file copy progress */
    UInt bytesRead = 0;
    UInt bytesWritten = 0;
    UInt filesize;
    UInt totalBytesCopied = 0;

    /* Mount and register the SD Card */
    SDSPI_Params_init(&sdspiParams);
    sdspiHandle = SDSPI_open(Board_SDSPI, DRIVE_NUM, &sdspiParams);
    if (sdspiHandle == NULL) {
        System_abort("Error starting the SD card\n");
    }
    else {
        System_printf("Drive %u is mounted\n", DRIVE_NUM);
    }

    /* Try to open the source file */
    fresult = f_open(&src, inputfile, FA_READ);
    if (fresult != FR_OK) {
        System_printf("Creating a new file \"%s\"...", inputfile);

        /* Open file for both reading and writing */
        fresult = f_open(&src, inputfile, FA_CREATE_NEW|FA_READ|FA_WRITE);
        if (fresult != FR_OK) {
            System_printf("Error: \"%s\" could not be created\n",
                    inputfile);
            System_abort("Aborting...\n");
        }

        f_write(&src, textarray, strlen(textarray), &bytesWritten);
        f_sync(&src);

        /* Reset the internal file pointer */
        f_lseek(&src, 0);

        System_printf("done\n");
    }
    else {
        System_printf("Using existing copy of \"%s\"\n", inputfile);
    }

    /* Create a new file object for the file copy */
    fresult = f_open(&dst, outputfile, FA_CREATE_ALWAYS|FA_WRITE);
    if (fresult != FR_OK) {
        System_printf("Error opening \"%s\"\n", outputfile);
        System_abort("Aborting...\n");
    }
    else {
        System_printf("Starting file copy\n");
    }

    /*  Copy the contents from the src to the dst */
    while (TRUE) {
        /*  Read from source file */
        fresult = f_read(&src, cpy_buff, CPY_BUFF_SIZE, &bytesRead);
        if (fresult || bytesRead == 0) {
            break; /* Error or EOF */
        }

        /*  Write to dst file */
        fresult = f_write(&dst, cpy_buff, bytesRead, &bytesWritten);
        if (fresult || bytesWritten < bytesRead) {
            System_printf("Disk Full\n");
            break; /* Error or Disk Full */
        }

        /*  Update the total number of bytes copied */
        totalBytesCopied += bytesWritten;
    }

    f_sync(&dst);

    /* Get the filesize of the source file */
    filesize = f_size(&src);

    /* Close both inputfile[] and outputfile[] */
    f_close(&src);
    f_close(&dst);

    System_printf("File \"%s\" (%u B) copied to \"%s\" (Wrote %u B)\n",
                  inputfile, filesize, outputfile, totalBytesCopied);

    /* Now output the outputfile[] contents onto the console */
    fresult = f_open(&dst, outputfile, FA_READ);
    if (fresult != FR_OK) {
        System_printf("Error opening \"%s\"\n", outputfile);
        System_abort("Aborting...\n");
    }

    /* Print file contents */
    while (TRUE) {
        /* Read from output file */
        fresult = f_read(&dst, cpy_buff, CPY_BUFF_SIZE, &bytesRead);
        if (fresult || bytesRead == 0) {
            break; /* Error or EOF */
        }
        /* Write output */
        System_printf("%s", cpy_buff);
    }

    /* Close the file */
    f_close(&dst);

    /* Stopping the SDCard */
    SDSPI_close(sdspiHandle);
    System_printf("Drive %u unmounted\n", DRIVE_NUM);

    BIOS_exit(0);
}
Beispiel #3
0
/*JSON{ "type":"staticmethod",
        "class" : "E",
        "name" : "openFile",
        "generate" : "jswrap_E_openFile",
        "description" : [ "Open a file" ],
        "params" : [ [ "path", "JsVar", "the path to the file to open." ],
                      [ "mode", "JsVar", "The mode to use when opening the file. Valid values for mode are 'r' for read, 'w' for write new, 'w+' for write existing, and 'a' for append. If not specified, the default is 'r'."] ],
        "return" : ["JsVar", "A File object"]
}*/
JsVar *jswrap_E_openFile(JsVar* path, JsVar* mode) {
  FRESULT res = FR_INVALID_NAME;
  JsFile file;
  file.fileVar = 0;
  FileMode fMode = FM_NONE;
  if (jsfsInit()) {
    JsVar *arr = fsGetArray(JS_FS_OPEN_FILES_NAME, true);
    if (!arr) return 0; // out of memory

    char pathStr[JS_DIR_BUF_SIZE] = "";
    char modeStr[3] = "r";
    if (!jsvIsUndefined(path)) {
      jsvGetString(path, pathStr, JS_DIR_BUF_SIZE);
      if (!jsvIsUndefined(mode))
        jsvGetString(mode, modeStr, 3);

#ifndef LINUX
      BYTE ff_mode = 0;
      bool append = false;
#endif

      if(strcmp(modeStr,"r") == 0) {
        fMode = FM_READ;
#ifndef LINUX
        ff_mode = FA_READ | FA_OPEN_EXISTING;
#endif
      } else if(strcmp(modeStr,"a") == 0) {
        fMode = FM_WRITE;
#ifndef LINUX
        ff_mode = FA_WRITE | FA_OPEN_ALWAYS;
        append = true;
#endif
      } else if(strcmp(modeStr,"w") == 0) {
        fMode = FM_WRITE;
#ifndef LINUX
        ff_mode = FA_WRITE | FA_CREATE_ALWAYS;
#endif
      } else if(strcmp(modeStr,"w+") == 0) {
        fMode = FM_READ_WRITE;
#ifndef LINUX
        ff_mode = FA_WRITE | FA_OPEN_ALWAYS;
#endif
      }
      if(fMode != FM_NONE && allocateJsFile(&file, fMode, FT_FILE)) {
#ifndef LINUX
        if ((res=f_open(&file.data.handle, pathStr, ff_mode)) == FR_OK) {
          if (append) f_lseek(&file.data.handle, file.data.handle.fsize); // move to end of file
#else
        file.data.handle = fopen(pathStr, modeStr);
        if (file.data.handle) {
          res=FR_OK;
#endif
          file.data.state = FS_OPEN;
          fileSetVar(&file);
          // add to list of open files
          jsvArrayPush(arr, file.fileVar);
          jsvUnLock(arr);
        } else {
          // File open failed
          jsvUnLock(file.fileVar);
          file.fileVar = 0;
        }

        if(res != FR_OK)
          jsfsReportError("Could not open file", res);

      }
    } else {
      jsError("Path is undefined");
    }
  }


  return file.fileVar;
}

/*JSON{  "type" : "method", "class" : "File", "name" : "close",
         "generate_full" : "jswrap_file_close(parent)",
         "description" : [ "Close an open file."]
}*/
void jswrap_file_close(JsVar* parent) {
  if (jsfsInit()) {
    JsFile file;
    if (fileGetFromVar(&file, parent) && file.data.state == FS_OPEN) {
#ifndef LINUX
      f_close(&file.data.handle);
#else
      fclose(file.data.handle);
      file.data.handle = 0;
#endif
      file.data.state = FS_CLOSED;
      fileSetVar(&file);
      // TODO: could try and free the memory used by file.data ?

      JsVar *arr = fsGetArray(JS_FS_OPEN_FILES_NAME, false);
      if (arr) {
        JsVar *idx = jsvGetArrayIndexOf(arr, file.fileVar, true);
        if (idx) {
          jsvRemoveChild(arr, idx);
          jsvUnLock(idx);
        }
        jsvUnLock(arr);
      }
    }
  }
}

/*JSON{  "type" : "method", "class" : "File", "name" : "write",
         "generate" : "jswrap_file_write",
         "description" : [ "write data to a file"],
         "params" : [ ["buffer", "JsVar", "A string containing the bytes to write"] ],
         "return" : [ "int32", "the number of bytes written" ]
}*/
size_t jswrap_file_write(JsVar* parent, JsVar* buffer) {
  FRESULT res = 0;
  size_t bytesWritten = 0;
  if (jsfsInit()) {
    JsFile file;
    if (fileGetFromVar(&file, parent)) {
      if(file.data.mode == FM_WRITE || file.data.mode == FM_READ_WRITE) {
        JsvIterator it;
        jsvIteratorNew(&it, buffer);
        char buf[32];

        while (jsvIteratorHasElement(&it)) {
          // pull in a buffer's worth of data
          size_t n = 0;
          while (jsvIteratorHasElement(&it) && n<sizeof(buf)) {
            buf[n++] = (char)jsvIteratorGetIntegerValue(&it);
            jsvIteratorNext(&it);
          }
          // write it out
          size_t written = 0;
#ifndef LINUX
          res = f_write(&file.data.handle, &buf, n, &written);
#else
          written = fwrite(&buf, 1, n, file.data.handle);
#endif
          bytesWritten += written;
          if(written == 0)
            res = FR_DISK_ERR;
          if (res) break;
        }
        jsvIteratorFree(&it);
        // finally, sync - just in case there's a reset or something
#ifndef LINUX
        f_sync(&file.data.handle);
#else
        fflush(file.data.handle);
#endif
      }

      fileSetVar(&file);
    }
  }

  if (res) {
    jsfsReportError("Unable to write file", res);
  }
  return bytesWritten;
}
Beispiel #4
0
/**
* @brief  USBH_USR_MSC_Application 
*         Demo application for mass storage
* @param  None
* @retval Staus
*/
int USBH_USR_MSC_Application(void)
{
  FRESULT res;
  uint8_t writeTextBuff[] = "BIG_MANTA FS/HS STM32 Connectivity line Host Demo application using FAT_FS   ";
  uint16_t bytesWritten, bytesToWrite;
  
  /* Set LCD Layer size and pixel format */
  LTDC_LayerPixelFormat(LTDC_Layer2, LTDC_Pixelformat_RGB565); 
  LTDC_LayerSize(LTDC_Layer2, 240, 320);
  /* LTDC reload configuration */  
  LTDC_ReloadConfig(LTDC_IMReload);
  
  switch(USBH_USR_ApplicationState)
  {
  case USH_USR_FS_INIT: 
    
    /* Initialises the File System*/
    if ( f_mount( 0, &fatfs ) != FR_OK ) 
    {
      /* efs initialisation fails*/
      LCD_ErrLog("> Cannot initialize File System.\n");
      return(-1);
    }
    LCD_UsrLog("> File System initialized.\n");
    LCD_UsrLog("> Disk capacity : %d Bytes\n", USBH_MSC_Param.MSCapacity * \
      USBH_MSC_Param.MSPageLength); 
    
    if(USBH_MSC_Param.MSWriteProtect == DISK_WRITE_PROTECTED)
    {
      LCD_ErrLog((void *)MSG_WR_PROTECT);
    }
    
    USBH_USR_ApplicationState = USH_USR_FS_READLIST;
    break;
    
  case USH_USR_FS_READLIST:
    
    LCD_UsrLog((void *)MSG_ROOT_CONT);
    Explore_Disk("0:/", 1);
    line_idx = 0;   
    USBH_USR_ApplicationState = USH_USR_FS_WRITEFILE;
    
    break;
    
  case USH_USR_FS_WRITEFILE:
    
    /*Key B3 in polling*/
    while((HCD_IsDeviceConnected(&USB_OTG_Core)) && \
      (STM_EVAL_PBGetState (BUTTON_USER) != RESET))          
    {
      Toggle_Leds();
    }
    /* Writes a text file, STM32.TXT in the disk*/
    LCD_UsrLog("> Writing File to disk flash ...\n");
    if(USBH_MSC_Param.MSWriteProtect == DISK_WRITE_PROTECTED)
    {
      
      LCD_ErrLog ( "> Disk flash is write protected \n");
      USBH_USR_ApplicationState = USH_USR_FS_DRAW;
      break;
    }
    
    /* Register work area for logical drives */
    f_mount(0, &fatfs);
    
    if(f_open(&file, "0:STM32.TXT",FA_CREATE_ALWAYS | FA_WRITE) == FR_OK)
    { 
      /* Write buffer to file */
      bytesToWrite = sizeof(writeTextBuff); 
      res= f_write (&file, writeTextBuff, bytesToWrite, (void *)&bytesWritten);   
      
      if((bytesWritten == 0) || (res != FR_OK)) /*EOF or Error*/
      {
        LCD_ErrLog("> STM32.TXT CANNOT be writen.\n");
      }
      else
      {
        LCD_UsrLog("> 'STM32.TXT' file created\n");
      }
      
      /*close file and filesystem*/
      f_close(&file);
      f_mount(0, NULL); 
    }
    
    else
    {
      LCD_UsrLog ("> STM32.TXT created in the disk\n");
    }

    USBH_USR_ApplicationState = USH_USR_FS_PDFCREATE; 
    
    LCD_SetTextColor(Green);
    LCD_DisplayStringLine(LCD_LINE_15,"To start PDF file Create            ");
    LCD_DisplayStringLine(LCD_LINE_16,"Press Key                           "); 
    LCD_SetTextColor(LCD_LOG_DEFAULT_COLOR); 
    while(STM_EVAL_PBGetState (BUTTON_USER) != SET)
      {
        Toggle_Leds();
      }
    break;
    
  case USH_USR_FS_DRAW:
    
    /*Key B3 in polling*/
    while((HCD_IsDeviceConnected(&USB_OTG_Core)) && \
      (STM_EVAL_PBGetState (BUTTON_USER) != RESET))
    {
      Toggle_Leds();
    }
  
    while(HCD_IsDeviceConnected(&USB_OTG_Core))
    {
      if ( f_mount( 0, &fatfs ) != FR_OK ) 
      {
        /* fat_fs initialisation fails*/
        return(-1);
      }
      return Image_Browser("0:/");
    }
    break;
	case USH_USR_FS_PDFCREATE:
		PdfCreate();
		return(1);
//		break;
		
  default: break;
  }
  return(0);
}
static portBASE_TYPE prvPerformCopy( 	char *pcSourceFile,
										int32_t lSourceFileLength,
										char *pcDestinationFile,
										char *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( 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( pcDestinationFile, "a" );
		if( pxFile != NULL )
		{
			f_write( pxWriteBuffer, lBytesToRead, 1, pxFile );
			f_close( pxFile );
		}
		else
		{
			xReturn = pdFAIL;
			break;
		}

		lBytesRead += lBytesToRead;
	}

	return xReturn;
}
Beispiel #6
0
//*****************************************************************************
//
// This is called each time there is a new data record to log to the storage
// device.  A line of text in CSV format will be written to the file.
//
//*****************************************************************************
int32_t
USBStickWriteRecord(tLogRecord *psRecord)
{
    static char pcBuf[256];
    uint32_t ui32Idx, ui32BufIdx = 0, ui32RecordIdx, ui32Selected;
    FRESULT iFResult;
    uint32_t ui32BytesWritten;

    //
    // Check the arguments
    //
    ASSERT(psRecord);
    if(!psRecord)
    {
        return(1);
    }

    //
    // Check state for ready device and opened file
    //
    if((g_iState != eSTATE_DEVICE_READY) || !(g_ui32Flags & FLAGS_FILE_OPENED))
    {
        return(1);
    }

    //
    // Print time stamp columns
    //
    ui32BufIdx += usnprintf(&pcBuf[ui32BufIdx], sizeof(pcBuf) - ui32BufIdx,
                            "%u,%u", psRecord->ui32Seconds,
                            psRecord->ui16Subseconds);

    //
    // Iterate through selected data items and print to CSV buffer
    //
    ui32RecordIdx = 0;
    ui32Selected = psRecord->ui16ItemMask;
    for(ui32Idx = 0; ui32Idx < NUM_LOG_ITEMS; ui32Idx++)
    {
        //
        // If this data item is selected, then print a value to the CSV buffer
        //
        if(ui32Selected & 1)
        {
            ui32BufIdx += usnprintf(&pcBuf[ui32BufIdx],
                                    (sizeof(pcBuf) - ui32BufIdx), ",%d",
                                    psRecord->pi16Items[ui32RecordIdx]);
            ui32RecordIdx++;
        }
        else
        {
            //
            // Otherwise, this column of data is not selected so emit just a
            // comma
            //
            ui32BufIdx += usnprintf(&pcBuf[ui32BufIdx],
                                    (sizeof(pcBuf) - ui32BufIdx), ",");
        }

        //
        // Next selected item ...
        //
        ui32Selected >>= 1;
    }

    //
    // Append a CRLF to the end
    //
    ui32BufIdx += usnprintf(&pcBuf[ui32BufIdx], (sizeof(pcBuf) - ui32BufIdx),
                            "\r\n");

    //
    // Now write the entire buffer to the USB stick file
    //
    iFResult = f_write(&g_sFileObject, pcBuf, ui32BufIdx, &ui32BytesWritten);

    //
    // Check for errors
    //
    if((iFResult != FR_OK) || (ui32BytesWritten != ui32BufIdx))
    {
        //
        // Some error occurred
        //
        g_ui32Flags &= ~FLAGS_FILE_OPENED;
        return(1);
    }
    else
    {
        //
        // No errors occurred, return success
        //
        return(0);
    }
}
Beispiel #7
0
JsVar *wrap_fat_readdir(JsVar *path) {
  JsVar *arr = jsvNewWithFlags(JSV_ARRAY);
  if (!arr) return 0; // out of memory

  char pathStr[JS_DIR_BUF_SIZE] = "";
  if (!jsvIsUndefined(path))
    jsvGetString(path, pathStr, JS_DIR_BUF_SIZE);
#ifdef LINUX
  if (!pathStr[0]) strcpy(pathStr, "."); // deal with empty readdir
#endif

  FRESULT res = 0;
  if (jsfsInit()) {
#ifndef LINUX
    DIR dirs;
    if ((res=f_opendir(&dirs, pathStr)) == FR_OK) {
      FILINFO Finfo;
      while (((res=f_readdir(&dirs, &Finfo)) == FR_OK) && Finfo.fname[0]) {
        char *fn = GET_FILENAME(Finfo);
#else
    DIR *dir = opendir(pathStr);
    if(dir) {
      struct dirent *pDir=NULL;
      while((pDir = readdir(dir)) != NULL) {
        char *fn = (*pDir).d_name;
#endif
        JsVar *fnVar = jsvNewFromString(fn);
        if (fnVar) // out of memory?
          jsvArrayPush(arr, fnVar);
      }
#ifdef LINUX
      closedir(dir);
#endif
    }
  }
  if (res) jsfsReportError("Unable to list files", res);
  return arr;
}

/*JSON{  "type" : "staticmethod", "class" : "fs", "name" : "writeFile",
         "generate" : "wrap_fat_writeFile",
         "description" : [ "Write the data to the given file", "NOTE: Espruino does not yet support Async file IO, so this function behaves like the 'Sync' version." ],
         "params" : [ [ "path", "JsVar", "The path of the file to write" ],
                      [ "data", "JsVar", "The data to write to the file" ] ]
}*/
/*JSON{  "type" : "staticmethod", "class" : "fs", "name" : "writeFileSync", "ifndef" : "SAVE_ON_FLASH",
         "generate" : "wrap_fat_writeFile",
         "description" : [ "Write the data to the given file" ],
         "params" : [ [ "path", "JsVar", "The path of the file to write" ],
                      [ "data", "JsVar", "The data to write to the file" ] ]
}*/
/*JSON{  "type" : "staticmethod", "class" : "fs", "name" : "appendFile",
         "generate" : "wrap_fat_appendFile",
         "description" : [ "Append the data to the given file, created a new file if it doesn't exist", "NOTE: Espruino does not yet support Async file IO, so this function behaves like the 'Sync' version." ],
         "params" : [ [ "path", "JsVar", "The path of the file to write" ],
                      [ "data", "JsVar", "The data to write to the file" ] ]
}*/
/*JSON{  "type" : "staticmethod", "class" : "fs", "name" : "appendFileSync", "ifndef" : "SAVE_ON_FLASH",
         "generate" : "wrap_fat_appendFile",
         "description" : [ "Append the data to the given file, created a new file if it doesn't exist" ],
         "params" : [ [ "path", "JsVar", "The path of the file to write" ],
                      [ "data", "JsVar", "The data to write to the file" ] ]
}*/
void wrap_fat_writeOrAppendFile(JsVar *path, JsVar *data, bool append) {
  char pathStr[JS_DIR_BUF_SIZE] = "";
  if (!jsvIsUndefined(path))
    jsvGetString(path, pathStr, JS_DIR_BUF_SIZE);

  FRESULT res = 0;
  if (jsfsInit()) {
#ifndef LINUX
    FIL file;

    if ((res=f_open(&file, pathStr, FA_WRITE|(append ? FA_OPEN_ALWAYS : FA_CREATE_ALWAYS))) == FR_OK) {

      if (append) {
        // move to end of file to append data
        f_lseek(&file, file.fsize);
//        if (res != FR_OK) jsfsReportError("Unable to move to end of file", res);
      }
#else
      FILE *file = fopen(pathStr, append?"a":"w");
      if (file) {
#endif

      JsvStringIterator it;
      JsVar *dataString = jsvAsString(data, false);
      jsvStringIteratorNew(&it, dataString, 0);
      size_t toWrite = 0;
      size_t written = 0;

      while (jsvStringIteratorHasChar(&it) && res==FR_OK && written==toWrite) {

        // re-use pathStr buffer
        toWrite = 0;
        while (jsvStringIteratorHasChar(&it) && toWrite < JS_DIR_BUF_SIZE) {
          pathStr[toWrite++] = jsvStringIteratorGetChar(&it);
          jsvStringIteratorNext(&it);
        }
#ifndef LINUX
        res = f_write(&file, pathStr, toWrite, &written);
#else
        written = fwrite(pathStr, 1, toWrite, file);
#endif
      }
      jsvStringIteratorFree(&it);
      jsvUnLock(dataString);
#ifndef LINUX
      f_close(&file);
#else
      fclose(file);
#endif
    }
  }
  if (res) jsfsReportError("Unable to write file", res);
}
void wrap_fat_writeFile(JsVar *path, JsVar *data) {
  wrap_fat_writeOrAppendFile(path, data, false);
}
void wrap_fat_appendFile(JsVar *path, JsVar *data) {
  wrap_fat_writeOrAppendFile(path, data, true);
}
Beispiel #8
0
int main(int oargc, char* oargv[])
{
    int ret;
    int    argc = oargc - 1;
    char** argv = oargv + 1;

    // first parameter must be the image file.
    if (argc == 0)
    {
        fprintf(stderr, "Error: First parameter must be a filename.\n");
        PRINT_HELP_AND_QUIT();
    }

    if (is_command(argv[0]))
    {
        fprintf(stderr, "Error: First parameter must be a filename, found '%s' instead.\n", argv[0]);
        PRINT_HELP_AND_QUIT();
    }

    if (disk_openimage(0, argv[0]))
    {
        fprintf(stderr, "Error: Could not open image file '%s'.\n", argv[0]);
        ret = 1;
        goto exit;
    }

    argc--;
    argv++;

    while (argc > 0)
    {
        char* parg = *argv;
        int nargs = 0;
        int i = 0;

        if (!is_command(parg))
        {
            fprintf(stderr, "Error: Expected a command, found '%s' instead.\n", parg);
            PRINT_HELP_AND_QUIT();
        }

        parg++;
        argv++;
        argc--;

        // find next command, to calculare number of args
        while ((argv[i] != NULL) && !is_command(argv[i++]))
            nargs++;

        if (strcmp(parg, "format") == 0)
        {
            // NOTE: The fs driver detects which FAT format fits best based on size
            int sectors;

            NEED_PARAMS(1, 2);

            // Arg 1: number of sectors
            sectors = atoi(argv[0]);

            if (sectors <= 0)
            {
                fprintf(stderr, "Error: Sectors must be > 0\n");
                ret = 1;
                goto exit;
            }

            if (disk_ioctl(0, SET_SECTOR_COUNT, &sectors))
            {
                fprintf(stderr, "Error: Failed to set sector count to %d.\n", sectors);
                ret = 1;
                goto exit;
            }

            NEED_MOUNT();

            ret = f_mkfs("0:", 1, sectors < 4096 ? 1 : 8);
            if (ret)
            {
                fprintf(stderr, "Error: Formatting drive: %d.\n", ret);
                goto exit;
            }

            // Arg 2: custom header label (optional)
            if (nargs > 1)
            {
#define FAT_VOL_LABEL_LEN   11
                char vol_label[2 + FAT_VOL_LABEL_LEN + 1]; // Null-terminated buffer
                char* label = vol_label + 2; // The first two characters are reserved for the drive number "0:"
                char ch;

                int i, invalid = 0;
                int len = strlen(argv[1]);

                if (len <= FAT_VOL_LABEL_LEN)
                {
                    // Verify each character (should be printable ASCII)
                    // and copy it in uppercase.
                    for (i = 0; i < len; i++)
                    {
                        ch = toupper(argv[1][i]);
                        if ((ch < 0x20) || !isprint(ch))
                        {
                            invalid = 1;
                            break;
                        }

                        label[i] = ch;
                    }
                
                    if (!invalid)
                    {
                        // Pad the label with spaces
                        while (len < FAT_VOL_LABEL_LEN)
                        {
                            label[len++] = ' ';
                        }
                    }
                }
                else
                {
                    invalid = 1;
                }

                if (invalid)
                {
                    fprintf(stderr, "Error: Header label is limited to 11 printable uppercase ASCII symbols.");
                    ret = 1;
                    goto exit;
                }

                if (disk_read(0, buff, 0, 1))
                {
                    fprintf(stderr, "Error: Unable to read existing boot sector from image.");
                    ret = 1;
                    goto exit;
                }

                if (g_Filesystem.fs_type == FS_FAT32)
                {
                    memcpy(buff + 71, label, FAT_VOL_LABEL_LEN);
                }
                else
                {
                    memcpy(buff + 43, label, FAT_VOL_LABEL_LEN);
                }

                if (disk_write(0, buff, 0, 1))
                {
                    fprintf(stderr, "Error: Unable to write new boot sector to image.");
                    ret = 1;
                    goto exit;
                }

                // Set also the directory volume label
                memcpy(vol_label, "0:", 2);
                vol_label[2 + FAT_VOL_LABEL_LEN] = '\0';
                if (f_setlabel(vol_label))
                {
                    fprintf(stderr, "Error: Unable to set the volume label.");
                    ret = 1;
                    goto exit;
                }
            }
        }
        else if (strcmp(parg, "boot") == 0)
        {
            FILE* fe;
            BYTE* temp = buff + 1024;

            NEED_PARAMS(1, 1);

            // Arg 1: boot file

            fe = fopen(argv[0], "rb");
            if (!fe)
            {
                fprintf(stderr, "Error: Unable to open external file '%s' for reading.", argv[0]);
                ret = 1;
                goto exit;
            }

            if (!fread(buff, 512, 1, fe))
            {
                fprintf(stderr, "Error: Unable to read boot sector from file '%s'.", argv[0]);
                fclose(fe);
                ret = 1;
                goto exit;
            }

            fclose(fe);

            NEED_MOUNT();

            if (disk_read(0, temp, 0, 1))
            {
                fprintf(stderr, "Error: Unable to read existing boot sector from image.");
                ret = 1;
                goto exit;
            }

            if (g_Filesystem.fs_type == FS_FAT32)
            {
                printf("TODO: Writing boot sectors for FAT32 images not yet supported.");
                ret = 1;
                goto exit;
            }
            else
            {
#define FAT16_HEADER_START 3
#define FAT16_HEADER_END 62

                memcpy(buff + FAT16_HEADER_START, temp + FAT16_HEADER_START, FAT16_HEADER_END - FAT16_HEADER_START);
            }

            if (disk_write(0, buff, 0, 1))
            {
                fprintf(stderr, "Error: Unable to write new boot sector to image.");
                ret = 1;
                goto exit;
            }
        }
        else if (strcmp(parg, "add") == 0)
        {
            FILE* fe;
            FIL   fv = { 0 };
            UINT rdlen = 0;
            UINT wrlen = 0;

            NEED_PARAMS(2, 2);

            NEED_MOUNT();

            // Arg 1: external file to add
            // Arg 2: virtual filename

            fe = fopen(argv[0], "rb");
            if (!fe)
            {
                fprintf(stderr, "Error: Unable to open external file '%s' for reading.", argv[0]);
                ret = 1;
                goto exit;
            }

            if (f_open(&fv, argv[1], FA_WRITE | FA_CREATE_ALWAYS))
            {
                fprintf(stderr, "Error: Unable to open file '%s' for writing.", argv[1]);
                fclose(fe);
                ret = 1;
                goto exit;
            }

            while ((rdlen = fread(buff, 1, sizeof(buff), fe)) > 0)
            {
                if (f_write(&fv, buff, rdlen, &wrlen) || wrlen < rdlen)
                {
                    fprintf(stderr, "Error: Unable to write '%d' bytes to disk.", wrlen);
                    ret = 1;
                    goto exit;
                }
            }

            fclose(fe);
            f_close(&fv);
        }
        else if (strcmp(parg, "extract") == 0)
        {
            FIL   fe = { 0 };
            FILE* fv;
            UINT rdlen = 0;
            UINT wrlen = 0;

            NEED_PARAMS(2, 2);

            NEED_MOUNT();

            // Arg 1: virtual file to extract
            // Arg 2: external filename

            if (f_open(&fe, argv[0], FA_READ))
            {
                fprintf(stderr, "Error: Unable to open file '%s' for reading.", argv[0]);
                ret = 1;
                goto exit;
            }

            fv = fopen(argv[1], "wb");
            if (!fv)
            {
                fprintf(stderr, "Error: Unable to open external file '%s' for writing.", argv[1]);
                f_close(&fe);
                ret = 1;
                goto exit;
            }

            while ((f_read(&fe, buff, sizeof(buff), &rdlen) == 0) && (rdlen > 0))
            {
                if (fwrite(buff, 1, rdlen, fv) < rdlen)
                {
                    fprintf(stderr, "Error: Unable to write '%d' bytes to file.", rdlen);
                    ret = 1;
                    goto exit;
                }
            }

            f_close(&fe);
            fclose(fv);
        }
        else if (strcmp(parg, "move") == 0)
        {
            NEED_PARAMS(2, 2);

            NEED_MOUNT();
            // Arg 1: src path & filename
            // Arg 2: new path & filename

            if (f_rename(argv[0], argv[1]))
            {
                fprintf(stderr, "Error: Unable to move/rename '%s' to '%s'", argv[0], argv[1]);
                ret = 1;
                goto exit;
            }
        }
        else if (strcmp(parg, "copy") == 0)
        {
            FIL fe = { 0 };
            FIL fv = { 0 };
            UINT rdlen = 0;
            UINT wrlen = 0;

            NEED_PARAMS(2, 2);

            NEED_MOUNT();
            // Arg 1: src path & filename
            // Arg 2: new path & filename

            if (f_open(&fe, argv[0], FA_READ))
            {
                fprintf(stderr, "Error: Unable to open file '%s' for reading.", argv[0]);
                ret = 1;
                goto exit;
            }
            if (f_open(&fv, argv[1], FA_WRITE | FA_CREATE_ALWAYS))
            {
                fprintf(stderr, "Error: Unable to open file '%s' for writing.", argv[1]);
                f_close(&fe);
                ret = 1;
                goto exit;
            }

            while ((f_read(&fe, buff, sizeof(buff), &rdlen) == 0) && (rdlen > 0))
            {
                if (f_write(&fv, buff, rdlen, &wrlen) || wrlen < rdlen)
                {
                    fprintf(stderr, "Error: Unable to write '%d' bytes to disk.", wrlen);
                    ret = 1;
                    goto exit;
                }
            }

            f_close(&fe);
            f_close(&fv);
        }
        else if (strcmp(parg, "mkdir") == 0)
        {
            NEED_PARAMS(1, 1);

            NEED_MOUNT();

            // Arg 1: folder path
            if (f_mkdir(argv[0]))
            {
                fprintf(stderr, "Error: Unable to create directory.");
                ret = 1;
                goto exit;
            }
        }
        else if (strcmp(parg, "delete") == 0)
        {
            NEED_PARAMS(1, 1);

            NEED_MOUNT();

            // Arg 1: file/folder path (cannot delete non-empty folders)
            if (f_unlink(argv[0]))
            {
                fprintf(stderr, "Error: Unable to delete file or directory.");
                ret = 1;
                goto exit;
            }
        }
        else if (strcmp(parg, "list") == 0)
        {
            char* root = "/";
            DIR dir = { 0 };
            FILINFO info = { 0 };
            char lfname[257];

            NEED_PARAMS(0, 1);

            // Arg 1: folder path (optional)

            if (nargs == 1)
            {
                root = argv[0];
            }

            if (f_opendir(&dir, root))
            {
                fprintf(stderr, "Error: Unable to opening directory '%s' for listing.\n", root);
                ret = 1;
                goto exit;
            }

            printf("Listing directory contents of: %s\n", root);

            info.lfname = lfname;
            info.lfsize = sizeof(lfname)-1;
            while ((!f_readdir(&dir, &info)) && (strlen(info.fname) > 0))
            {
                if (strlen(info.lfname) > 0)
                    printf(" - %s (%s)\n", info.lfname, info.fname);
                else
                    printf(" - %s\n", info.fname);
            }
        }
        else
        {
            fprintf(stderr, "Error: Unknown or invalid command: %s\n", argv[-1]);
            PRINT_HELP_AND_QUIT();
        }
        argv += nargs;
        argc -= nargs;
    }

    ret = 0;

exit:

    disk_cleanup(0);

    return ret;
}
Beispiel #9
0
/**
  * @brief  Main program
  * @param  None
  * @retval None
  */
int main(void)
{
  FRESULT res1, res2;                                   /* FatFs function common result codes */
  uint32_t byteswritten1, byteswritten2;                /* File write counts */
  uint32_t bytesread1, bytesread2;                      /* File read counts */
  uint8_t wtext[] = "This is STM32 working with FatFs"; /* File write buffer */
  uint8_t rtext1[100], rtext2[100];                     /* File read buffers */
  
  /* STM32F4xx HAL library initialization:
       - Configure the Flash prefetch, instruction and Data caches
       - Configure the Systick to generate an interrupt each 1 msec
       - Set NVIC Group Priority to 4
       - Global MSP (MCU Support Package) initialization
     */
  HAL_Init();
  
  /* Configure the system clock to 175 MHz */
  SystemClock_Config();
  
  /* Configure LED1 and LED3 */
  BSP_LED_Init(LED1);
  BSP_LED_Init(LED3);
  
  /*##-1- Link the disk I/O drivers ##########################################*/
  if((FATFS_LinkDriver(&SDRAMDISK_Driver, RAMpath) == 0) && (FATFS_LinkDriver(&SD_Driver, SDpath) == 0))
  {  
    /*##-2- Register the file system object to the FatFs module ##############*/
    res1 = f_mount(&RAMFatFs, (TCHAR const*)RAMpath, 0);
    res2 = f_mount(&SDFatFs, (TCHAR const*)SDpath, 0);
    
    if((res1 != FR_OK) || (res2 != FR_OK))
    {
      /* FatFs Initialization Error */
      Error_Handler();
    }
    else
    {
      /*##-3- Create a FAT file system (format) on the logical drives ########*/
      /* WARNING: Formatting the uSD card will delete all content on the device */ 
      res1 = f_mkfs((TCHAR const*)RAMpath, 0, 0);
      res2 = f_mkfs((TCHAR const*)SDpath, 0, 0);
      
      if((res1 != FR_OK) || (res2 != FR_OK))
      {
        /* FatFs Format Error */
        Error_Handler();
      }
      else
      {
        /*##-4- Create and Open new text file objects with write access ######*/
        res1 = f_open(&RAMFile, "0:STM32.TXT", FA_CREATE_ALWAYS | FA_WRITE);
        res2 = f_open(&SDFile, "1:STM32.TXT", FA_CREATE_ALWAYS | FA_WRITE);
        
        if((res1 != FR_OK) || (res2 != FR_OK))
        {
          /* 'STM32.TXT' file Open for write Error */
          Error_Handler();
        }
        else
        {
          /*##-5- Write data to the text files ###############################*/
          res1 = f_write(&RAMFile, wtext, sizeof(wtext), (void *)&byteswritten1);
          res2 = f_write(&SDFile, wtext, sizeof(wtext), (void *)&byteswritten2);
          
          if((byteswritten1 == 0) || (byteswritten2 == 0) || (res1 != FR_OK) || (res2 != FR_OK))
          {
            /* 'STM32.TXT' file write Error */
            Error_Handler();
          }
          else
          {
            /*##-6- Close the open text files ################################*/
            f_close(&RAMFile);
            f_close(&SDFile);
            
            /*##-7- Open the text files object with read access ##############*/
            res1 = f_open(&RAMFile, "0:STM32.TXT", FA_READ);
            res2 = f_open(&SDFile, "1:STM32.TXT", FA_READ);
            
            if((res1 != FR_OK) || (res2 != FR_OK))
            {
              /* 'STM32.TXT' file Open for read Error */
              Error_Handler();
            }
            else
            {
              /*##-8- Read data from the text files ##########################*/
              res1 = f_read(&RAMFile, rtext1, sizeof(rtext1), (UINT*)&bytesread1);
              res2 = f_read(&SDFile, rtext2, sizeof(rtext2), (UINT*)&bytesread2);
              
              if((res1 != FR_OK) || (res2 != FR_OK))
              {
                /* 'STM32.TXT' file Read or EOF Error */
                Error_Handler();
              }
              else
              {
                /*##-9- Close the open text files ############################*/
                f_close(&RAMFile);
                f_close(&SDFile);
                
                /*##-10- Compare read data with the expected data ############*/
                if((bytesread1 != byteswritten1) || (bytesread2 != byteswritten2))
                {                
                  /* Read data is different from the expected data */
                  Error_Handler();
                }
                else
                {
                  /* Success of the demo: no error occurrence */
                  BSP_LED_On(LED1);
                }
              }
            }
          }
        }
      }
    }
  }
  
  /*##-11- Unlink the disk I/O drivers #######################################*/
  FATFS_UnLinkDriver(RAMpath);
  FATFS_UnLinkDriver(SDpath);
  
  /* Infinite loop */
  while (1)
  {
  }
}
/**
  * @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 */

  /* STM32F4xx HAL library initialization:
       - Configure the Flash prefetch, instruction and Data caches
       - Configure the Systick to generate an interrupt each 1 msec
       - Set NVIC Group Priority to 4
       - Global MSP (MCU Support Package) initialization
     */
  HAL_Init();

  /* Configure the system clock to 168 MHz */
  SystemClock_Config();

  /* Configure LED1 and LED3 */
  BSP_LED_Init(LED1);
  BSP_LED_Init(LED3);

  /*##-1- Link the RAM disk I/O driver #######################################*/
  if(FATFS_LinkDriver(&SDRAMDISK_Driver, RAMDISKPath) == 0)
  {
    /*##-2- Register the file system object to the FatFs module ##############*/
    if(f_mount(&RAMDISKFatFs, (TCHAR const*)RAMDISKPath, 0) != FR_OK)
    {
      /* FatFs Initialization Error */
      Error_Handler();
    }
    else
    {
      /*##-3- Create a FAT file system (format) on the logical drive #########*/
      if(f_mkfs((TCHAR const*)RAMDISKPath, 0, 0) != FR_OK)
      {
        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);

          if((byteswritten == 0) || (res != FR_OK))
          {
            /* 'STM32.TXT' file Write or EOF Error */
            Error_Handler();
          }
          else
          {
            /*##-6- Close the open text file #################################*/
            f_close(&MyFile);

            /*##-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)) /* EOF or Error */
              {
                /* '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 */
                  BSP_LED_On(LED1);
                }
              }
            }
          }
        }
      }
    }
  }

  /*##-11- Unlink the RAM disk I/O driver ####################################*/
  FATFS_UnLinkDriver(RAMDISKPath);

  /* Infinite loop */
  while (1)
  {
  }
}
Beispiel #11
0
  void SD_Init(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 */        

  /*##-1- Link the 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 #########*/
      if(f_mkfs((TCHAR const*)SDPath, 0, 0) != FR_OK)
      {     
        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);
          
          if((byteswritten == 0) || (res != FR_OK))
          {
            /* 'STM32.TXT' file Write or EOF Error */
            Error_Handler();
          }
          else
          {
            /*##-6- Close the open text file #################################*/
            f_close(&MyFile);
            
            /*##-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)) /* EOF or Error */
              {
                /* '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 */
                  BSP_LED_On(LED0);
                }
              }
            }
          }
        }
      }
    }
  }
  
  /*##-11- Unlink the SD disk I/O driver ####################################*/
  FATFS_UnLinkDriver(SDPath);
  
}
Beispiel #12
0
/* Usart receive task */
void vUsartRx_Task( void ) {
    unsigned char pucFileName[30];          // File name
    unsigned char ucReceived;               // Received char
    short i;

    short sFlag = 0;                        // State flag

    FIL Fil;                                // File object
    FRESULT rc;                             // Result code
    DIR dir;                                // Directory object
    FILINFO fno;                            // File information object
    UINT bw, br;                            // File counters

    // Usart receive loop
    for (;;) {
        // Data is available
        if (USART_IsDataAvailable(AT91C_BASE_US0)) {
            USART_ReadBuffer(AT91C_BASE_US0, &ucReceived, 1);

            // Stage 0: receive file name
            if          (sFlag == 0 && ucReceived == '\x01') {
                i = 0;
                memset(pucFileName, 0, 30);
                sFlag = 1;
                //debug_printf("\r\n--");

            // Stage 1: receiving file name
            } else if   (sFlag == 1 && ucReceived != '\x02') {
                //debug_printf("%c", ucReceived);
                pucFileName[i] = ucReceived;
                i++;
            // Stage 1: end of file name
            } else if   (sFlag == 1 && ucReceived == '\x02') {
                //debug_printf("\r\nRec file: %s\r\n", pucFileName);
                sFlag = 2;

                // Create the file
                rc = f_open(&Fil, pucFileName, FA_CREATE_ALWAYS | FA_WRITE);
                if (rc) {
                    sprintf(ucRemoteBuffer, "File creation failure.\r\n");
                    remote_printf(ucRemoteBuffer);
                    sFlag = 0;
                }

            // Stage 2: receive file
            } else if   (sFlag == 2 && ucReceived != '\x03') {
                //debug_printf("%c", ucReceived);
                f_write(&Fil, &ucReceived, 1, &bw);

            // Stage 2: end of file
            } else if   (sFlag == 2 && ucReceived == '\x03') {
                sFlag = 3;

            // Stage 3: end of transmission
            } else if   (sFlag == 3 && ucReceived == '\x04') {
                f_close(&Fil);
                sprintf(ucRemoteBuffer, "\r\nReceived file: %s\r\n", pucFileName);
                remote_printf(ucRemoteBuffer);
                sFlag = 0;
            }
        } else {
            vTaskDelay(5);
        }
    }
}
Beispiel #13
0
void LTK_edit_file(void)
{
    FATFS fs;
    FIL file;
    FRESULT res; 
    DIR dirs;
    FILINFO finfo;
    char key = 0;
    char path[20];

    uint32_t index = 0x00;
    uint32_t reindex = 0x00;
    uint8_t file_buff[512] = {0};

    uint32_t files_num = 0;
    res = f_mount(0,&fs);
    if (res != FR_OK)
    {
        printf("mont file system error, error code: %u\n",res);
        return;
    }
    res = f_opendir(&dirs,"/");
    printf("file list\n");
    if (res == FR_OK) 
    {
        while ((f_readdir(&dirs, &finfo) == FR_OK) && finfo.fname[0]) 
        {
            if (finfo.fattrib & AM_DIR) 
            { 
                continue;
            } 
            else 
            {   
                files_num++;
                printf("/%12s%7ld KB\n", &finfo.fname[0],(finfo.fsize + 512) / 1024);
            }
        }
        if( files_num == 0 )
        {
            printf("no file\n!");    
        }
    }
    else
    {
        printf("failed to open root directory, error code: %u\n", res);
    }
    printf("input the full name of the file, terminated with enter\n");
    scanf("%[^\n]",path);
    res = f_open(&file,path,FA_READ | FA_WRITE);
    if (res == FR_OK)
    {

        printf("file: %s opened successfully\n",path);
        printf("input the text!");
        printf("terminated with ESC or Ctrl+C\n");

        while(1)
        {
            key = getchar();
            if ((key == 0x1B) || (key == 0x03))   //key ESC or Ctrl + C
            {
                printf("saving data...\n");
                res = f_write(&file,file_buff,index,&reindex);
                if ((res == FR_OK) && (reindex == index))
                {
                    printf("data saved\n");
                    f_close(&file);
                    index = 0x00;
                    reindex = 0x00;
                }
                else
                {
                    printf("fail to save data, error code: %u", res);
                }
                break;
            }
            else
            {
                file_buff[index++] = key;
                if (index > 512)
                {
                    index = 0x00;
                }
            }
        }
    }
    else
    {
        printf("fail to open the file, error code: %u\n",res);
    }
}
Beispiel #14
0
/*
*********************************************************************************************************
*	函 数 名: GUI_Copy_ScreenRect()
*	功能说明: 屏幕截图,然后以bmp图片格式(为24位高真彩位图)保存到指定的路径下
*	形    参:x:X坐标   y:y坐标   sizex:长度   sizey:宽度
*             *Save_Path:保存路径,其中文件名后缀必须为bmp
*             例如:"0:/Picture/abcd.bmp" 注意!!:路径"0:/0:/Picture"必须存在
*             否则该函数调用无效。            	
*	返 回 值: 无
*********************************************************************************************************
*/
void GUI_SaveBMP(uint16_t startx,uint16_t starty,uint16_t sizex,uint16_t sizey,void *Save_Path)
{
	uint32_t	size = (sizex*sizey)*3;//-- 由于是24为BMP位图,一个像素占3个字节,所以要乘以3
	uint16_t	Header_num = sizeof(BITMAPFILEHEADER)+sizeof(BITMAPINFOHEADER);
	int16_t 	i = 0,j = 0,temp = 0,count = 0;
	uint16_t 	Buffer_num = 510;


	BITMAPFILEHEADER 	 BmpFileHeader;
	BITMAPINFOHEADER	 BmpInfoHeader;
	

	/*------------------------------- 建立文件头数据 -----------------------------------------*/
	BmpFileHeader.bfType      = 0x4D42;//--文件标志.只对'BM',用来识别BMP位图类型
	BmpFileHeader.bfSize 	  = size + Header_num;//--文件大小,占四个字节
	BmpFileHeader.bfReserved1 = 0;				  //--保留字段1
	BmpFileHeader.bfReserved2 = 0;				  //--保留字段2
	BmpFileHeader.bfOffBits   = Header_num;//--从文件开始到位图数据(bitmap data)开始之间的的偏移量
	/*------------------------------- 建立文件信息数据 ---------------------------------------*/
	BmpInfoHeader.biSize   = sizeof(BITMAPINFOHEADER);//--说明BITMAPINFOHEADER结构所需要的字数
	BmpInfoHeader.biWidth  = sizex;   //--说明图象的宽度,以象素为单位
	BmpInfoHeader.biHeight = sizey;   //--说明图象的高度,以象素为单位 
	BmpInfoHeader.biPlanes = 1;	      //--为目标设备说明位面数,其值将总是被设为1
	BmpInfoHeader.biBitCount = 24;    //--说明比特数/象素,其值为1、4、8、16、24、或32
	BmpInfoHeader.biCompression = 0;  //--说明图象数据压缩的类型,无压缩
	BmpInfoHeader.biSizeImage = size; //--说明图象的大小(必须是4的倍数),以字节为单位。
										//--当用BI_RGB格式时,可设置为0 
	BmpInfoHeader.biXPelsPerMeter = 0;//--说明水平分辨率,用象素/米表示
	BmpInfoHeader.biYPelsPerMeter = 0;//--说明垂直分辨率,用象素/米表示
	BmpInfoHeader.biClrUsed		  = 0;//--说明位图实际使用的彩色表中的颜色索引数
	BmpInfoHeader.biClrImportant  = 0;//--说明对图象显示有重要影响的颜色索引的数目,如果是0,表示都重要
	/*-------------------------- 创建保存截图数据的文件  ------------------------------------*/
	if (f_open(&FileSave,Save_Path, FA_WRITE|FA_CREATE_ALWAYS) == FR_OK ) 
	{	
			//--先写图像头数据和图像信息数据
			result = f_write (&FileSave,&BmpFileHeader,sizeof(BmpFileHeader),&bw);
			if (result != FR_OK)
			{
				return;
			}
			
			result = f_write (&FileSave,&BmpInfoHeader,sizeof(BmpInfoHeader),&bw);
			if (result != FR_OK)
			{
				return;
			}
			for(j = sizey-1; j >= 0; j--)
			{		 	
					 for(i = 0; i < sizex; i++)
					 {
							temp = LCD_GetPixel(startx+i,starty+j);
							data[count+2] = (u8)((temp&0xf800)>>8);
							data[count+1] = (u8)((temp&0x7e0)>>3);
							data[count]   = (u8)((temp&0x1f)<<3);
							count += 3;
							if(count == Buffer_num)
							{
									count = 0;
									result = f_write (&FileSave,data,Buffer_num,&bw);
									if (result != FR_OK)
									{
										return;
									}		
							}
					 }
			}
		if(count > 0)	f_write (&FileSave,data,count,&bw);
		f_close(&FileSave);			
     }
Beispiel #15
0
void start_jffs2(void)
{
	if (!nvram_match("jffs2_on", "1")) {
		notice_set("jffs", "");
		return;
	}

	int format = 0;
	char s[256];
	int size;
	int part;
	const char *p;
	struct statfs sf;
	int model = 0;

	if (!wait_action_idle(10)) return;

	if (!mtd_getinfo(JFFS2_PARTITION, &part, &size)) return;

	model = get_model();
_dprintf("*** jffs2: %d, %d\n", part, size);
	if (nvram_match("jffs2_format", "1")) {
		nvram_set("jffs2_format", "0");
		if( (model==MODEL_RTAC56U || model==MODEL_RTAC56S || model==MODEL_RTAC68U || model==MODEL_RTAC87U) ^ (!mtd_erase(JFFS_NAME)) ){
                        error("formatting");
                        return;
		}
		
		format = 1;
	}

	sprintf(s, "%d", size);
	p = nvram_get("jffs2_size");
	if ((p == NULL) || (strcmp(p, s) != 0)) {
		if (format) {
			nvram_set("jffs2_size", s);
			nvram_commit_x();
		}
		else if ((p != NULL) && (*p != 0)) {
			error("verifying known size of");
			return;
		}
	}

	if (statfs("/jffs", &sf) == 0) { 
		switch(model) {
			case MODEL_RTAC56S: 
			case MODEL_RTAC56U: 
			case MODEL_RTAC68U: 
			case MODEL_RTAC87U: 
			case MODEL_RTN65U:
			case MODEL_RTN14U: // it should be better to use LINUX_KERNEL_VERSION >= KERNEL_VERSION(2,6,36)
			{
				if (sf.f_type != 0x73717368 /* squashfs */) {
					// already mounted
					notice_set("jffs", format ? "Formatted" : "Loaded");
					return;
				}
				break;
			}
			default:
			{
	                        if (sf.f_type != 0x71736873 /* squashfs */) {
        	                        // already mounted
                	                notice_set("jffs", format ? "Formatted" : "Loaded");
                        	        return;
				}
				break;
			}
		}
	}
	if (nvram_get_int("jffs2_clean_fs")) {
		if (!mtd_unlock(JFFS2_PARTITION)) {
			error("unlocking");
			return;
		}
	}
	modprobe(JFFS_NAME);
	sprintf(s, MTD_BLKDEV(%d), part);

	if (mount(s, "/jffs", JFFS_NAME, MS_NOATIME, "") != 0) {
                if( (get_model()==MODEL_RTAC56U || get_model()==MODEL_RTAC56S || get_model()==MODEL_RTAC68U || get_model()==MODEL_RTAC87U) ^ (!mtd_erase(JFFS_NAME)) ){
                        error("formatting");
                        return;
                }

		format = 1;
		if (mount(s, "/jffs", JFFS_NAME, MS_NOATIME, "") != 0) {
			_dprintf("*** jffs2 2-nd mount error\n");
			//modprobe_r(JFFS_NAME);
			error("mounting");
			return;
		}
	}

#ifdef TEST_INTEGRITY
	int test;

	if (format) {
		if (f_write("/jffs/.tomato_do_not_erase", &size, sizeof(size), 0, 0) != sizeof(size)) {
			stop_jffs2(0);
			error("setting integrity test for");
			return;
		}
	}
	if ((f_read("/jffs/.tomato_do_not_erase", &test, sizeof(test)) != sizeof(test)) || (test != size)) {
		stop_jffs2(0);
		error("testing integrity of");
		return;
	}
#endif

	if (nvram_get_int("jffs2_clean_fs")) {
		_dprintf("Clean /jffs/*\n");
		system("rm -fr /jffs/*");
		nvram_unset("jffs2_clean_fs");
		nvram_commit_x();
	}

	notice_set("jffs", format ? "Formatted" : "Loaded");

	if (((p = nvram_get("jffs2_exec")) != NULL) && (*p != 0)) {
		chdir("/jffs");
		system(p);
		chdir("/");
	}
	run_userfile("/jffs", ".asusrouter", "/jffs", 3);

}
Beispiel #16
0
FRESULT FatFs::File::write(const void* buf, uint32_t len, uint32_t* written)
{
    return f_write(&file, buf, len, written);
}
Beispiel #17
0
//*****************************************************************************
//
// This is called at the start of logging to open a file on the storage
// device in preparation for saving data.  If no file name is specified, then
// a new file will be created.
//
// If a file name is specified, then that will be used instead of searching
// for an available file.  The file name that is passed in must be a maximum
// of 8 characters (9 including trailing 0) and represents the first part of
// the file name not including the extension.
//
// The function returns a pointer to the first part of the file name
// (without file extension).  It can be up to 8 characters (9 including the
// trailing 0).  If there is any error then a NULL pointer is returned.
//
//*****************************************************************************
char *
USBStickOpenLogFile(char *pcFilename8)
{
    FRESULT iFResult;
    uint32_t ui32BytesWritten;
    static char pcFilename[16];
    uint32_t ui32Len;

    //
    // Check state for ready device
    //
    g_ui32Flags &= ~FLAGS_FILE_OPENED;
    if(g_iState == eSTATE_DEVICE_READY)
    {
        //
        // If a file name is specified then open that file
        //
        if(pcFilename8 && pcFilename8[0])
        {
            //
            // Copy the filename into local storage and cap at 8 characters
            // length.
            //
            memcpy(pcFilename, pcFilename8, 8);
            pcFilename[8] = 0;

            //
            // Find the actual length of the string (8 chars or less) so we
            // know where to add the extension.
            //
            ui32Len = strlen(pcFilename);

            //
            // Add the extension to the file name.
            //
            usnprintf(&pcFilename[ui32Len], 5, ".CSV");
        }

        //
        // Otherwise no file name was specified so create a new one.
        //
        else
        {
            if(CreateFileName(pcFilename, sizeof(pcFilename)))
            {
                //
                // There was a problem creating a file name so return an error
                //
                return(0);
            }
        }

        //
        // Open the file by name that was determined above.  If the file exists
        // it will be opened, and if not it will be created.
        //
        iFResult = f_open(&g_sFileObject, pcFilename, (FA_OPEN_ALWAYS |
                                                      FA_WRITE));
        if(iFResult != FR_OK)
        {
            return(0);
        }

        //
        // Since it is possible that the file already existed when opened,
        // seek to the end of the file so new data will be appended.  If this
        // is a new file then this will just be the beginning of the file.
        //
        iFResult = f_lseek(&g_sFileObject, g_sFileObject.fsize);
        if(iFResult != FR_OK)
        {
            return(0);
        }

        //
        // Set flag to indicate file is now opened.
        //
        g_ui32Flags |= FLAGS_FILE_OPENED;

        //
        // If no file name was specified, then this is a new file so write a
        // header line with column titles to the CSV file.
        //
        if(!pcFilename8 || !pcFilename8[0])
        {
            //
            // Write a header line to the CSV file
            //
            iFResult = f_write(&g_sFileObject, g_pcCSVHeaderLine,
                              sizeof(g_pcCSVHeaderLine), &ui32BytesWritten);
            if(iFResult != FR_OK)
            {
                g_ui32Flags &= ~FLAGS_FILE_OPENED;
                return(0);
            }

            //
            // Since no file name was specified that means a file name was
            // created.  Terminate the new file name at the '.' separator
            // and return it to the caller.  We know that created file names
            // are always 7 characters.  Return the newly created file name
            // (the part before the '.')
            //
            pcFilename[7] = 0;
            return(pcFilename);
        }

        //
        // Otherwise, a file name was specified, so no need to write a
        // header row.  The caller's file name is unchanged so return the
        // same value back.
        //
        else
        {
            return(pcFilename8);
        }
    }

    else
    {
        //
        // Device not ready so return NULL.
        //
        return(0);
    }
}
Beispiel #18
0
//****************************************************************************
//
//! Main function
//!
//! \param none
//!
//!
//! \return None.
//
//****************************************************************************
void main()
{

    FIL fp;
    FATFS fs;
    FRESULT res;
    DIR dir;
    WORD Size;

    //
    // Initialize Board configurations
    //
    BoardInit();

    //
    // Muxing for Enabling UART_TX and UART_RX.
    //
    PinMuxConfig();

    //
    // Set the SD card clock as output pin
    //
    MAP_PinDirModeSet(PIN_07,PIN_DIR_MODE_OUT);

    //
    // Initialising the Terminal.
    //
    InitTerm();

    //
    // Clearing the Terminal.
    //
    ClearTerm();

    //
    // Display the Banner
    //
    Message("\n\n\n\r");
    Message("\t\t   ********************************************\n\r");
    Message("\t\t        CC3200 SDHost Fatfs Demo Application  \n\r");
    Message("\t\t   ********************************************\n\r");
    Message("\n\n\n\r");

    //
    // Enable MMCHS
    //
    MAP_PRCMPeripheralClkEnable(PRCM_SDHOST,PRCM_RUN_MODE_CLK);

    //
    // Reset MMCHS
    //
    MAP_PRCMPeripheralReset(PRCM_SDHOST);

    //
    // Configure MMCHS
    //
    MAP_SDHostInit(SDHOST_BASE);

    //
    // Configure card clock
    //
    MAP_SDHostSetExpClk(SDHOST_BASE,MAP_PRCMPeripheralClockGet(PRCM_SDHOST),15000000);

    f_mount(0,&fs);
    res = f_opendir(&dir,"/");
    if( res == FR_OK)
    {
        Message("Opening root directory.................... [ok]\n\n\r");
        Message("/\n\r");
        ListDirectory(&dir);
    }
    else
    {
        Message("Opening root directory.................... [Failed]\n\n\r");
    }

    Message("\n\rReading user file...\n\r");
    res = f_open(&fp,USERFILE,FA_READ);
    if(res == FR_OK)
    {
        f_read(&fp,pBuffer,100,&Size);
        Report("Read : %d Bytes\n\n\r",Size);
        Report("%s",pBuffer);
        f_close(&fp);
    }
    else
    {
        Report("Failed to open %s\n\r",USERFILE);
    }

    Message("\n\n\rWriting system file...\n\r");
    res = f_open(&fp,SYSFILE,FA_CREATE_ALWAYS|FA_WRITE);
    if(res == FR_OK)
    {
        f_write(&fp,SYSTEXT,sizeof(SYSTEXT),&Size);
        Report("Wrote : %d Bytes",Size);
        res = f_close(&fp);
    }
    else
    {
        Message("Failed to create a new file\n\r");
    }

    while(1)
    {

    }
}
Beispiel #19
0
static int runCommand(int argc, char ** argv)
{
    int i, sectors;

    DIR rootDir;
    FILINFO info;

    char * filename;

    FIL    intFileObj;
    FILE * extFileObj;

    UINT bytesRead, bytesWritten;

    // What command?
    if (strcmp(argv[2], "mkfs") == 0)
    {
        // Get sector count
        if (argc != 4)
            return printUsage();

        sectors = atoi(argv[3]);

        // Validate sector count
        if (sectors <= 0)
        {
            fputs("Sector Count must be > 0\n", stderr);
            return 1;
        }

        sectorCount = (DWORD) sectors;

        // Write 0s for the image
        memset(buffer, 0, SECTOR_SIZE);
        for (i = 0; i < sectors; i++)
        {
            if (disk_write(0, buffer, i, 1) != RES_OK)
                return 1;
        }

        // Make filesystem
        if (f_mkfs(0, 1, 0) != FR_OK)
        {
            fputs("mkfs failed\n", stderr);
            return 1;
        }
    }
    else if (strcmp(argv[2], "ls") == 0)
    {
        // Get directory to list
        if (argc > 4)
            return printUsage();

        // Open directory
        if (f_opendir(&rootDir, (argc == 4) ? argv[3] : "") != FR_OK)
        {
            fputs("opendir failed (directory exists?)\n", stderr);
            return 1;
        }

        // Set long file name buffer
        info.lfname = (char *) buffer;
        info.lfsize = BUFFER_SIZE;

        // List contents
        while (f_readdir(&rootDir, &info) == FR_OK && info.fname[0] != 0)
        {
            // Get filename
            filename = *info.lfname ? info.lfname : info.fname;

            // Print attributes
            printf((info.fattrib & AM_RDO) ? "r" : " ");
            printf((info.fattrib & AM_HID) ? "h" : " ");
            printf((info.fattrib & AM_SYS) ? "s" : " ");
            printf((info.fattrib & AM_DIR) ? "d" : " ");
            printf((info.fattrib & AM_ARC) ? "a" : " ");

            // Print filename
            printf(" %s\n", filename);
        }
    }
    else if (strcmp(argv[2], "rm") == 0)
    {
        // Get filename
        if (argc != 4)
            return printUsage();

        filename = argv[3];

        // Make file writable
        f_chmod(filename, 0, AM_RDO);

        // Remove file
        if (f_unlink(filename) != FR_OK)
        {
            fputs("unlink failed (file exists?)\n", stderr);
            return 1;
        }
    }
    else if (strcmp(argv[2], "mkdir") == 0)
    {
        // Get filename
        if (argc != 4)
            return printUsage();

        filename = argv[3];

        // Create directory
        if (f_mkdir(filename) != FR_OK)
        {
            fputs("mkdir failed\n", stderr);
            return 1;
        }
    }
    else if (strcmp(argv[2], "read") == 0)
    {
        // Get both files
        if (argc != 5)
            return printUsage();

        // Open both files
        if (f_open(&intFileObj, argv[3], FA_READ) != FR_OK)
        {
            fputs("internal open failed (file exists?)\n", stderr);
            return 1;
        }

        extFileObj = fopen(argv[4], "wb");
        if (extFileObj == NULL)
        {
            perror("external open failed\n");
            f_close(&intFileObj);
            return 1;
        }

        // Copy data
        do
        {
            // Internal read
            if (f_read(&intFileObj, buffer, BUFFER_SIZE, &bytesRead) != FR_OK)
            {
                fputs("internal read failed\n", stderr);
                fclose(extFileObj);
                f_close(&intFileObj);
                return 1;
            }

            // External write
            if (fwrite(buffer, 1, bytesRead, extFileObj) != bytesRead)
            {
                perror("external write failed\n");
                fclose(extFileObj);
                f_close(&intFileObj);
                return 1;
            }
        }
        while (bytesRead == BUFFER_SIZE);

        // Close files
        fclose(extFileObj);
        f_close(&intFileObj);
    }
    else if (strcmp(argv[2], "write") == 0)
    {
        // Get both files
        if (argc != 5)
            return printUsage();

        // Open both files
        if (f_open(&intFileObj, argv[3], FA_WRITE | FA_CREATE_ALWAYS) != FR_OK)
        {
            fputs("internal open failed\n", stderr);
            return 1;
        }

        extFileObj = fopen(argv[4], "rb");
        if (extFileObj == NULL)
        {
            perror("external open failed (file exists?)");
            f_close(&intFileObj);
            return 1;
        }

        // Copy data
        do
        {
            // External read
            bytesRead = fread(buffer, 1, BUFFER_SIZE, extFileObj);
            if (bytesRead != BUFFER_SIZE && !feof(extFileObj))
            {
                fputs("external read failed\n", stderr);
                fclose(extFileObj);
                f_close(&intFileObj);
                return 1;
            }

            // Internal write
            if (f_write(&intFileObj, buffer, bytesRead, &bytesWritten) != FR_OK ||
                    bytesRead != bytesWritten)
            {
                fputs("internal write failed\n", stderr);
                fclose(extFileObj);
                f_close(&intFileObj);
                return 1;
            }
        }
        while (bytesRead == BUFFER_SIZE);

        // Close files
        fclose(extFileObj);
        f_close(&intFileObj);
    }
    else
    {
        // Bad command
        return printUsage();
    }

    return 0;
}
Beispiel #20
0
/**
  * @brief  Main routine for Mass Storage Class
  * @param  None
  * @retval None
  */
static void MSC_Application(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 */
  
  /* Register the file system object to the FatFs module */
  if(f_mount(&USBDISKFatFs, (TCHAR const*)USBDISKPath, 0) != FR_OK)
  {
    /* FatFs Initialization Error */
    Error_Handler();
  }
  else
  {
      /* 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
      {
        /* Write data to the text file */
        res = f_write(&MyFile, wtext, sizeof(wtext), (void *)&byteswritten);
        
        if((byteswritten == 0) || (res != FR_OK))
        {
          /* 'STM32.TXT' file Write or EOF Error */
          Error_Handler();
        }
        else
        {
          /* Close the open text file */
          f_close(&MyFile);
          
        /* 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
        {
          /* Read data from the text file */
          res = f_read(&MyFile, rtext, sizeof(rtext), (void *)&bytesread);
          
          if((bytesread == 0) || (res != FR_OK))
          {
            /* 'STM32.TXT' file Read or EOF Error */
            Error_Handler();
          }
          else
          {
            /* Close the open text file */
            f_close(&MyFile);
            
            /* 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 */
              BSP_LED_On(LED3);
            }
          }
        }
      }
    }
  }
  
  /* Unlink the USB disk I/O driver */
  FATFS_UnLinkDriver(USBDISKPath);
}
Beispiel #21
0
Datei: IV.c Projekt: yanava/blfw
//TODO: typedef enum for return values
// fatfs_handle is the object responsible for fat32 interface
int IV_ExportCurve(char * filename, IV_CURVE_T *curve, IV_FATFS_T *fatfs_handle)
{
  uint32_t i;
  char header[64];
  char data_string[128];
  UINT BytesWritten;
  unsigned int n_attempt;
  
  //check if the caller is a orc
  if(filename == 0)
  {
    return 0;
  }
  
  //check if the requested curve has enough points
  if(curve->super.elements == 0)
  {
    return 0;
  }
  
  SD_InterruptEnable();
  
  memset(&fatfs_handle->fs32, 0, sizeof(FATFS));
  
  fatfs_handle->res = f_mount(0, &fatfs_handle->fs32);
  
  if(fatfs_handle->res != FR_OK)
  {
    return -1;
  }
  
  fatfs_handle->res = f_close(&fatfs_handle->fil);
  
  n_attempt = IV_MAX_FATFS_ATTEMPT;
  
  do
  {
      fatfs_handle->res = f_open(&fatfs_handle->fil, filename, FA_CREATE_ALWAYS | FA_WRITE);
      n_attempt -= 1;
  } while(n_attempt > 0 && fatfs_handle->res != FR_OK);
  
  if(n_attempt == 0)
  {
      fatfs_handle->res = f_close(&fatfs_handle->fil);
      return -2;  // very bad, check if the retarded user inserted the sd card
  }
  
  f_lseek(&fatfs_handle->fil, (fatfs_handle->fil.fsize)); // EOF please
   
  fatfs_handle->res = f_write(&fatfs_handle->fil, header, strlen(header), &BytesWritten);
  
  //Log the whole curve even the empty points, improve this!
  for(i = 0; i < IV_CURVE_SIZE; i++)
  {
    sprintf(data_string, "V[%d] = %d; I[%d] = %d;\r\n", i, curve->points[i].v, i, curve->points[i].correct_i);
    fatfs_handle->res = f_write(&fatfs_handle->fil, data_string, strlen(data_string), &BytesWritten);
  }  
  
  fatfs_handle->res = f_close(&fatfs_handle->fil);
  
  return 1;
}
Beispiel #22
0
/* StartTaskFATFS function */
void StartTaskFATFS(void const * argument)
{
  /* USER CODE BEGIN StartTaskFATFS */
  /* Infinite loop */
	UINT count = 0;
uint32_t i = 1;
static	FATFS fileSystem;
static	FIL testFile;
	FRESULT res = FR_OK;
	char buf[100];
	sprintf(gbuf, "fat run");
			//HAL_UART_Transmit(&huart1,(uint8_t*)buf,strlen(buf),100);
	
	do{
	osDelay(1000);
//	sprintf(SD_Path,"0:/\0");
	res = f_mount(&fileSystem, SD_Path, 1);
		sprintf(gbuf, "fat mnt %i",res);
		
    osDelay(1000);
	//HAL_UART_Transmit(&huart1,(uint8_t*)buf,strlen(buf),100);

	/*if(res == FR_NO_FILESYSTEM){ 
		res = f_mkfs("", 0, 0);
		sprintf(gbuf, "fat mkfs %i",res);
		
    osDelay(1000);
		//HAL_UART_Transmit(&huart1,(uint8_t*)buf,strlen(buf),100);
		
		res = f_mount(&fileSystem, SD_Path, 1);
		sprintf(gbuf, "fat mnt %i",res);
		
    osDelay(1000);
	//HAL_UART_Transmit(&huart1,(uint8_t*)buf,strlen(buf),100);
	
}*/
	}while (res!= FR_OK);
	
			HAL_UART_Transmit(&huart1,(uint8_t*)buf,strlen(buf),100);
  res = f_open(&testFile, "testfile.txt", FA_OPEN_ALWAYS | FA_READ |FA_WRITE );
			sprintf(gbuf, "fat open %i",res);
	
    osDelay(1000);
			//HAL_UART_Transmit(&huart1,(uint8_t*)buf,strlen(buf),100);
	/*uint16_t tmp = f_size(&testFile);
	f_lseek(&testFile, tmp);
			*/
	for(;;)
  {
		//if(i > 100000) vTaskDelete(TaskFATFSHandle);
		if(i%100 == 0){
			sprintf(&gbuf[9], "fat wr %i", i);
			
    osDelay(1000);
			//HAL_UART_Transmit(&huart1,(uint8_t*)buf,strlen(buf),100);
		}
		memset(buf,0,100);
		sprintf(buf, "%lu\r\n", i++);
    res = f_write(&testFile, buf, strlen(buf), &count);
		if( res != FR_OK) break;
		f_sync(&testFile);
    //f_close(&testFile);
    osDelay(10);
  }
  /* USER CODE END StartTaskFATFS */
}
Beispiel #23
0
/**
 * @brief write a profile string to a ini file
 * @param section [in] name of the section,can't be NULL and empty string
 * @param key [in] name of the key pairs to value, can't be NULL and empty string
 * @param value [in] profile string value
 * @param file [in] path of ini file
 * @return 1 : success\n 0 : failure
 */
int write_profile_string(const char *section, const char *key,
					const char *value, const char *file)
{
	char *buf;
	char *w_buf;
	int sec_s,sec_e,key_s,key_e, value_s, value_e;
	int value_len = (int)strlen(value);
	int file_size;
	unsigned int new_file_size;

	//check parameters
	assert(section != NULL && strlen(section));
	assert(key != NULL && strlen(key));
	assert(value != NULL);
	assert(file !=NULL &&strlen(key));

	buf = (char *)sys_malloc(MAX_FILE_SIZE);
	w_buf = (char *)sys_malloc(MAX_FILE_SIZE);
	memset(buf,0,MAX_FILE_SIZE);
	memset(w_buf,0,MAX_FILE_SIZE);

	if(!load_ini_file(file,buf,&file_size))
	{
		sec_s = -1;
	}
	else
	{
		parse_file(section,key,buf,&sec_s,&sec_e,&key_s,&key_e,&value_s,&value_e);
	}

	if( -1 == sec_s)
	{
		if(0==file_size)
		{
			sprintf(w_buf,"[%s]\r\n%s=%s\r\n",section,key,value);
			new_file_size = strlen(section) + strlen(key) + strlen(value) + 5;
		}
		else
		{
			//not find the section, then add the new section at end of the file
			memcpy(w_buf,buf,file_size);
			sprintf(w_buf+file_size,"\r\n[%s]\r\n%s=%s\r\n",section,key,value);
			new_file_size = file_size + strlen(section) + strlen(key) + value_len + 7;
		}
	}
	else if(-1 == key_s)
	{
		//not find the key, then add the new key=value at end of the section
		memcpy(w_buf, buf, sec_e);
		sprintf(w_buf + sec_e, "%s=%s\r\n", key, value);
		memcpy(w_buf + sec_e + strlen(key) + value_len + 3,buf + sec_e, file_size - sec_e);
		new_file_size = file_size + strlen(key) + value_len + 3;
	}
	else
	{
		//update value with new value
		memcpy(w_buf, buf, value_s);
		memcpy(w_buf + value_s, value, value_len);
		memcpy(w_buf+value_s+value_len, buf+value_e, file_size - value_e);
		new_file_size = file_size - value_e + value_len + value_s;
	}

	FIL file_obj;
	unsigned int br;

	if (f_open(&file_obj, file, FA_WRITE)) {
		sys_free(buf);
		sys_free(w_buf);
		return 0;
	}

	if (f_write(&file_obj, w_buf, new_file_size, &br)) {
		sys_free(buf);
		sys_free(w_buf);
		return 0;
	}

	if (f_truncate(&file_obj)) {		/* Truncate unused area */
		sys_free(buf);
		sys_free(w_buf);
		return 0;
	}

	f_close(&file_obj);

	sys_free(buf);
	sys_free(w_buf);
	return 1;
}
Beispiel #24
0
/*********************************************************************************************************************
** Function name:           main
** Descriptions:            
** Input parameters:        
** Output parameters:       
** Returned value:          ==OS_OK : 操作成功
**                          !=OS_OK : 操作失败(包含出错信息)
**--------------------------------------------------------------------------------------------------------------------
** Created by:              Fengliang
** Created Date:            2011-5-16  13:23:42
** Test recorde:            
**--------------------------------------------------------------------------------------------------------------------
** Modified by:
** Modified date:
** Test recorde: 
*********************************************************************************************************************/
int main(int argc, _TCHAR* argv[]) 
{ 
    char aWriteBuffer[] = "精诚服务,真诚永远!——源于China";              	/* 文件内容                             */
    char aReadBuffer[1024];

    FATFS   fs[1];                                                          /* Work area for logical drives         */
    FRESULT Status;                                                         /* 操作状态                             */
    FIL     SrcFile, DstFile;                                               /* file objects                         */
    UINT    ReadCounter, WriteCounter;                                      /* File read counter                    */


    /*
     * 1) Register work area for each volume (Always succeeds regardless of disk status)
     */
    f_mount(0, &fs[0]);

#if 0
    f_mkfs(0, 1, 512);
#endif

    /*
     * 2) 创建目录.
     */
    f_mkdir("0:ChinaOS");


    /* 
     * 3) 打开文件 on the drive 0
     */
    Status = f_open(&SrcFile, "0:hello.txt", FA_OPEN_EXISTING | FA_READ);
    if (OS_OK != Status)
    {
        printf("Could not find the src file\n");
    }

    Status = f_open(&DstFile, "0:ChinaOS中国操作系统.txt", FA_CREATE_ALWAYS | FA_WRITE);
    if (OS_OK != Status)
    {
        printf("Could not find the dest file\n");
    }

    /*
     * 4) 复制文件数据.
     */
    while (1)
    {
        Status = f_read(&SrcFile, aReadBuffer, sizeof(aReadBuffer), &ReadCounter);
        if (OS_OK != Status || ReadCounter == 0)
        {
            break;                                                          /* error or eof                         */
        }

        /* Copy source to destination */
        Status = f_write(&DstFile, aReadBuffer, ReadCounter, &WriteCounter);
        if (OS_OK != Status || WriteCounter < ReadCounter) 
        {
            break;                                                          /* error or disk full                   */
        }
    }

    /*
     * 5) Close open files
     */
    f_close(&SrcFile);
    f_close(&DstFile);
    
    /*
     * 6) Unregister work area prior to discard it.
     */
    f_unmount(0);

    return 0; 
}
/**
  * @brief  Files operations: Read/Write and compare
  * @param  None
  * @retval None
  */
void MSC_File_Operations(void)
{
  uint16_t bytesread;

  /* Register the file system object to the FatFs module */
  if(f_mount(&USBH_fatfs, "", 0) != FR_OK)
  {
    LCD_ErrLog("Cannot Initialize FatFs! \n");
  }
  else
  {
    LCD_UsrLog("INFO : FatFs Initialized \n");

    if(f_open(&MyFile, "0:USBHost.txt",FA_CREATE_ALWAYS | FA_WRITE) != FR_OK)
    {
      LCD_ErrLog("Cannot Open 'USBHost.txt' file \n");
    }
    else
    {
      LCD_UsrLog("INFO : 'USBHost.txt' opened for write  \n");
      res= f_write (&MyFile, wtext, sizeof(wtext), (void *)&bytesWritten);
      f_close(&MyFile);

      if((bytesWritten == 0) || (res != FR_OK)) /*EOF or Error*/
      {
        LCD_ErrLog("Cannot Write on the  'USBHost.txt' file \n");
      }
      else
      {
        if(f_open(&MyFile, "0:USBHost.txt", FA_READ) != FR_OK)
        {
          LCD_ErrLog("Cannot Open 'USBHost.txt' file for read.\n");
        }
        else
        {
          LCD_UsrLog("INFO : Text written on the 'USBHost.txt' file \n");

          res = f_read(&MyFile, rtext, sizeof(rtext), (void *)&bytesread);

          if((bytesread == 0) || (res != FR_OK)) /*EOF or Error*/
          {
            LCD_ErrLog("Cannot Read from the  'USBHost.txt' file \n");
          }
          else
          {
            LCD_UsrLog("Read Text : \n");
            LCD_DbgLog((char *)rtext);
            LCD_DbgLog("\n");
          }
          f_close(&MyFile);
        }
        /* Compare read data with the expected data */
        if((bytesread == bytesWritten))
        {
          LCD_UsrLog("INFO : FatFs data compare SUCCES");
          LCD_UsrLog("\n");
        }
        else
        {
          LCD_ErrLog("FatFs data compare ERROR");
          LCD_ErrLog("\n");
        }
      }
    }
  }
}
Beispiel #26
0
/*******************************************************************************
* Function Name  : main
* Description    : Main program.
* Input          : None
* Output         : None
* Return         : None
*******************************************************************************/
int SD_Test(void)
{
    u16 i;
	FIL file;
	char data[512];
	UINT number=0;
	char *s="hello,lightjpu\n";

    //Init_Device();
    //RTC_Start();
    SPI_Configuration();

    res = f_mount(0, &fs);

    //res = f_mkfs(0,0,0);
    // if(res!=FR_OK)
   // {
//		while(1);
   // }
	
    res = f_open(&file, "data.txt", FA_CREATE_ALWAYS | FA_READ | FA_WRITE);
    
    if(res!=FR_OK)
    {
		while(1);
    }
    
    for(i=0;i<512;i++)
	{
		data[i] = 0x38;
	}

	res = f_write(&file, data, 512, &number);
	if(res!=FR_OK)
    {
		while(1);
    }
	
    while(1)
    {
        //if(fgets(data, sizeof(data), &file)==NULL)
        //{
            break;
        //}
        //prints(data);
    }

    f_close(&file);

     
   // write_time = Time_GetUnixTime();                            
    res = f_open(&file, "331.txt", FA_CREATE_ALWAYS | FA_WRITE);
    for(i=0;i<3;i++)                                            
    {                                                           
        res = f_write(&file, s, 14, &br);                   
        if(br<14)  //判断是否磁盘写满                          
        {                                                       
            break;                                              
        }                                                       
    }                                                           
   // write_time = Time_GetUnixTime() - write_time;               
        f_close(&file);                                         
    



    SD_PWR_OFF();
    while(1)
    {
        
        /* 
        if(TimeDisplay)                                                           
        {                                                                         
            current_time = Time_GetUnixTime();                                    
            time_now = Time_GetCalendarTime();                                    
                                                                                  
            USART_SendData(USART1, 0x0c);                                         
            while(USART_GetFlagStatus(USART1, USART_FLAG_TC)==RESET);             
                                                                                  
            printf("\r\nUNIX时间:%d", current_time);                             
            printf("\t当前时间:%d-%d-%d %d %02d:%02d:%02d\t", time_now.tm_year, \
                   time_now.tm_mon+1, time_now.tm_mday, time_now.tm_wday+1,\      
                   time_now.tm_hour, time_now.tm_min, time_now.tm_sec);           
            TimeDisplay = 0;                                                      
        }                                                                         
        */
        
    }
}
Beispiel #27
0
static void save(int quick) {
	int i;
	int n;
	int b;
	char hgz[256];
	char tmp[256];
	char bak[256];
	char bkp[256];
	time_t now;
	struct tm *tms;
	static int lastbak = -1;

	_dprintf("%s: quick=%d\n", __FUNCTION__, quick);

	f_write("/var/lib/misc/cstats-stime", &save_utime, sizeof(save_utime), 0, 0);

	n = save_history_from_tree(history_fn);
	_dprintf("%s: saved %d records from tree on file %s\n", __FUNCTION__, n, history_fn);

	_dprintf("%s: write source=%s\n", __FUNCTION__, save_path);
	f_write_string(source_fn, save_path, 0, 0);

	if (quick) {
		return;
	}

	sprintf(hgz, "%s.gz", history_fn);

	if (save_path[0] != 0) {
		strcpy(tmp, save_path);
		strcat(tmp, ".tmp");

		for (i = 15; i > 0; --i) {
			if (!wait_action_idle(10)) {
				_dprintf("%s: busy, not saving\n", __FUNCTION__);
			}
			else {
				_dprintf("%s: cp %s %s\n", __FUNCTION__, hgz, tmp);
				if (eval("cp", hgz, tmp) == 0) {
					_dprintf("%s: copy ok\n", __FUNCTION__);

					if (!nvram_match("rstats_bak", "0")) {
						now = time(0);
						tms = localtime(&now);
						if (lastbak != tms->tm_yday) {
							strcpy(bak, save_path);
							n = strlen(bak);
							if ((n > 3) && (strcmp(bak + (n - 3), ".gz") == 0)) n -= 3;
//							sprintf(bak + n, "_%d.bak", ((tms->tm_yday / 7) % 3) + 1);
//							if (eval("cp", save_path, bak) == 0) lastbak = tms->tm_yday;
							strcpy(bkp, bak);
							for (b = HI_BACK-1; b > 0; --b) {
								sprintf(bkp + n, "_%d.bak", b + 1);
								sprintf(bak + n, "_%d.bak", b);
								rename(bak, bkp);
							}
							if (eval("cp", "-p", save_path, bak) == 0) lastbak = tms->tm_yday;
						}
					}

					_dprintf("%s: rename %s %s\n", __FUNCTION__, tmp, save_path);
					if (rename(tmp, save_path) == 0) {
						_dprintf("%s: rename ok\n", __FUNCTION__);
						break;
					}
				}
			}

			// might not be ready
			sleep(3);
			if (gotterm) break;
		}
	}
}
Beispiel #28
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();
  }
}
Beispiel #29
0
/*******************************************************************************
* Function Name  : main.
* Description    : Main routine.
* Input          : None.
* Output         : None.
* Return         : None.
*******************************************************************************/
int main(void)
{

boolean_t  Success = TRUE;

/* ================================================================ */
/* Board Initializations and Configurations except OLED             */
/* (clocks, I/Os, on-chip peripherals, on-board ICs)                */
/* ================================================================ */

   LBF_Board_Fixed_Inits();
   LBF_Board_Selective_Inits(); 
             // actions driven by User_Configuration.h

   Stm32_Led_ON();

/* ================================================================ */
/* Optional initialization of Middleware libraries :                */
/* USBD drivers, FatFS File System, STemWin GUI                     */
/* ================================================================ */

    // UNCOMMENT AS NEEDED:
    // (refer to INFO.txt for details on actions performed)

    /* ... To use La BlueFrog as USB Mass Storage (Full Speed)      */
    //Delay_ms(1000);
    //Success &= LBF_LaunchUSB_MassStorage();  

    /* ... To initialize FatFS                                      */
    /*     and mount the Data Flash as FAT File System              */
    Success &= LBF_FatFS_Init();

    /* ... To initialize the STemWin Graphical Library              */ 
    /*     Caution: reserves some RAM - keep some for stack/heap    */
    // Success &= LBF_emWin_Init();

    // ERROR HANDLER
    /* Replace by your own as wished */
    Led_StopNBlinkOnFalse (Success);
    	// stops here if one of above inits has failed

    Stm32_Led_OFF();


/* ===================================================== */
/* Application Code Below */
/* ===================================================== */

// NOTE: Here, as Data Flash may not be formatted yet,
//  we don't use LBF_LaunchUSB_MassStorage in the initalization phase above


/* ==  User Declarations =============================== */

    FIL MyFile;    /* FatFS File object */
    UINT bw;       /* Number of bytes written in file */


/* ==  Body     ======================================== */

     Stm32_Led_ON();
    // Launch reformat only when any Push Button pressed
    while ( !State_Switch1_IsOn() && !State_Switch2_IsOn() );

    Stm32_Led_OFF();

    /* Create FAT volume with default cluster size */
    Success &= ( f_mkfs("", 0, 0) == FR_OK); 

    /* Create a file as new */
    Success &= ( f_open(&MyFile, "FS_Formt.log", FA_CREATE_NEW | FA_WRITE) == FR_OK);

    /* Write a message */
    Success &= ( f_write(&MyFile, "Formatted by FatFS\r\n", 20, &bw)  == FR_OK);

    /* Close the file */
    f_close(&MyFile);
 
    // Launch USB
    Success &= LBF_LaunchUSB_MassStorage();  

    /* Error handler */
    Led_StopNBlinkOnFalse (Success);


  // Done !
  Stm32_Led_ON();
  while (1);

    
}
Beispiel #30
-1
int notmain (void)
{
	FRESULT rc;				/* Result code */
	DIR dir;				/* Directory object */
	FILINFO fno;			/* File information object */
	UINT br ;

	bcm2835_uart_begin();

	f_mount(0, &Fatfs);		/* Register volume work area (never fails) */

#if 1
	printf("\r\nOpen an existing file (rainbowcircle.ild).\r\n");
	rc = f_open(&Fil, "rainbowcircle.ild", FA_READ);
	if (rc) die(rc);


	for (;;) {
		uint32_t i1 = bcm2835_st_read();
		rc = f_read(&Fil, Buff, 20, &br);	/* Read a chunk of file */
		uint32_t i2 = bcm2835_st_read();
		if (rc || !br) break;			/* Error or end of file */
		printf("br [%d] i2-i1 [%d]\n", br, (int)(i2-i1));
	}
	if (rc) die(rc);

	printf("\r\nClose the file.\r\n");
	rc = f_close(&Fil);
	if (rc) die(rc);
#endif
#if 0
	printf("\r\nCreate a new file (hello.txt).\r\n");
	rc = f_open(&Fil, "HELLO.TXT", FA_WRITE | FA_CREATE_ALWAYS);
	if (rc) die(rc);

	printf("\r\nWrite a text data. (Hello world!)\r\n");
	rc = f_write(&Fil, "Hello world!\r\n", 14, &bw);
	if (rc) die(rc);
	printf("%u bytes written.\r\n", bw);

	printf("\r\nClose the file.\r\n");
	rc = f_close(&Fil);
	if (rc) die(rc);
#endif
	printf("\r\nOpen root directory.\r\n");
	rc = f_opendir(&dir, "");
	if (rc) die(rc);

	char filename_buf[32];

	printf("\r\nDirectory listing...\r\n");
	for (;;) {
		fno.lfname = filename_buf;
		fno.lfsize = sizeof(filename_buf);
		rc = f_readdir(&dir, &fno);		/* Read a directory item */
		if (rc || !fno.fname[0]) break;	/* Error or end of dir */
		if (fno.fattrib & AM_DIR)
			printf("   <dir>  %s\r\n", fno.fname);
		else {
			char * fn = *fno.lfname ? fno.lfname : fno.fname;
			printf("%8lu  %s\r\n", fno.fsize, (char *) fn);
		}
	}
	if (rc) die(rc);

	printf("\nTest completed.\n");

	die(0);

	return 0;

}