Esempio n. 1
0
/**
  * @brief  Open a file and display it on lcd
  * @param  DirName: the Directory name to open
  * @param  FileName: the file name to open
  * @param  BufferAddress: A pointer to a buffer to copy the file to
  * @param  FileLen: the File length
  * @retval err: Error status (0=> success, 1=> fail)
  */
uint32_t Storage_OpenReadFile(uint8_t Xpoz, uint16_t Ypoz, const char *BmpName)
{
  uint32_t size = 0;
  FIL bmpfile;
  uint32_t nbline;
  BmpHeader* pbmpheader = (BmpHeader*)aBuffer;
  
  /* Close a bmp file */
  f_open(&bmpfile, BmpName, FA_READ);
  
  /* Read the constant part of the header from the file and store it at the top of aBuffer*/
  f_read(&bmpfile, &aBuffer, BITMAP_HEADER_SIZE, &BytesRead);
  
  /* Get the size of the data stored inside the file */
  size = pbmpheader->fsize - pbmpheader->offset;
  
  /* Start reading at the top of the file */
  f_lseek(&bmpfile, 0);
  
  /* Read the entire header from the file and store it at the top of aBuffer */
  f_read(&bmpfile, &aBuffer, pbmpheader->offset, &BytesRead);
  
  /* Compute the number of entire lines which can be stored inside the buffer */
  nbline = (BITMAP_BUFFER_SIZE - pbmpheader->offset + BITMAP_HEADER_SIZE)/(pbmpheader->w * 2);
  
  /* As long as the entire bitmap file as not been displayed */
  do
  {
    uint32_t nbbytetoread;
    
    /* Get the number of bytes which can be stored inside the buffer */
    nbbytetoread = MIN(size,nbline*pbmpheader->w*2);
  
    /* Adapt the total size of the bitmap, stored inside the header, to this chunck */
    pbmpheader->fsize = pbmpheader->offset + nbbytetoread;
  
    /* Adapt the number of line, stored inside the header, to this chunck */
    pbmpheader->h = nbbytetoread/(pbmpheader->w*2);
    
    /* Start reading at the end of the file */
    f_lseek(&bmpfile, pbmpheader->offset + size - nbbytetoread);
    
    /* Store this chunck (or the entire part if possible) of the file inside a buffer */
    f_read(&bmpfile, aBuffer + pbmpheader->offset, nbbytetoread, &BytesRead);
  
    /* Draw the bitmap */
    BSP_LCD_DrawBitmap(Xpoz, Ypoz, aBuffer);    
      
    /* Update the remaining number of bytes to read */
    size -= nbbytetoread;
    
    /* Change the display position of the next bitmap */
    Ypoz += nbline;
      
  }while (size > 0);
  
  /* Close the bmp file */
  f_close(&bmpfile);
  
  return 0;
}      
Esempio n. 2
0
const pm_char * bmpLoad(uint8_t *bmp, const char *filename, const xcoord_t width, const uint8_t height)
{
  FIL bmpFile;
  UINT read;
  uint8_t palette[16];
  uint8_t bmpBuf[LCD_W]; /* maximum with LCD_W */
  uint8_t *buf = &bmpBuf[0];

  if (width > LCD_W) {
    return STR_INCOMPATIBLE;
  }

  FRESULT result = f_open(&bmpFile, filename, FA_OPEN_EXISTING | FA_READ);
  if (result != FR_OK) {
    return SDCARD_ERROR(result);
  }

  if (f_size(&bmpFile) < 14) {
    f_close(&bmpFile);
    return STR_INCOMPATIBLE;
  }

  result = f_read(&bmpFile, buf, 14, &read);
  if (result != FR_OK || read != 14) {
    f_close(&bmpFile);
    return SDCARD_ERROR(result);
  }

  if (buf[0] != 'B' || buf[1] != 'M') {
    f_close(&bmpFile);
    return STR_INCOMPATIBLE;
  }

  uint32_t fsize  = *((uint32_t *)&buf[2]);
  uint32_t hsize  = *((uint32_t *)&buf[10]); /* header size */

  uint32_t len = limit((uint32_t)4, (uint32_t)(hsize-14), (uint32_t)32);
  result = f_read(&bmpFile, buf, len, &read);
  if (result != FR_OK || read != len) {
    f_close(&bmpFile);
    return SDCARD_ERROR(result);
  }

  uint32_t ihsize = *((uint32_t *)&buf[0]); /* more header size */

  /* invalid header size */
  if (ihsize + 14 > hsize) {
    f_close(&bmpFile);
    return STR_INCOMPATIBLE;
  }

  /* sometimes file size is set to some headers size, set a real size in that case */
  if (fsize == 14 || fsize == ihsize + 14)
    fsize = f_size(&bmpFile) - 2;

  /* declared file size less than header size */
  if (fsize <= hsize) {
    f_close(&bmpFile);
    return STR_INCOMPATIBLE;
  }

  uint32_t w, h;

  switch (ihsize){
    case  40: // windib
    case  56: // windib v3
    case  64: // OS/2 v2
    case 108: // windib v4
    case 124: // windib v5
      w  = *((uint32_t *)&buf[4]);
      h = *((uint32_t *)&buf[8]);
      buf += 12;
      break;
    case  12: // OS/2 v1
      w  = *((uint16_t *)&buf[4]);
      h = *((uint16_t *)&buf[6]);
      buf += 8;
      break;
    default:
      f_close(&bmpFile);
      return STR_INCOMPATIBLE;
  }

  if (*((uint16_t *)&buf[0]) != 1) { /* planes */
    f_close(&bmpFile);
    return STR_INCOMPATIBLE;
  }

  if (w > width || h > height) {
    f_close(&bmpFile);
    return STR_INCOMPATIBLE;
  }

  uint16_t depth = *((uint16_t *)&buf[2]);

  buf = &bmpBuf[0];

  if (depth == 4) {
    if (f_lseek(&bmpFile, hsize-64) != FR_OK || f_read(&bmpFile, buf, 64, &read) != FR_OK || read != 64) {
      f_close(&bmpFile);
      return SDCARD_ERROR(result);
    }
    for (uint8_t i=0; i<16; i++) {
      palette[i] = buf[4*i] >> 4;
    }
  }
  else {
    if (f_lseek(&bmpFile, hsize) != FR_OK) {
static BaseType_t prvTYPECommand( char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString )
{
const char *pcParameter;
BaseType_t xParameterStringLength, xReturn = pdTRUE;
static F_FILE *pxFile = NULL;
int iChar;
size_t xByte;
size_t xColumns = 50U;

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

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

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

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

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

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

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

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

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

	strcat( pcWriteBuffer, cliNEW_LINE );

	return xReturn;
}
Esempio n. 4
0
void read_config (void)
{
  char line[80];
  char *pToken;
  char *pLine;
  unsigned j;

  // first set defaults
  for (j=0; j < NUM_TOKENS; j++)
  {
    switch (config_lookup[j].type)
    {
      case TYPE_INT:
      {
        int32_t *pVal = config_lookup[j].pValue;
        *pVal = config_lookup[j].val_i;
        break;
      }
      case TYPE_DOUBLE:
      {
        double *pVal = config_lookup[j].pValue;
        *pVal = config_lookup[j].val_d;
        break;
      }
    }
  }
    
  /* initialize SPI for SDCard */
  spi_init();

  /* access to "config.txt" file on SDCard */

  FATFS fs;       /* Work area (file system object) for logical drive */
  FIL file;       /* file object */
  FRESULT res;    /* FatFs function common result code */

  /* Register a work area for logical drive 0 */
  res = f_mount(0, &fs);
  if(res)
    debug("Err mount fs\n");
  
  /* Open config.txt file */
  res = f_open(&file, "config.txt", FA_OPEN_EXISTING | FA_READ);
  if (res)
    debug("File config.txt not found\n");
  else
  {
    bool    found;

    pLine = f_gets(line, sizeof(line), &file); /* read one line */
    while (pLine)
    {
      pToken = get_token (pLine);
      if (pToken && *pToken != '#')
      {
        found = false;      
        for (j=0; (j < NUM_TOKENS) && !found; j++)
        {
          if (stricmp (pToken, config_lookup[j].name) == 0)
          {
            found = true;
            pToken = get_token (NULL);
            if (pToken && (*pToken == '='))
            {
              // get value
              pToken = get_token (NULL);
            
              if (pToken)
              {
                switch (config_lookup[j].type)
                {
                  case TYPE_INT:
                  {
                    int32_t *pVal = config_lookup[j].pValue;
                    *pVal = atoi (pToken);
                    break;
                  }
                  case TYPE_DOUBLE:
                  {
                    double *pVal = config_lookup[j].pValue;
                    *pVal = atod(pToken);
                    break;
                  }
                }
                // debug  
                //sersendf ("Found: %s = %d\r\n", config_lookup[j].name, *config_lookup[j].pValue);
              }
              else
                sersendf ("Missing value for %s\r\n", config_lookup[j].name);
              
            }
            else
              sersendf ("Expected '='%s\r\n", line);              
          }
        }
        
        if (!found)
          sersendf ("Unknown config: %s\r\n", pToken);
      }
      
      pLine = f_gets(line, sizeof(line), &file); /* read next line */
    }

    /* Close config.txt file */
    res = f_close(&file);
    if (res)
      debug("Error closing config.txt\n");
  }

  //
  //read_gcode_file ("autoexec.g");
  
  res = f_open(&file, "autoexec.g", FA_OPEN_EXISTING | FA_READ);
  if (res == FR_OK)
  {
    tLineBuffer line_buf;
    
    pLine = f_gets(line_buf.data, sizeof(line_buf.data), &file); /* read one line */
    while (pLine)
    {
      line_buf.len = strlen(pLine);
      gcode_parse_line (&line_buf);
      pLine = f_gets(line_buf.data, sizeof(line_buf.data), &file); /* read next line */
    }

    /* Close file */
    res = f_close(&file);
    if (res)
      debug("Error closing autoexec.g\n");
  }  
  
  // 
  
  /* Initialize using values read from "config.txt" file */
  gcode_parse_init();

}
Esempio n. 5
0
/**
 * This function is used to release the sd settings
 *
 * @param	None
 *
 * @return	None
 *
 *****************************************************************************/
u32 XFsbl_SdRelease(void )
{
	(void )f_close(&fil);

	return XFSBL_SUCCESS;
}
Esempio n. 6
0
/**
  * @brief  Main program
  * @param  None
  * @retval None
  */
int main(void)
{
  FRESULT res;                                          /* FatFs function common result code */
  uint32_t byteswritten, bytesread;                     /* File write/read counts */
  uint8_t wtext[] = "This is STM32 working with FatFs"; /* File write buffer */
  uint8_t rtext[100];                                   /* File read buffer */
  
  /* 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 180 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)
  {
  }
}
Esempio n. 7
0
/*******************************************************************************
* Function Name  : SD_Close
* Description    : Close a Writing Session 
* Input          : None
* Output         : None
* Return         : None
*******************************************************************************/
void SD_Close(void)
{
	/* close card and umount */
	f_close(&file); // close the file
	ret = f_mount(0,NULL);	// unmount
}
static void adc_common_config(int argc, char** argv, int8_t *endpoint_id)
{
    FRESULT f_res;
    FIL fil;
    uint8_t pattern_size = sizeof(ha_host_ns::adc_dev_config_pattern);
    char f_name[4];

    *endpoint_id = -1;
    char port = '0';
    uint16_t pin = 0;
    uint16_t adc_x = 0;
    uint16_t channel = 0;

    char config_str[pattern_size];

    if (argc <= 1) {
        printf("ERR: too few argument. Try -h to get help.\n");
        return;
    }

    /* Read all configuration from shell */
    for (uint8_t count = 1; count < argc; count++) {
        if (argv[count][0] == '-') {
            switch (argv[count][1]) {
            case 'h': //get help
                printf(adc_usage, argv[0]);
                return;
            case 'e': //set endpoint id
                count++;
                if (count >= argc) {
                    printf("ERR: too few argument. Try -h to get help.\n");
                    return;
                }
                /* save endpoint id */
                *endpoint_id = atoi(argv[count]);
                if (*endpoint_id < 0
                        || *endpoint_id > ha_host_ns::max_end_point) {
                    printf("ERR: invalid endpoint id value\n");
                    return;
                }
                /* get file name from ep id */
                snprintf(f_name, sizeof(f_name), "%x", *endpoint_id);
                /* open "ep id" file */
                f_res = f_open(&fil, f_name, FA_READ | FA_OPEN_ALWAYS);
                if (f_res != FR_OK) {
                    print_ferr(f_res);
                    return;
                }
                f_sync(&fil);
                UINT byte_read;
                f_res = f_read(&fil, config_str, pattern_size, &byte_read);
                if (f_res != FR_OK) {
                    print_ferr(f_res);
                    f_close(&fil);
                    return;
                }
                f_close(&fil);
                sscanf(config_str, ha_host_ns::adc_dev_config_pattern, &port,
                        &pin, &adc_x, &channel);
                break;
            case 'p':
                count++;
                if (count >= argc) {
                    printf("ERR: too few argument. Try -h to get help.\n");
                    return;
                }
                if (!check_port(argv[count][0], &port)) {
                    printf("ERR: invalid port value.\n");
                    return;
                }
                break;
            case 'n':
                count++;
                if (count >= argc) {
                    printf("ERR: too few argument. Try -h to get help.\n");
                    return;
                }
                pin = atoi(argv[count]);
                if (pin < 0 || pin > 15) {
                    printf("ERR: invalid pin value\n");
                    return;
                }
                break;
            case 'a':
                count++;
                if (count >= argc) {
                    printf("ERR: too few argument. Try -h to get help.\n");
                    return;
                }
                adc_x = atoi(argv[count]);
                if (adc_x < 0 || adc_x > 3) {
                    printf("ERR: invalid adc value\n");
                    return;
                }
                break;
            case 'c':
                count++;
                if (count >= argc) {
                    printf("ERR: too few argument. Try -h to get help.\n");
                    return;
                }
                channel = atoi(argv[count]);
                if (channel < 0 || channel > 15) {
                    printf("ERR: invalid channel value\n");
                    return;
                }
                break;
            default:
                printf("Unknown option.\n");
                return;
            }
        } else {
            printf("Unknown option.\n");
            return;
        }
    }

    if (*endpoint_id < 0) {
        printf("ERR: missing -e option.\n");
        return;
    }

    /* Write configurations to file */
    f_res = f_open(&fil, f_name, FA_WRITE | FA_CREATE_ALWAYS);
    if (f_res != FR_OK) {
        print_ferr(f_res);
        return;
    }
    f_sync(&fil);

    snprintf(config_str, pattern_size, ha_host_ns::adc_dev_config_pattern, port,
            pin, adc_x, channel);

    UINT byte_written;
    f_res = f_write(&fil, config_str, pattern_size, &byte_written);
    if (f_res != FR_OK) {
        print_ferr(f_res);
        f_close(&fil);
        return;
    }
    f_close(&fil);

    /* read back */
    f_res = f_open(&fil, f_name, FA_READ);
    if (f_res != FR_OK) {
        print_ferr(f_res);
        return;
    }
    f_sync(&fil);
    while (f_gets(config_str, sizeof(config_str), &fil)) {
        printf("%s", config_str);
    }
    f_close(&fil);

    return;
}
/**
*\brief This function copies the application image to the DDR by reading the
*       header info.\n
*
* \param - none.\n
*
* \return none.\n
*
*/
unsigned int HSMMCSDImageCopy(void)
{
    FRESULT fresult;
    unsigned short usBytesRead = 0;
    ti_header imageHdr;
    unsigned char *destAddr;
    char *fname = "/app";

    /*
    ** Open the file for reading.
    */
    fresult = f_open(&g_sFileObject, fname, FA_READ);

    /*
    ** If there was some problem opening the file, then return an error.
    */
    if(fresult != FR_OK)
    {
        UARTPuts("\r\n Unable to open application file\r\n", -1);
        return 0;
    }
    else
    {
        UARTPuts("Copying application image from MMC/SD card to RAM\r\n", -1);
        fresult = f_read(&g_sFileObject, (unsigned char *)&imageHdr, 8,&usBytesRead);
        if(fresult != FR_OK)
        {
            UARTPuts("\r\n Error reading application file\r\n", -1);
            return 0;
        }

        if(usBytesRead != 8)
        {
            return 0;
        }
        destAddr = (unsigned char*)imageHdr.load_addr;
        entryPoint = imageHdr.load_addr;
    }

    /*
    ** Enter a loop to repeatedly read data from the file and display it, until
    ** the end of the file is reached.
    */
    do
    {
        /*
        ** Read a block of data from the file.  Read as much as can fit in the
        ** temporary buffer, including a space for the trailing null.
        */
        fresult = f_read(&g_sFileObject, g_cTmpBuf, sizeof(g_cTmpBuf) - 1,&usBytesRead);

        /*
        ** If there was an error reading, then print a newline and return the
        ** error to the user.
        */
        if(fresult != FR_OK)
        {
            UARTPuts("\r\n Error reading application file\r\n", -1);
            return 0;
        }

        if(usBytesRead >= sizeof(g_cTmpBuf))
        {
            return 0;
        }

        /*
        ** Null terminate the last block that was read to make it a null
        ** terminated string that can be used with printf.
        */
        g_cTmpBuf[usBytesRead] = 0;

        /*
        ** Read the last chunk of the file that was received.
        */
        memcpy(destAddr, g_cTmpBuf, (sizeof(g_cTmpBuf) - 1));
        destAddr += (sizeof(g_cTmpBuf) - 1);
        /*
        ** Continue reading until less than the full number of bytes are read.
        ** That means the end of the buffer was reached.
        */
    }
    while(usBytesRead == sizeof(g_cTmpBuf) - 1);

    /*
    ** Close the file.
    */
    fresult = f_close(&g_sFileObject);

    /*
    ** Return success.
    */
    return 1;
}
void rgb_led_config(int argc, char** argv)
{
    FRESULT f_res;
    FIL fil;
    char f_name[4];
    uint8_t pattern_size = sizeof(ha_host_ns::rgb_config_pattern);

    int8_t ep_id = -1;
    uint8_t dev_type = (uint8_t) ha_ns::RGB_LED;

    char Rport = '0';
    uint16_t Rpin = 0;
    uint16_t Rtimer_x = 0;
    uint16_t Rchannel = 0;

    char Gport = '0';
    uint16_t Gpin = 0;
    uint16_t Gtimer_x = 0;
    uint16_t Gchannel = 0;

    char Bport = '0';
    uint16_t Bpin = 0;
    uint16_t Btimer_x = 0;
    uint16_t Bchannel = 0;

    uint16_t red_at_wp = 0;
    uint16_t green_at_wp = 0;
    uint16_t blue_at_wp = 0;

    char config_str[pattern_size];

    if (argc <= 1) {
        printf("ERR: too few argument. Try -h to get help.\n");
        return;
    }

    /* Read all configuration from shell */
    for (uint8_t count = 1; count < argc; count++) {
        if (argv[count][0] == '-') {
            switch (argv[count][1]) {
            case 'h': //get help
                printf(rgb_usage);
                return;
            case 'e': //set endpoint id
                count++;
                if (count >= argc) {
                    printf("ERR: too few argument. Try -h to get help.\n");
                    return;
                }
                /* save endpoint id */
                ep_id = atoi(argv[count]);
                if (ep_id < 0 || ep_id > ha_host_ns::max_end_point) {
                    printf("ERR: invalid endpoint id value\n");
                    return;
                }
                snprintf(f_name, sizeof(f_name), "%x", ep_id);
                f_res = f_open(&fil, f_name, FA_READ | FA_OPEN_ALWAYS);
                if (f_res != FR_OK) {
                    print_ferr(f_res);
                    return;
                }
                f_sync(&fil);
                UINT byte_read;
                f_res = f_read(&fil, config_str, pattern_size, &byte_read);
                if (f_res != FR_OK) {
                    print_ferr(f_res);
                    return;
                }
                f_close(&fil);
                sscanf(config_str, ha_host_ns::rgb_config_pattern, &Rport,
                        &Rpin, &Rtimer_x, &Rchannel, &Gport, &Gpin, &Gtimer_x,
                        &Gchannel, &Bport, &Bpin, &Btimer_x, &Bchannel,
                        &red_at_wp, &green_at_wp, &blue_at_wp);
                break;
            case 'R': //configure Red channel
                count++;
                if (count >= argc) {
                    printf("ERR: too few argument. Try -h to get help.\n");
                    return;
                }
                if (!check_port(argv[count][0], &Rport)) {
                    printf("ERR: invalid port value.\n");
                    return;
                }
                count++;
                if (count >= argc) {
                    printf("ERR: too few argument. Try -h to get help.\n");
                    return;
                }
                Rpin = atoi(argv[count]);
                if (Rpin < 0 || Rpin > 15) {
                    printf("ERR: invalid pin value\n");
                    return;
                }
                count++;
                if (count >= argc) {
                    printf("ERR: too few argument. Try -h to get help.\n");
                    return;
                }
                Rtimer_x = atoi(argv[count]);
                if (Rtimer_x < 0 || Rtimer_x > 8 || Rtimer_x == 6
                        || Rtimer_x == 7) {
                    printf("ERR: invalid timer value for pwm\n");
                    return;
                }
                count++;
                if (count >= argc) {
                    printf("ERR: too few argument. Try -h to get help.\n");
                    return;
                }
                Rchannel = atoi(argv[count]);
                if (Rchannel < 0 || Rchannel > 15) {
                    printf("ERR: invalid timer value\n");
                    return;
                }
                break;
            case 'G': //configure Green channel
                count++;
                if (count >= argc) {
                    printf("ERR: too few argument. Try -h to get help.\n");
                    return;
                }
                if (!check_port(argv[count][0], &Gport)) {
                    printf("ERR: invalid port value.\n");
                    return;
                }
                count++;
                if (count >= argc) {
                    printf("ERR: too few argument. Try -h to get help.\n");
                    return;
                }
                Gpin = atoi(argv[count]);
                if (Rpin < 0 || Rpin > 15) {
                    printf("ERR: invalid pin value\n");
                    return;
                }
                count++;
                if (count >= argc) {
                    printf("ERR: too few argument. Try -h to get help.\n");
                    return;
                }
                Gtimer_x = atoi(argv[count]);
                if (Gtimer_x < 0 || Gtimer_x > 8 || Gtimer_x == 6
                        || Gtimer_x == 7) {
                    printf("ERR: invalid timer value for pwm\n");
                    return;
                }
                count++;
                if (count >= argc) {
                    printf("ERR: too few argument. Try -h to get help.\n");
                    return;
                }
                Gchannel = atoi(argv[count]);
                if (Gchannel < 0 || Gchannel > 15) {
                    printf("ERR: invalid timer value\n");
                    return;
                }
                break;
            case 'B': //configure Blue channel
                count++;
                if (count >= argc) {
                    printf("ERR: too few argument. Try -h to get help.\n");
                    return;
                }
                if (!check_port(argv[count][0], &Bport)) {
                    printf("ERR: invalid port value.\n");
                    return;
                }
                count++;
                if (count >= argc) {
                    printf("ERR: too few argument. Try -h to get help.\n");
                    return;
                }
                Bpin = atoi(argv[count]);
                if (Rpin < 0 || Rpin > 15) {
                    printf("ERR: invalid pin value\n");
                    return;
                }
                count++;
                if (count >= argc) {
                    printf("ERR: too few argument. Try -h to get help.\n");
                    return;
                }
                Btimer_x = atoi(argv[count]);
                if (Btimer_x < 0 || Btimer_x > 8 || Btimer_x == 6
                        || Btimer_x == 7) {
                    printf("ERR: invalid timer value for pwm\n");
                    return;
                }
                count++;
                if (count >= argc) {
                    printf("ERR: too few argument. Try -h to get help.\n");
                    return;
                }
                Bchannel = atoi(argv[count]);
                if (Bchannel < 0 || Bchannel > 15) {
                    printf("ERR: invalid timer value\n");
                    return;
                }
                break;
            case 'C': //set calibrating factor
                count++;
                if (count >= argc) {
                    printf("ERR: too few argument. Try -h to get help.\n");
                    return;
                }
                red_at_wp = atoi(argv[count]);
                count++;
                if (count >= argc) {
                    printf("ERR: too few argument. Try -h to get help.\n");
                    return;
                }
                green_at_wp = atoi(argv[count]);
                count++;
                if (count >= argc) {
                    printf("ERR: too few argument. Try -h to get help.\n");
                    return;
                }
                blue_at_wp = atoi(argv[count]);
                if (red_at_wp > 100 || green_at_wp > 100 || blue_at_wp > 100) {
                    printf(
                            "ERR: invalid calibrating factor. Try -h to get help.\n");
                    return;
                }
                break;
            default:
                printf("Unknown option.\n");
                return;
            }
        } else {
            printf("Unknown option.\n");
            return;
        }
    }

    if (ep_id < 0) {
        printf("ERR: missing -e option.\n");
        return;
    }

    /* Write configurations to file */
    f_res = f_open(&fil, f_name, FA_WRITE | FA_CREATE_ALWAYS);
    if (f_res != FR_OK) {
        print_ferr(f_res);
        return;
    }
    f_sync(&fil);

    snprintf(config_str, pattern_size, ha_host_ns::rgb_config_pattern, Rport,
            Rpin, Rtimer_x, Rchannel, Gport, Gpin, Gtimer_x, Gchannel, Bport,
            Bpin, Btimer_x, Bchannel, red_at_wp, green_at_wp, blue_at_wp);

    UINT byte_written;
    f_res = f_write(&fil, config_str, pattern_size, &byte_written);
    if (f_res != FR_OK) {
        print_ferr(f_res);
        f_close(&fil);
        return;
    }
    f_close(&fil);

    /* read back */
    f_res = f_open(&fil, f_name, FA_READ);
    if (f_res != FR_OK) {
        print_ferr(f_res);
        return;
    }
    f_sync(&fil);
    while (f_gets(config_str, sizeof(config_str), &fil)) {
        printf("%s", config_str);
    }
    f_close(&fil);

    /* modify device list file */
    modify_dev_list_file(ep_id, dev_type);

    return;
}
void adc_sensor_config(int argc, char** argv)
{
    FRESULT f_res;
    FIL fil;
    char f_name[4];
    uint8_t pattern_size = sizeof(ha_host_ns::adc_sensor_config_pattern);
    uint8_t first_equa_type = 0;
    uint8_t first_params = 0;
    uint16_t num_params = 0;
    uint16_t num_equation = 0;

    int8_t ep_id = -1;
    int8_t specified_subtype = -1;

    char port = '0';
    uint16_t pin = 0;
    uint16_t adc_x = 0;
    uint16_t channel = 0;

    int filter_thres = 0;
    int under_thres = 0;
    int over_thres = 0;

    char config_str[pattern_size];

    if (argc <= 1) {
        printf("ERR: too few argument. Try -h to get help.\n");
        return;
    }

    /* Read all configuration from shell */
    for (uint8_t count = 1; count < argc; count++) {
        if (argv[count][0] == '-') {
            switch (argv[count][1]) {
            case 'h': //get help
                printf(adc_sensor_usage);
                return;
            case 's':
                count++;
                if (count >= argc) {
                    printf("ERR: too few argument. Try -h to get help.\n");
                    return;
                }
                specified_subtype = atoi(argv[count]);
                break;
            case 'e': //set endpoint id
                count++;
                if (count >= argc) {
                    printf("ERR: too few argument. Try -h to get help.\n");
                    return;
                }
                /* save endpoint id */
                ep_id = atoi(argv[count]);
                if (ep_id < 0 || ep_id > ha_host_ns::max_end_point) {
                    printf("ERR: invalid endpoint id value\n");
                    return;
                }
                snprintf(f_name, sizeof(f_name), "%x", ep_id);
                f_res = f_open(&fil, f_name, FA_READ | FA_OPEN_ALWAYS);
                if (f_res != FR_OK) {
                    print_ferr(f_res);
                    return;
                }
                f_sync(&fil);

                UINT byte_read;
                f_res = f_read(&fil, config_str, pattern_size, &byte_read);
                if (f_res != FR_OK) {
                    print_ferr(f_res);
                    f_close(&fil);
                    return;
                }
                f_close(&fil);
                sscanf(config_str, ha_host_ns::adc_sensor_config_pattern, &port,
                        &pin, &adc_x, &channel, &filter_thres, &under_thres,
                        &over_thres, &num_equation, &num_params);
                break;
            case 'p': //set port
                count++;
                if (count >= argc) {
                    printf("ERR: too few argument. Try -h to get help.\n");
                    return;
                }
                if (!check_port(argv[count][0], &port)) {
                    printf("ERR: invalid port value.\n");
                    return;
                }
                break;
            case 'n': //set pin
                count++;
                if (count >= argc) {
                    printf("ERR: too few argument. Try -h to get help.\n");
                    return;
                }
                pin = atoi(argv[count]);
                if (pin < 0 || pin > 15) {
                    printf("ERR: invalid pin value\n");
                    return;
                }
                break;
            case 'a': //set adc
                count++;
                if (count >= argc) {
                    printf("ERR: too few argument. Try -h to get help.\n");
                    return;
                }
                adc_x = atoi(argv[count]);
                if (adc_x < 0 || adc_x > 3) {
                    printf("ERR: invalid adc value\n");
                    return;
                }
                break;
            case 'c': //set channel
                count++;
                if (count >= argc) {
                    printf("ERR: too few argument. Try -h to get help.\n");
                    return;
                }
                channel = atoi(argv[count]);
                if (channel < 0 || channel > 15) {
                    printf("ERR: invalid channel value\n");
                    return;
                }
                break;
            case 't': //get equation type
                count++;
                if (count >= argc) {
                    printf("ERR: too few argument. Try -h to get help.\n");
                    return;
                }
                first_equa_type = count;
                num_equation = 0;
                while (count < argc && argv[count][0] != '-') {
                    num_equation++;
                    count++;
                }
                if (num_equation == 0) {
                    printf("ERR: missing parameters in -t option.\n");
                    return;
                }
                count--;
                break;
            case 'P':
                count++;
                if (count >= argc) {
                    printf("ERR: too few argument. Try -h to get help.\n");
                    return;
                }
                first_params = count;
                num_params = 0;
                while (count < argc) {
                    if (argv[count][0] == '-') {
                        if (!isdigit(argv[count][1])) {
                            break;
                        }
                    }
                    num_params++;
                    count++;
                }
                count--;
                break;
            case 'f':
                count++;
                if (count >= argc) {
                    printf("ERR: too few argument. Try -h to get help.\n");
                    return;
                }
                filter_thres = atoi(argv[count]);
                break;
            case 'u':
                count++;
                if (count >= argc) {
                    printf("ERR: too few argument. Try -h to get help.\n");
                    return;
                }
                under_thres = atoi(argv[count]);
                break;
            case 'o':
                count++;
                if (count >= argc) {
                    printf("ERR: too few argument. Try -h to get help.\n");
                    return;
                }
                over_thres = atoi(argv[count]);
                break;
            default:
                printf("Unknown option.\n");
                return;
            }
        } else {
            printf("Unknown option.\n");
            return;
        }
    }

    if (ep_id < 0) {
        printf("ERR: missing -e option.\n");
        return;
    }

    if (specified_subtype < 0) {
        printf("ERR: missing -s option.\n");
        return;
    }

    if (first_equa_type == 0 || first_params == 0) {
        printf("ERR: missing -t or -P option.\n");
        return;
    }

    f_res = f_unlink(f_name);
    if (f_res != FR_OK) {
        print_ferr(f_res);
        return;
    }

    /* Write configurations to file */
    f_res = f_open(&fil, f_name, FA_WRITE | FA_CREATE_ALWAYS);
    if (f_res != FR_OK) {
        printf("Error on opening file to write configuration\n");
        return;
    }
    f_sync(&fil);

    snprintf(config_str, pattern_size, ha_host_ns::adc_sensor_config_pattern,
            port, pin, adc_x, channel, filter_thres, under_thres, over_thres,
            num_equation, num_params);
    f_puts(config_str, &fil);
    f_sync(&fil);

    for (uint8_t count = first_equa_type;
            count < first_equa_type + num_equation; count++) {
        snprintf(config_str, pattern_size, ha_host_ns::sensor_equa_type,
                argv[count][0]);
        f_puts(config_str, &fil);
        f_sync(&fil);
    }

    float param = 0.0f;
    for (uint8_t count = first_params; count < first_params + num_params;
            count++) {
        param = strtof(argv[count], NULL);
        snprintf(config_str, pattern_size, ha_host_ns::sensor_equa_params,
                param);
        f_puts(config_str, &fil);
        f_sync(&fil);
    }
    f_close(&fil);

    /* read back */
    f_res = f_open(&fil, f_name, FA_READ);
    if (f_res != FR_OK) {
        print_ferr(f_res);
        return;
    }
    f_sync(&fil);
    while (f_gets(config_str, sizeof(config_str), &fil)) {
        printf("%s", config_str);
    }
    f_close(&fil);

    /* modify device list file */
    modify_dev_list_file(ep_id,
            combine_dev_type(ha_ns::ADC_SENSOR, (uint8_t) specified_subtype));

    return;
}
Esempio n. 12
0
void file_close() {
  file_res = f_close(&file_handle);
}
Esempio n. 13
0
/*------------------------------------------------------------
 * Function Name  : SD_UpdateExecute
 * Description    : 执行SD卡升级
 * Input          : None
 * Output         : None
 * Return         : None
 *------------------------------------------------------------*/
ErrorStatus SD_UpdateExecute( uint16_t x, uint16_t y )
{
	FIL file_obj;
	FRESULT fresult;
	uint32_t br = 0;
	uint32_t addr = 0;
	uint32_t process = 0;
	uint32_t f_size = 0;
	uint8_t update_buff[UPDATE_ONCE_READ];
	char buff[10];
	char Update_name[50];
	uint8_t last_process = 100;
	
	strcpy(Update_name,SD_UPDATE_FILE_APPEND_PATH);
	strcat(Update_name,Name_buff);
	
	fresult = f_open(&file_obj,Update_name,FA_OPEN_EXISTING|FA_READ);
	if (fresult != FR_OK)
	{
		f_close(&file_obj);
		lcd_font24(x,y,COLOR_POINT,COLOR_BACK,"> 打开文件错误!",UPDATE_FONT);
		return ERROR;
	}
	
	f_size = file_obj.fsize;
	
	do
	{
		fresult = f_read(&file_obj,update_buff,UPDATE_ONCE_READ,&br); 
		
		if ((fresult != FR_OK) || (br > UPDATE_ONCE_READ))
		{
			f_close(&file_obj);
			lcd_font24(x,y,COLOR_POINT,COLOR_BACK,"> 读取文件错误!",UPDATE_FONT);
			return ERROR;
		}
		
		if (ERROR == SD_ProgramFlashOperation(update_buff,addr,br))
		{
			f_close(&file_obj);
			lcd_font24(x,y,COLOR_POINT,COLOR_BACK,"> 写入flash数据错误!",UPDATE_FONT);
			return ERROR;
		}
		
		process = (float)addr / f_size * 100;		
		if (((process % 5) == 0) && (last_process != process))
		{
			last_process = process;
			lcd_font24(x,y,COLOR_POINT,COLOR_BACK,"-",UPDATE_FONT);
			x += 12;
			usprintf(buff,"%3d%%",process);
			lcd_font24(x,y,COLOR_POINT,COLOR_BACK,buff,UPDATE_FONT);
		}
		
		addr += br;
		
	}while (br != 0);
		
	fresult = f_close(&file_obj);
	
	return SUCCESS;
}
Esempio n. 14
0
/**
  * @brief  Open a file and copy its content to a buffer
  * @param  DirName: the Directory name to open
  * @param  FileName: the file name to open
  * @param  BufferAddress: A pointer to a buffer to copy the file to
  * @param  FileLen: the File lenght
  * @retval err: Error status (0=> success, 1=> fail)
  */
uint32_t Storage_OpenReadFile(uint8_t *Address, const char* BmpName)
{
  uint32_t index = 0, size = 0, i1 = 0;
  uint32_t BmpAddress;
  FIL F1;

  if (f_open(&F1, (TCHAR const*)BmpName, FA_READ) != FR_OK)
  {
    while(1)
    {
    } 
  }
  if (f_read (&F1, sector, 30, (UINT *)&BytesRead) != FR_OK)
  {
    while(1)
    {
    } 
  }
  
  BmpAddress = (uint32_t)sector;

  /* Read bitmap size */
  size = *(uint16_t *) (BmpAddress + 2);
  size |= (*(uint16_t *) (BmpAddress + 4)) << 16;  
 
  /* Get bitmap data address offset */
  index = *(uint16_t *) (BmpAddress + 10);
  index |= (*(uint16_t *) (BmpAddress + 12)) << 16;  
  
  f_close (&F1);
  
  f_open (&F1, (TCHAR const*)BmpName, FA_READ);

  do
  {
    if (size < 256*2)
    {
      i1 = size;
    }
    else
    {
      i1 = 256*2;
    }
    size -= i1;
    f_read (&F1, sector, i1, (UINT *)&BytesRead);

    for (index = 0; index < i1; index++)
    {
      *(__IO uint8_t*) (Address) = *(__IO uint8_t *)BmpAddress;
      
      BmpAddress++;  
      Address++;
    }  
    
    BmpAddress = (uint32_t)sector;
  }
  while (size > 0);

  f_close (&F1);
  
  return 1;
}
Esempio n. 15
0
/*
 ************************************************************************
 *
 * This is the next part if the initialization sequence: we are now
 * running from RAM and have a "normal" C environment, i. e. global
 * data can be written, BSS has been cleared, the stack size in not
 * that critical any more, etc.
 *
 ************************************************************************
 */
void board_init_r(gd_t *id, ulong dest_addr)
{
	char *s;
	//bd_t *bd;
	ulong malloc_start;
#ifdef CONFIG_NONCACHE_MEMORY
	uint  malloc_noncache_start;
#endif
#if !defined(CONFIG_SYS_NO_FLASH)
	ulong flash_size;
#endif
	int workmode;
	int ret;
#ifdef CONFIG_SUNXI_HDCP_IN_SECURESTORAGE
	int hdcpkey_enable=0;
#endif
	gd = id;
	//bd = gd->bd;

	gd->flags |= GD_FLG_RELOC;	/* tell others: relocation done */

	monitor_flash_len = _end_ofs;

	malloc_start = dest_addr - TOTAL_MALLOC_LEN - sizeof(struct spare_boot_head_t);
#ifdef CONFIG_NONCACHE_MEMORY_SIZE
	malloc_start &= (~(0x00100000 -1));
	malloc_noncache_start = malloc_start - CONFIG_NONCACHE_MEMORY_SIZE;
	gd->malloc_noncache_start = malloc_noncache_start;
#endif
	/* Enable caches */
	enable_caches();
	debug("monitor flash len: %08lX\n", monitor_flash_len);
	board_init();	/* Setup chipselects */
#ifdef CONFIG_SERIAL_MULTI
	serial_initialize();
#endif
	debug("Now running in RAM - U-Boot at: %08lx\n", dest_addr);

#ifdef CONFIG_LOGBUFFER
	logbuff_init_ptrs();
#endif
#ifdef CONFIG_POST
	post_output_backlog();
#endif

	/* The Malloc area is immediately below the monitor copy in DRAM */
	mem_malloc_init (malloc_start, TOTAL_MALLOC_LEN);
#ifdef CONFIG_SMALL_MEMSIZE
        save_config();
#endif
#ifdef CONFIG_NONCACHE_MEMORY
	mem_noncache_malloc_init(malloc_noncache_start, CONFIG_NONCACHE_MEMORY_SIZE);
#endif

#if defined(CONFIG_ARCH_HOMELET)
	check_physical_key_early();
#endif

	workmode = uboot_spare_head.boot_data.work_mode;
	debug("work mode %d\n", workmode);

	axp_reinit();
	//uboot_spare_head.boot_data.work_mode = WORK_MODE_CARD_PRODUCT;

#if defined(CONFIG_CPUS_STANDBY) //目前只在homelet上使用
	do_box_standby();
#endif

#ifdef 	CONFIG_ARCH_HOMELET
	gpio_control();
#endif
#if 0
#if !defined(CONFIG_SYS_NO_FLASH)
	puts("Flash: ");

	flash_size = flash_init();
	if (flash_size > 0) {
# ifdef CONFIG_SYS_FLASH_CHECKSUM
		print_size(flash_size, "");
		/*
		 * Compute and print flash CRC if flashchecksum is set to 'y'
		 *
		 * NOTE: Maybe we should add some WATCHDOG_RESET()? XXX
		 */
		s = getenv("flashchecksum");
		if (s && (*s == 'y')) {
			printf("  CRC: %08X", crc32(0,
				(const unsigned char *) CONFIG_SYS_FLASH_BASE,
				flash_size));
		}
		putc('\n');
# else	/* !CONFIG_SYS_FLASH_CHECKSUM */
		print_size(flash_size, "\n");
# endif /* CONFIG_SYS_FLASH_CHECKSUM */
	} else {
		puts(failed);
		hang();
	}
#endif
#endif
	/* set up exceptions */
	interrupt_init();
	/* enable exceptions */
	enable_interrupts();
	sunxi_dma_init();
#ifdef DEBUG
    puts("ready to config storage\n");
#endif

#ifdef CONFIG_ARCH_HOMELET	//for homlet to use one-key-recovery
	ret = sunxi_flash_handle_init();
	if(!ret)
	{
		sunxi_partition_init();
	}
#endif

	if((workmode == WORK_MODE_BOOT) || (workmode == WORK_MODE_CARD_PRODUCT) || (workmode == WORK_MODE_SPRITE_RECOVERY))
	{
#if (defined(CONFIG_SUNXI_DISPLAY) || defined(CONFIG_SUN7I_DISPLAY))
	    drv_disp_init();
#endif
#ifdef CONFIG_SUNXI_HDCP_IN_SECURESTORAGE
		ret = script_parser_fetch("hdmi_para", "hdmi_hdcp_enable", &hdcpkey_enable, 1);
		if((ret) || (hdcpkey_enable != 1))
		{
			board_display_device_open();
			board_display_layer_request();
		}
#else
		board_display_device_open();
		board_display_layer_request();
#endif
	}

#ifndef CONFIG_ARCH_HOMELET	//for pad used
	ret = sunxi_flash_handle_init();
	if(!ret)
	{
		sunxi_partition_init();
	}
#endif

#ifdef CONFIG_SUNXI_HDCP_IN_SECURESTORAGE
		//here: write key to hardware
		if(hdcpkey_enable==1)
		{
			char buffer[4096];
			int data_len;
			int ret0;

			memset(buffer, 0, 4096);
			ret0 = sunxi_secure_storage_init();
			if(ret0)
			{
				printf("sunxi init secure storage failed\n");
			}
			else
			{
				ret0 = sunxi_secure_storage_read("hdcpkey", buffer, 4096, &data_len);
				if(ret0)
				{
					printf("probe hdcp key failed\n");
				}
				else
				{
					ret0 = smc_aes_bssk_decrypt_to_keysram(buffer, data_len);
					if(ret0)
					{
						printf("push hdcp key failed\n");
					}
					else
					{
						board_display_device_open();
						board_display_layer_request();
					}
				}
			}
		}
#endif

#ifdef  CONFIG_BOOT_A15
	if(sunxi_sprite_download_boot0_simple())
	{
		printf("rewrite boot0 to save boot cpu failed\n");
	}
#endif
#ifndef CONFIG_SUNXI_SPINOR_PLATFORM
	sunxi_keydata_burn_by_usb();
#endif
//#else
//#if defined(CONFIG_CMD_NAND)
//	if(!storage_type){
//		puts("NAND:  ");
//		nand_init();        /* go init the NAND */
//	}
//#endif/*CONFIG_CMD_NAND*/
//
//#if defined(CONFIG_GENERIC_MMC)
//	if(storage_type){
//		puts("MMC:   ");
//		mmc_initialize(bd);
//	}
//#endif/*CONFIG_GENERIC_MMC*/

#ifdef CONFIG_HAS_DATAFLASH
	AT91F_DataflashInit();
	dataflash_print_info();
#endif

	/* initialize environment */
	env_relocate();
#if defined(CONFIG_CMD_PCI) || defined(CONFIG_PCI)
	arm_pci_init();
#endif

	/* IP Address */
	gd->bd->bi_ip_addr = getenv_IPaddr("ipaddr");
	stdio_init();	/* get the devices list going. */
	jumptable_init();
#if defined(CONFIG_API)
	/* Initialize API */
	api_init();
#endif

	console_init_r();	/* fully init console as a device */
#if defined(CONFIG_ARCH_MISC_INIT)
	/* miscellaneous arch dependent initialisations */
	arch_misc_init();
#endif
#if defined(CONFIG_MISC_INIT_R)
	/* miscellaneous platform dependent initialisations */
	misc_init_r();
#endif
	/* Perform network card initialisation if necessary */
#if defined(CONFIG_DRIVER_SMC91111) || defined (CONFIG_DRIVER_LAN91C96)
	/* XXX: this needs to be moved to board init */
	if (getenv("ethaddr")) {
		uchar enetaddr[6];
		eth_getenv_enetaddr("ethaddr", enetaddr);
		smc_set_mac_addr(enetaddr);
	}
#endif /* CONFIG_DRIVER_SMC91111 || CONFIG_DRIVER_LAN91C96 */

	/* Initialize from environment */
	s = getenv("loadaddr");
	if (s != NULL)
		load_addr = simple_strtoul(s, NULL, 16);
#if defined(CONFIG_CMD_NET)
	s = getenv("bootfile");
	if (s != NULL)
		copy_filename(BootFile, s, sizeof(BootFile));
#endif
#ifdef BOARD_LATE_INIT
	board_late_init();
#endif
#ifdef CONFIG_BITBANGMII
	bb_miiphy_init();
#endif
#if defined(CONFIG_CMD_NET)
#if defined(CONFIG_NET_MULTI)
	puts("Net:   ");
#endif
	eth_initialize(gd->bd);
#if defined(CONFIG_RESET_PHY_R)
	debug("Reset Ethernet PHY\n");
	reset_phy();
#endif
#endif

#ifdef CONFIG_POST
	post_run(NULL, POST_RAM | post_bootmode_get(0));
#endif

#if defined(CONFIG_PRAM) || defined(CONFIG_LOGBUFFER)
	/*
	 * Export available size of memory for Linux,
	 * taking into account the protected RAM at top of memory
	 */
	{
		ulong pram;
		uchar memsz[32];
#ifdef CONFIG_PRAM
		char *s;

		s = getenv("pram");
		if (s != NULL)
			pram = simple_strtoul(s, NULL, 10);
		else
			pram = CONFIG_PRAM;
#else
		pram = 0;
#endif
#ifdef CONFIG_LOGBUFFER
#ifndef CONFIG_ALT_LB_ADDR
		/* Also take the logbuffer into account (pram is in kB) */
		pram += (LOGBUFF_LEN + LOGBUFF_OVERHEAD) / 1024;
#endif
#endif
		sprintf((char *)memsz, "%ldk", (gd->ram_size / 1024) - pram);
		setenv("mem", (char *)memsz);
	}
#endif
	//sprite_cartoon_test();
	if(workmode == WORK_MODE_BOOT)
    {
#if defined(CONFIG_SUNXI_SCRIPT_REINIT)
		{
			FATFS script_mount;
			int  ret;
			uint read_bytes = 0;
			FILE  script_fs;
			uchar  *buf = NULL;

			f_mount_ex(0, &script_mount, 0);
			ret = f_open (&script_fs, "0:script.bin", FA_OPEN_EXISTING | FA_READ | FA_WRITE );
			if(ret)
			{
				printf("cant open script.bin, maybe it is not exist\n");
			}
			else
			{
				buf = (uchar *)malloc(100 * 1024);
				memset(buf, 0, 100 * 1024);

				if(!f_read(&script_fs, buf, 100 * 1024, &read_bytes))
				{
					printf("f_read read bytes = %d\n", read_bytes);
				}
				f_close(&script_fs);
				puts("try to unlink file ");
				printf("%d\n", f_unlink("0:script.bin"));
			}
			f_mount(0, NULL, NULL);
			if(read_bytes > 0)
			{
				char *tmp_target_buffer = (char *)(CONFIG_SYS_TEXT_BASE - 0x01000000);

				sunxi_flash_exit(1);

				memcpy(tmp_target_buffer + uboot_spare_head.boot_head.uboot_length, buf, read_bytes);
				sunxi_sprite_download_uboot(tmp_target_buffer, uboot_spare_head.boot_data.storage_type, 1);

				reset_cpu(0);
			}
			if(buf)
			{
				free(buf);
			}
		}
#endif
    	printf("WORK_MODE_BOOT\n");
#if (defined(CONFIG_SUNXI_DISPLAY) || defined(CONFIG_SUN7I_DISPLAY))
		if(!ret)
		{
#ifndef CONFIG_ARCH_HOMELET
			printf("board_status_probe\n");
			board_status_probe(0);
#endif
                    if(!gd->chargemode)
                    {
			printf("sunxi_bmp_logo_display\n");
			sunxi_bmp_display("bootlogo.bmp");
                    }
                    else
                    {
                        printf("sunxi_bmp_charger_display\n");
                        sunxi_bmp_display("bat\\battery_charge.bmp");
                    }
		}
#endif
#ifdef CONFIG_READ_LOGO_FOR_KERNEL
	    sunxi_read_bootlogo("bootlogo");
#endif

	}
	/* main_loop() can return to retry autoboot, if so just run it again. */
	for (;;)
	{
		main_loop();
	}
	hang();
	/* NOTREACHED - no way out of command loop except booting */
}
Esempio n. 16
0
int main(void) {
    // TODO disable JTAG

    // Stack limit should be less than real stack size, so we have a chance
    // to recover from limit hit.  (Limit is measured in bytes.)
    mp_stack_set_limit((char*)&_ram_end - (char*)&_heap_end - 1024);

    /* 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();

    // set the system clock to be HSE
    SystemClock_Config();

    // enable GPIO clocks
    __GPIOA_CLK_ENABLE();
    __GPIOB_CLK_ENABLE();
    __GPIOC_CLK_ENABLE();
    __GPIOD_CLK_ENABLE();

    // enable the CCM RAM
    __CCMDATARAMEN_CLK_ENABLE();

#if 0
#if defined(NETDUINO_PLUS_2)
    {
        GPIO_InitTypeDef GPIO_InitStructure;
        GPIO_InitStructure.GPIO_Speed = GPIO_Speed_25MHz;
        GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT;
        GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
        GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;

#if MICROPY_HW_HAS_SDCARD
        // Turn on the power enable for the sdcard (PB1)
        GPIO_InitStructure.GPIO_Pin = GPIO_Pin_1;
        GPIO_Init(GPIOB, &GPIO_InitStructure);
        GPIO_WriteBit(GPIOB, GPIO_Pin_1, Bit_SET);
#endif

        // Turn on the power for the 5V on the expansion header (PB2)
        GPIO_InitStructure.GPIO_Pin = GPIO_Pin_2;
        GPIO_Init(GPIOB, &GPIO_InitStructure);
        GPIO_WriteBit(GPIOB, GPIO_Pin_2, Bit_SET);
    }
#endif
#endif

    // basic sub-system init
    pendsv_init();
    timer_tim3_init();
    led_init();
#if MICROPY_HW_HAS_SWITCH
    switch_init0();
#endif

    int first_soft_reset = true;

soft_reset:

    // check if user switch held to select the reset mode
    led_state(1, 0);
    led_state(2, 1);
    led_state(3, 0);
    led_state(4, 0);
    uint reset_mode = 1;

#if MICROPY_HW_HAS_SWITCH
    if (switch_get()) {
        for (uint i = 0; i < 3000; i++) {
            if (!switch_get()) {
                break;
            }
            HAL_Delay(20);
            if (i % 30 == 29) {
                if (++reset_mode > 3) {
                    reset_mode = 1;
                }
                led_state(2, reset_mode & 1);
                led_state(3, reset_mode & 2);
                led_state(4, reset_mode & 4);
            }
        }
        // flash the selected reset mode
        for (uint i = 0; i < 6; i++) {
            led_state(2, 0);
            led_state(3, 0);
            led_state(4, 0);
            HAL_Delay(50);
            led_state(2, reset_mode & 1);
            led_state(3, reset_mode & 2);
            led_state(4, reset_mode & 4);
            HAL_Delay(50);
        }
        HAL_Delay(400);
    }
#endif

#if MICROPY_HW_ENABLE_RTC
    if (first_soft_reset) {
        rtc_init();
    }
#endif

    // more sub-system init
#if MICROPY_HW_HAS_SDCARD
    if (first_soft_reset) {
        sdcard_init();
    }
#endif
    if (first_soft_reset) {
        storage_init();
    }

    // GC init
    gc_init(&_heap_start, &_heap_end);

    // Micro Python init
    mp_init();
    mp_obj_list_init(mp_sys_path, 0);
    mp_obj_list_append(mp_sys_path, MP_OBJ_NEW_QSTR(MP_QSTR_)); // current dir (or base dir of the script)
    mp_obj_list_append(mp_sys_path, MP_OBJ_NEW_QSTR(MP_QSTR__slash_flash));
    mp_obj_list_append(mp_sys_path, MP_OBJ_NEW_QSTR(MP_QSTR__slash_flash_slash_lib));
    mp_obj_list_init(mp_sys_argv, 0);

    // Change #if 0 to #if 1 if you want REPL on UART_6 (or another uart)
    // as well as on USB VCP
#if 0
    {
        mp_obj_t args[2] = {
            MP_OBJ_NEW_SMALL_INT(PYB_UART_6),
            MP_OBJ_NEW_SMALL_INT(115200),
        };
        pyb_stdio_uart = pyb_uart_type.make_new((mp_obj_t)&pyb_uart_type, MP_ARRAY_SIZE(args), 0, args);
    }
#else
    pyb_stdio_uart = NULL;
#endif

    // Initialise low-level sub-systems.  Here we need to very basic things like
    // zeroing out memory and resetting any of the sub-systems.  Following this
    // we can run Python scripts (eg boot.py), but anything that is configurable
    // by boot.py must be set after boot.py is run.

    readline_init0();
    pin_init0();
    extint_init0();
    timer_init0();
    uart_init0();

#if MICROPY_HW_ENABLE_RNG
    rng_init0();
#endif

    i2c_init0();
    spi_init0();
    pyb_usb_init0();

    // Initialise the local flash filesystem.
    // Create it if needed, and mount in on /flash.
    {
        // try to mount the flash
        FRESULT res = f_mount(&fatfs0, "/flash", 1);
        if (reset_mode == 3 || res == FR_NO_FILESYSTEM) {
            // no filesystem, or asked to reset it, so create a fresh one

            // LED on to indicate creation of LFS
            led_state(PYB_LED_R2, 1);
            uint32_t start_tick = HAL_GetTick();

            res = f_mkfs("/flash", 0, 0);
            if (res == FR_OK) {
                // success creating fresh LFS
            } else {
                __fatal_error("could not create LFS");
            }

            // set label
            f_setlabel("/flash/pybflash");

            // create empty main.py
            FIL fp;
            f_open(&fp, "/flash/main.py", FA_WRITE | FA_CREATE_ALWAYS);
            UINT n;
            f_write(&fp, fresh_main_py, sizeof(fresh_main_py) - 1 /* don't count null terminator */, &n);
            // TODO check we could write n bytes
            f_close(&fp);

            // create .inf driver file
            f_open(&fp, "/flash/pybcdc.inf", FA_WRITE | FA_CREATE_ALWAYS);
            f_write(&fp, fresh_pybcdc_inf, sizeof(fresh_pybcdc_inf) - 1 /* don't count null terminator */, &n);
            f_close(&fp);

            // create readme file
            f_open(&fp, "/flash/README.txt", FA_WRITE | FA_CREATE_ALWAYS);
            f_write(&fp, fresh_readme_txt, sizeof(fresh_readme_txt) - 1 /* don't count null terminator */, &n);
            f_close(&fp);

            // keep LED on for at least 200ms
            sys_tick_wait_at_least(start_tick, 200);
            led_state(PYB_LED_R2, 0);
        } else if (res == FR_OK) {
            // mount sucessful
        } else {
            __fatal_error("could not access LFS");
        }
    }

    // The current directory is used as the boot up directory.
    // It is set to the internal flash filesystem by default.
    f_chdrive("/flash");

    // Make sure we have a /flash/boot.py.  Create it if needed.
    {
        FILINFO fno;
#if _USE_LFN
        fno.lfname = NULL;
        fno.lfsize = 0;
#endif
        FRESULT res = f_stat("/flash/boot.py", &fno);
        if (res == FR_OK) {
            if (fno.fattrib & AM_DIR) {
                // exists as a directory
                // TODO handle this case
                // see http://elm-chan.org/fsw/ff/img/app2.c for a "rm -rf" implementation
            } else {
                // exists as a file, good!
            }
        } else {
            // doesn't exist, create fresh file

            // LED on to indicate creation of boot.py
            led_state(PYB_LED_R2, 1);
            uint32_t start_tick = HAL_GetTick();

            FIL fp;
            f_open(&fp, "/flash/boot.py", FA_WRITE | FA_CREATE_ALWAYS);
            UINT n;
            f_write(&fp, fresh_boot_py, sizeof(fresh_boot_py) - 1 /* don't count null terminator */, &n);
            // TODO check we could write n bytes
            f_close(&fp);

            // keep LED on for at least 200ms
            sys_tick_wait_at_least(start_tick, 200);
            led_state(PYB_LED_R2, 0);
        }
    }

#if defined(USE_DEVICE_MODE)
    usb_storage_medium_t usb_medium = USB_STORAGE_MEDIUM_FLASH;
#endif

#if MICROPY_HW_HAS_SDCARD
    // if an SD card is present then mount it on /sd/
    if (sdcard_is_present()) {
        FRESULT res = f_mount(&fatfs1, "/sd", 1);
        if (res != FR_OK) {
            printf("[SD] could not mount SD card\n");
        } else {
            // use SD card as current directory
            f_chdrive("/sd");

            // TODO these should go before the /flash entries in the path
            mp_obj_list_append(mp_sys_path, MP_OBJ_NEW_QSTR(MP_QSTR__slash_sd));
            mp_obj_list_append(mp_sys_path, MP_OBJ_NEW_QSTR(MP_QSTR__slash_sd_slash_lib));

            if (first_soft_reset) {
                // use SD card as medium for the USB MSD
#if defined(USE_DEVICE_MODE)
                usb_medium = USB_STORAGE_MEDIUM_SDCARD;
#endif
            }
        }
    }
#endif

    // reset config variables; they should be set by boot.py
    pyb_config_main = MP_OBJ_NULL;
    pyb_config_usb_mode = MP_OBJ_NULL;

    // run boot.py, if it exists
    // TODO perhaps have pyb.reboot([bootpy]) function to soft-reboot and execute custom boot.py
    if (reset_mode == 1) {
        const char *boot_py = "boot.py";
        FRESULT res = f_stat(boot_py, NULL);
        if (res == FR_OK) {
            int ret = pyexec_file(boot_py);
            if (ret & PYEXEC_FORCED_EXIT) {
                goto soft_reset_exit;
            }
            if (!ret) {
                flash_error(4);
            }
        }
    }

    // turn boot-up LEDs off
    led_state(2, 0);
    led_state(3, 0);
    led_state(4, 0);

    // Now we initialise sub-systems that need configuration from boot.py,
    // or whose initialisation can be safely deferred until after running
    // boot.py.

#if defined(USE_HOST_MODE)
    // USB host
    pyb_usb_host_init();
#elif defined(USE_DEVICE_MODE)
    // USB device
    usb_device_mode_t usb_mode = USB_DEVICE_MODE_CDC_MSC;
    // if we are not in reset_mode==1, this config variable will always be NULL
    if (pyb_config_usb_mode != MP_OBJ_NULL) {
        if (strcmp(mp_obj_str_get_str(pyb_config_usb_mode), "CDC+HID") == 0) {
            usb_mode = USB_DEVICE_MODE_CDC_HID;
        }
    }
    pyb_usb_dev_init(usb_mode, usb_medium);
#endif

#if MICROPY_HW_HAS_MMA7660
    // MMA accel: init and reset
    accel_init();
#endif

#if MICROPY_HW_ENABLE_SERVO
    // servo
    servo_init();
#endif

#if MICROPY_HW_ENABLE_DAC
    // DAC
    dac_init();
#endif

    mod_network_init();

    // At this point everything is fully configured and initialised.

    // Run the main script from the current directory.
    if (reset_mode == 1 && pyexec_mode_kind == PYEXEC_MODE_FRIENDLY_REPL) {
        const char *main_py;
        if (pyb_config_main == MP_OBJ_NULL) {
            main_py = "main.py";
        } else {
            main_py = mp_obj_str_get_str(pyb_config_main);
        }
        FRESULT res = f_stat(main_py, NULL);
        if (res == FR_OK) {
            int ret = pyexec_file(main_py);
            if (ret & PYEXEC_FORCED_EXIT) {
                goto soft_reset_exit;
            }
            if (!ret) {
                flash_error(3);
            }
        }
    }

    // Main script is finished, so now go into REPL mode.
    // The REPL mode can change, or it can request a soft reset.
    for (;;) {
        if (pyexec_mode_kind == PYEXEC_MODE_RAW_REPL) {
            if (pyexec_raw_repl() != 0) {
                break;
            }
        } else {
            if (pyexec_friendly_repl() != 0) {
                break;
            }
        }
    }

soft_reset_exit:

    // soft reset

    printf("PYB: sync filesystems\n");
    storage_flush();

    printf("PYB: soft reboot\n");
    timer_deinit();
    uart_deinit();

    first_soft_reset = false;
    goto soft_reset;
}
Esempio n. 17
0
File: main.c Progetto: marekr/asf
/*! \brief Main function. Execution starts here.
 */
int main(void)
{
#if SAMD21
	system_init();
#else
	sysclk_init();
	board_init();
#endif
	irq_initialize_vectors();
	cpu_irq_enable();

	// Initialize the sleep manager
	sleepmgr_init();

	ui_init();

	// Start USB host stack
	uhc_start();

	// The USB management is entirely managed by interrupts.
	// As a consequence, the user application does only have :
	// - to play with the power modes
	// - to create a file on each new LUN connected
	while (true) {
		sleepmgr_enter_sleep();
		if (main_usb_sof_counter > 2000) {
			main_usb_sof_counter = 0;
			volatile uint8_t lun;
			FRESULT res;

			for (lun = LUN_ID_USB; (lun < LUN_ID_USB +
					uhi_msc_mem_get_lun()) &&
					(lun < MAX_DRIVE); lun++) {
				// Check if LUN has been already tested
				if (TEST_OK == lun_states[lun] ||
						TEST_ERROR == lun_states[lun]) {
					continue;
				}
				// Mount drive
				memset(&fs, 0, sizeof(FATFS));
				res = f_mount(lun, &fs);
				if (FR_INVALID_DRIVE == res) {
					// LUN is not present
					lun_states[lun] = TEST_NO_PRESENT;
					continue;
				}
				// Create a test file on the disk
				test_file_name[0] = lun + '0';
				res = f_open(&file_object,
						(char const *)test_file_name,
						FA_CREATE_ALWAYS | FA_WRITE);
				if (res == FR_NOT_READY) {
					// LUN not ready
					lun_states[lun] = TEST_NO_PRESENT;
					f_close(&file_object);
					continue;
				}
				if (res != FR_OK) {
					// LUN test error
					lun_states[lun] = TEST_ERROR;
					f_close(&file_object);
					continue;
				}
				// Write to test file
				f_puts(MSG_TEST, &file_object);
				// LUN test OK
				lun_states[lun] = TEST_OK;
				f_close(&file_object);
			}
			if (main_count_states(TEST_NO_PRESENT) == MAX_DRIVE) {
				ui_test_finish(false); // Test fail
			} else if (MAX_DRIVE != main_count_states(TEST_NULL)) {
				if (main_count_states(TEST_ERROR)) {
					ui_test_finish(false); // Test fail
				} else if (main_count_states(TEST_OK)) {
					ui_test_flag_reset();
					ui_test_finish(true); // Test OK
				}
			} else {
				ui_test_flag_reset();
			}
		}
	}
}
Esempio n. 18
0
void fclose() {
    f_close(&fp);
}
Esempio n. 19
0
static void prvCreateDemoFileUsing_f_putc( void )
{
unsigned char ucReturn;
int iByte, iReturned;
F_FILE *pxFile;
char cFileName[ fsMAX_FILE_NAME_LEN ];

	/* Obtain and print out the working directory. */
	f_getcwd( cRAMBuffer, fsRAM_BUFFER_SIZE );
	printf( "In directory %s\r\n", cRAMBuffer );

	/* Create a sub directory. */
	ucReturn = f_mkdir( pcDirectory1 );
	configASSERT( ucReturn == F_NO_ERROR );

	/* Move into the created sub-directory. */
	ucReturn = f_chdir( pcDirectory1 );
	configASSERT( ucReturn == F_NO_ERROR );

	/* Obtain and print out the working directory. */
	f_getcwd( cRAMBuffer, fsRAM_BUFFER_SIZE );
	printf( "In directory %s\r\n", cRAMBuffer );

	/* Create a subdirectory in the new directory. */
	ucReturn = f_mkdir( pcDirectory2 );
	configASSERT( ucReturn == F_NO_ERROR );

	/* Move into the directory just created - now two directories down from
	the root. */
	ucReturn = f_chdir( pcDirectory2 );
	configASSERT( ucReturn == F_NO_ERROR );

	/* Obtain and print out the working directory. */
	f_getcwd( cRAMBuffer, fsRAM_BUFFER_SIZE );
	printf( "In directory %s\r\n", cRAMBuffer );
	configASSERT( strcmp( cRAMBuffer, pcFullPath ) == 0 );

	/* Generate the file name. */
	sprintf( cFileName, "%s.txt", pcDirectory2 );

	/* Print out the file name and the directory into which the file is being
	written. */
	printf( "Writing file %s in %s\r\n", cFileName, cRAMBuffer );

	pxFile = f_open( cFileName, "w" );

	/* Create a file 1 byte at a time.  The file is filled with incrementing
	ascii characters starting from '0'. */
	for( iByte = 0; iByte < fsPUTC_FILE_SIZE; iByte++ )
	{
		iReturned = f_putc( ( ( int ) '0' + iByte ), pxFile );
		configASSERT( iReturned ==  ( ( int ) '0' + iByte ) );
	}

	/* Finished so close the file. */
	f_close( pxFile );

	/* Move back to the root directory. */
	ucReturn = f_chdir( "../.." );
	configASSERT( ucReturn == F_NO_ERROR );

	/* Obtain and print out the working directory. */
	f_getcwd( cRAMBuffer, fsRAM_BUFFER_SIZE );
	printf( "Back in root directory %s\r\n", cRAMBuffer );
	configASSERT( strcmp( cRAMBuffer, pcRoot ) == 0 );
}
Esempio n. 20
0
/**
  * @brief  Test for FatFs,write and read data with SD 
  * @param  None
  * @retval None
  */
void FatFS_Test(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- Register the file system object to the FatFs module ##############*/
    if(f_mount(&SDFatFs, (TCHAR const*)SDPath, 0) != FR_OK)
    {
        /* FatFs Initialization Error */
        printf("f_mount Err\r\n"); 
    }
    else  
    {
        /*##-2- Create a FAT file system (format) on the logical drive #########*/
        /* WARNING: Formatting the uSD card will delete all content on the device */
        if(f_mkfs((TCHAR const*)SDPath, 0, 0) != FR_OK)
        {
            /* FatFs Format Error */
            printf("FatFs Format Err\r\n");
        }
        else
        {
            /*##-3- 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 */
                printf("f_open Err\r\n");
            }
            else
            {
                /*##-4- 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 */
                    printf("f_write Err\r\n");
                }
                else
                {
                    /*##-5- Close the open text file #################################*/
                    f_close(&MyFile);

                    /*##-6- 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 */
                        printf("f_open Err in Read\r\n");
                    }
                    else
                    {
                        /*##-7- Read data from the text file ###########################*/
                        res = f_read(&MyFile, rtext, sizeof(rtext), (UINT*)&bytesread);

                        if((bytesread == 0) || (res != FR_OK))
                        {
                            /* 'STM32.TXT' file Read or EOF Error */
                            printf("f_read Err\r\n");
                        }
                        else
                        {
                            /*##-8- Close the open text file #############################*/
                            f_close(&MyFile);

                            /*##-9- Compare read data with the expected data ############*/
                            if ((bytesread != byteswritten))
                            {                
                                /* Read data is different from the expected data */
                                printf("read data err\r\n");
                            }
                            else
                            {
                                /* Success of the demo: no error occurrence */
                                printf("read data OK\r\n");
                            }
                        }
                    }
                }
            }
        }
    }
}
Esempio n. 21
0
//u32 Loopmode=0;
int _main( int argc, char *argv[] )
{
	s32 ret = 0;
	
	u8 MessageHeap[0x10];
	//u32 MessageQueue=0xFFFFFFFF;

	BootStatus(0, 0, 0);

	thread_set_priority( 0, 0x79 );	// do not remove this, this waits for FS to be ready!
	thread_set_priority( 0, 0x50 );
	thread_set_priority( 0, 0x79 );

	//MessageQueue = ES_Init( MessageHeap );
	ES_Init( MessageHeap );

	BootStatus(1, 0, 0);

#ifndef NINTENDONT_USB
	BootStatus(2, 0, 0);
	ret = SDHCInit();
	if(!ret)
	{
		dbgprintf("SD:SDHCInit() failed:%d\r\n", ret );
		BootStatusError(-2, ret);
		mdelay(2000);
		Shutdown();
	}
#endif
	BootStatus(3, 0, 0);
	fatfs = (FATFS*)malloca( sizeof(FATFS), 32 );

	s32 res = f_mount( 0, fatfs );
	if( res != FR_OK )
	{
		dbgprintf("ES:f_mount() failed:%d\r\n", res );
		BootStatusError(-3, res);
		mdelay(2000);
		Shutdown();
	}
	
	BootStatus(4, 0, 0);

	BootStatus(5, 0, 0);
	
	int MountFail = 0;
	s32 fres = -1; 
	while(fres != FR_OK)
	{
		fres = f_open(&GameFile, "/bladie", FA_READ|FA_OPEN_EXISTING);
		switch(fres)
		{
			case FR_OK:
				f_close(&GameFile);
			case FR_NO_PATH:
			case FR_NO_FILE:
			{
				fres = FR_OK;
			} break;
			default:
			case FR_DISK_ERR:
			{
				f_mount(0, 0);		//unmount drive todo: retry could never work
				MountFail++;
				if(MountFail == 10)
				{
					BootStatusError(-5, fres);
					mdelay(2000);
					Shutdown();
				}
				mdelay(5);
			} break;
		}
	}

#ifdef NINTENDONT_USB
	BootStatus(6, s_size, s_cnt);
	s32 r = LoadModules(55);
	//dbgprintf("ES:ES_LoadModules(%d):%d\r\n", 55, r );
	if( r < 0 )
	{
		BootStatusError(-6, r);
		mdelay(2000);
		Shutdown();
	}
#endif

	BootStatus(7, s_size, s_cnt);
	ConfigInit();
	
	BootStatus(8, s_size, s_cnt);

	SDisInit = 1;

	memset32((void*)0x13002800, 0, 0x30);
	sync_after_write((void*)0x13002800, 0x30);
	u32 HID_Thread = 0;
	bool UseHID = ConfigGetConfig(NIN_CFG_HID);
	if( UseHID )
	{
		ret = HIDInit();
		if(ret < 0 )
		{
			dbgprintf("ES:HIDInit() failed\r\n" );
			BootStatusError(-8, ret);
			mdelay(2000);
			Shutdown();
		}
		write32(0x13003004, 0);
		sync_after_write((void*)0x13003004, 0x20);

		memset32((void*)0x13003420, 0, 0x1BE0);
		sync_after_write((void*)0x13003420, 0x1BE0);
		HID_Thread = thread_create(HID_Run, NULL, (u32*)0x13003420, 0x1BE0, 0x78, 1);
		thread_continue(HID_Thread);
	}
	BootStatus(9, s_size, s_cnt);

	DIinit();
	BootStatus(10, s_size, s_cnt);

	EXIInit();
	BootStatus(11, s_size, s_cnt);

	SIInit();

//fixes issues in some japanese games
	if((ConfigGetGameID() & 0xFF) == 'J')
		write32(HW_PPCSPEED, 0x2A9E0);

//Tell PPC side we are ready!
	cc_ahbMemFlush(1);
	mdelay(1000);
	BootStatus(0xdeadbeef, s_size, s_cnt);
/*
	write32( HW_PPCIRQFLAG, read32(HW_PPCIRQFLAG) );
	write32( HW_ARMIRQFLAG, read32(HW_ARMIRQFLAG) );

	set32( HW_PPCIRQMASK, (1<<31) );
	set32( HW_IPC_PPCCTRL, 0x30 );
*/
	u32 Now = read32(HW_TIMER);
	u32 PADTimer = Now;

	bool SaveCard = false;
	if( ConfigGetConfig(NIN_CFG_LED) )
	{
		set32(HW_GPIO_ENABLE, GPIO_SLOT_LED);
		clear32(HW_GPIO_DIR, GPIO_SLOT_LED);
		clear32(HW_GPIO_OWNER, GPIO_SLOT_LED);
	}
	write32(0xd8006a0, 0x30000004), mask32(0xd8006a8, 0, 2);
	while (1)
	{
		_ahbMemFlush(0);

		if(EXI_IRQ == true)
		{
			if(EXICheckTimer())
				EXIInterrupt();
		}
		if(SI_IRQ == true)
		{
			if((read32(HW_TIMER) - PADTimer) >= 65000)	// about 29 times a second
			{
				SIInterrupt();
				PADTimer = read32(HW_TIMER);
			}
		}
		if(DI_IRQ == true)
		{
			if(DI_Args->Buffer == 0xdeadbeef)
				DIInterrupt();
		}
		else if(SaveCard == true) /* DI IRQ indicates we might read async, so dont write at the same time */
		{
			if((read32(HW_TIMER) - Now) / 1898437 > 2) /* after 3 second earliest */
			{
				EXISaveCard();
				SaveCard = false;
			}
		}
		udelay(10); //wait for other threads

		//Baten Kaitos save hax
		if( read32(0) == 0x474B4245 )
		{
			if( read32( 0x0073E640 ) == 0xFFFFFFFF )
			{
				write32( 0x0073E640, 0 );
			}
		}

		if( Streaming )
		{
			if( (read32(HW_TIMER) * 19 / 10) - StreamTimer >= 5000000 )
			{
			//	dbgprintf(".");
				StreamOffset += 64*1024;

				if( StreamOffset >= StreamSize )
				{
					StreamOffset = StreamSize;
					Streaming = 0;
				}
				StreamTimer = read32(HW_TIMER) * 19 / 10;
			}
		}

		if( DiscChangeIRQ )
		{
			if( read32(HW_TIMER) * 128 / 243000000 > 2 )
			{
				//dbgprintf("DIP:IRQ mon!\r\n");
				set32( DI_SSTATUS, 0x3A );
				sync_after_write((void*)DI_SSTATUS, 4);
				DIInterrupt();
				DiscChangeIRQ = 0;
			}
		}
		_ahbMemFlush(1);
		DIUpdateRegisters();
		EXIUpdateRegistersNEW();
		SIUpdateRegisters();
		if(EXICheckCard())
		{
			Now = read32(HW_TIMER);
			SaveCard = true;
		}
		if(read32(DI_SCONFIG) == 0x1DEA)
		{
			while(DI_Args->Buffer != 0xdeadbeef)
				udelay(100);
			break;
		}
		cc_ahbMemFlush(1);
	}
	if( UseHID )
	{
		/* we're done reading inputs */
		thread_cancel(HID_Thread, 0);
	}
	thread_cancel(DI_Thread, 0);

	write32( DI_SCONFIG, 0 );
	sync_after_write( (void*)DI_SCONFIG, 4 );
	/* reset time */
	while(1)
	{
		_ahbMemFlush(0);
		sync_before_read( (void*)DI_SCONFIG, 4 );
		if(read32(DI_SCONFIG) == 0x2DEA)
			break;
		wait_for_ppc(1);
		cc_ahbMemFlush(1);
	}

	if( ConfigGetConfig(NIN_CFG_LED) )
		clear32(HW_GPIO_OUT, GPIO_SLOT_LED);

	if( ConfigGetConfig(NIN_CFG_MEMCARDEMU) )
		EXIShutdown();
	IOSBoot((char*)0x13003020, 0, read32(0x13003000));
	return 0;
}
Esempio n. 22
0
void *ms_load_ipl(const char *path)

{
	FRESULT result;
	WORD readed;
	DWORD *src;

	DWORD *top;
	DWORD size;
	void *entry;
	DWORD sum;
	int binary_type = 0;

	result = f_mount(0,&FileSystem);
	if(result!=0)
	{
Kprintf("f_mount error %08X\n",result);
		return 0;
	}

	result = f_open(&FileObject,path,FA_READ|FA_OPEN_EXISTING);
	if(result!=0)
	{
Kprintf("f_open %s error\n",path);
		return 0;
	}

	do{
		result = f_read(&FileObject,ipl_buf,0x1000,&readed);
		if(result!=0)
		{
Kprintf("f_read error\n");
			entry = 0;
			goto error;
		}

		if(binary_type==0)
		{
			// chech decrypted HEADER
			top  = (DWORD *)(ipl_buf[0]);
			size = (ipl_buf[1]);
			entry= (void *)(ipl_buf[2]);
			sum  = (ipl_buf[3]);
			if(
				check_ipl_address(top) &&
				check_ipl_address(top+size) && 
				(entry==0 || ( entry >= top && entry<=(top+size))) &&
				sum == 0
			){
				// decrypted with header
				binary_type = 2;
			} else if(
				ipl_buf[0x60/4]==0x01 &&
				ipl_buf[0x64/4]==0    &&
				ipl_buf[0x68/4]==0    &&
				ipl_buf[0x6c/4]==0xffffffff
			)
			{
				// encrypted IPL
				binary_type = 1;
			}
		}

		// decrypt block
		if(binary_type==1)
		{
			if( pspKirkProc(ipl_buf,0x1000,ipl_buf,0x1000,0x01) < 0)
			{
Kprintf("Decrypt error\n");
				entry = 0;
				goto error;
			}
		}

		// load BLOCK
		top  = (ipl_buf[0]);
		size = (ipl_buf[1]);
		entry= (ipl_buf[2]);
		sum  = (ipl_buf[3]);
		src  = &(ipl_buf[4]);
//Kprintf("TOP %08X SIZE %08X ENTRY %08X SUM %08X\n",top,size,entry,sum);

		while(size)
		{
			*top++ = *src++;
			size -= 4;
		}

	}while(entry==0);
//Kprintf("readed %d bytes\n",ttl_read);
error:
	f_close(&FileObject);

	return entry;
}
// program entry point
int main()
{   
    int errCode; 
	struct LCD_Geometry *pointCurrent= &Current;
    struct LCD_Properties *pointProperties = &Properties;
    FILE lcd_str = FDEV_SETUP_STREAM(TerminalChar, NULL, _FDEV_SETUP_RW);
    stdout = &lcd_str;
	
	FRESULT rc;				/* Result code */
	DIR dir;				/* Directory object */
	FILINFO fno;			/* File information object */
	UINT bw, br, i;
	
   	USART_init();
   	SPI_MasterInit();
   	
   	SSD1289_Initalize();
	  
   	UTouch_InitTouch(0);
    LCD_Fill_Rectangle(0,0, 320,240,0x000000);
    terminalemulator();
    Terminal_Set_Properties(2, 1, 0xFFFFFF);
	//while(1) 	{ Paint_Program();}
	    
	printf("Serial Default Output");
	/* Init the MMC */
	printf("mmc_init\n");
	 //disk_initialize(0);
	mmc_init();
	
	
	
	/// Drive must be mounted before use  // Drive 0 - signifies SD System 
	/// Halt on anything other than mounting system okay
	errCode = f_mount(0, &filesystem);
	if (errCode != FR_OK)
	{
		printf("Error: f_mount failed, error code: %d\r", errCode);
		printf("Please refer to error list"); 
		while (1); // freeze
	}
	
	printf("\n Mounted File System: Type SD");
	// Draw BMP	
	
	printf("\nCreate a new file (hello.txt).\n");
	rc = f_open(&file, "HELLO.TXT", FA_WRITE | FA_CREATE_ALWAYS);
	
	printf("\nWrite a text data. (Hello world!)\n");
	rc = f_write(&file, "Hello world!\r\n", 14, &bw);
	printf("%u bytes written.\n", bw);

	printf("\nClose the file.\n");
	rc = f_close(&file);

	while(1){
		//printf("\nOpen root directory.\n");
		rc = f_opendir(&dir, "");
		
		//printf("\nDirectory listing...\n");
		for (;;) {
			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\n", fno.fname);
			else
				{
				//printf("%8lu  %s\n", fno.fsize, fno.fname);
				draw_bmp(0,0,fno.fname);
				}
		
		}
	}
}
Esempio n. 24
0
/**
  * @brief  Update the recorded data. 
  * @param  None
  * @retval None
  */
void WaveRecorderProcess(void)
{     
  /* Current size of the recorded buffer */
  uint32_t byteswritten = 0; 
  
  WaveCounter = 0;
  LEDsState = LEDS_OFF;
  
  /* Remove Wave file if it exists on USB Flash Disk */
  f_unlink (REC_WAVE_NAME);
  
  /* Open the file to write on it */
  if ((AppliState == APPLICATION_IDLE) || (f_open(&WavFile, REC_WAVE_NAME, FA_CREATE_ALWAYS | FA_WRITE) != FR_OK))
  {   
    while(1)
    {
      /* Toggle LED5 in infinite loop to signal that: USB Flash Disk is not connected/removed
         or an issue has occurred when creating/opening Wave file */
      BSP_LED_Toggle(LED5); 
    }
  }
  else
  {
    WaveRecStatus = 1;
  }
  /* Initialize header file */
  WavProcess_EncInit(DEFAULT_AUDIO_IN_FREQ, pHeaderBuff);
  
  /* Write the header Wave */
  f_write(&WavFile, pHeaderBuff, 44, (void *)&byteswritten);
  
  /* Increment the Wave counter */  
  BufferCtl.fptr = byteswritten;
  
  BufferCtl.offset = BUFFER_OFFSET_NONE;
  BSP_AUDIO_IN_Init(DEFAULT_AUDIO_IN_FREQ, DEFAULT_AUDIO_IN_BIT_RESOLUTION, DEFAULT_AUDIO_IN_CHANNEL_NBR);
  BSP_AUDIO_IN_Record((uint16_t*)&InternalBuffer[0], INTERNAL_BUFF_SIZE);
  
  /* Reset the time recording base variable */
  TimeRecBase = 0;
  ITCounter = 0;
  LEDsState = LED3_TOGGLE;
  
  while(AppliState != APPLICATION_IDLE)
  { 
    /* Wait for the recording time */  
    if (TimeRecBase <= DEFAULT_TIME_REC)
    {
      /* Check if there are Data to write in Usb Key */
      if(AUDIODataReady == 1)
      {
        /* write buffer in file */
        if(f_write(&WavFile, (uint8_t*)(WrBuffer+AUDIOBuffOffset), WR_BUFFER_SIZE, (void*)&byteswritten) != FR_OK)
        {
          Error_Handler();
        }
        BufferCtl.fptr += byteswritten;
        AUDIODataReady = 0;
      }
      
      /* User button pressed */
      if (CmdIndex != CMD_RECORD)
      {
        /* Stop Audio Recording */
        WaveRecorderStop();
        /* Switch Command Index to Play */
        CmdIndex = CMD_PLAY;
        /* Toggoling LED6 to signal Play */
        LEDsState = LED6_TOGGLE;
        break;
      }
    }
    else /* End of recording time TIME_REC */
    {
      /* Stop Audio Recording */
      WaveRecorderStop();
      /* Change Command Index to Stop */
      CmdIndex = CMD_STOP;
      /* Toggoling LED4 to signal Stop */
      LEDsState = LED4_TOGGLE;
      AUDIODataReady = 0;
      break;
    }
  }
  
  /* Update the data length in the header of the recorded Wave */    
  f_lseek(&WavFile, 0);
  
  /* Parse the wav file header and extract required information */
  WavProcess_HeaderUpdate(pHeaderBuff, &WaveFormat);
  f_write(&WavFile, pHeaderBuff, 44, (void*)&byteswritten);
  
  /* Close file and unmount MyFilesystem */
  f_close (&WavFile);
  f_mount(NULL, 0, 1);
  
  /* Change Command Index to Play */
  CmdIndex = CMD_PLAY;
}
Esempio n. 25
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 LED3 On: Upload Done */
      BSP_LED_On(LED3); 
      
      /* Close file and filesystem */
      f_close(&MyFile);
      f_mount(0, 0, 0);   
    }
    /* Keep LED4 OFF when Device connected */
    BSP_LED_Off(LED4); 
  }
  else
  {
    /* Message ROP active: Turn LED3 On and 
       Toggle LED4 in infinite loop */
    BSP_LED_On(LED3);
    Fail_Handler();
  }
}
Esempio n. 26
0
File: example.c Progetto: marekr/asf
/**
 * \brief Application entry point.
 *
 * \return Unused (ANSI-C compatibility).
 */
int main(void)
{
	char test_file_name[] = "0:sd_mmc_test.txt";
	Ctrl_status status;
	FRESULT res;
	FATFS fs;
	FIL file_object;

	const usart_serial_options_t usart_serial_options = {
		.baudrate   = CONF_TEST_BAUDRATE,
		.charlength = CONF_TEST_CHARLENGTH,
		.paritytype = CONF_TEST_PARITY,
		.stopbits   = CONF_TEST_STOPBITS,
	};

	irq_initialize_vectors();
	cpu_irq_enable();

	sysclk_init();
	board_init();
	stdio_serial_init(CONF_TEST_USART, &usart_serial_options);

	/* Initialize SD MMC stack */
	sd_mmc_init();

	printf("\x0C\n\r-- SD/MMC/SDIO Card Example on FatFs --\n\r");
	printf("-- Compiled: %s %s --\n\r", __DATE__, __TIME__);
	while (1) {
		printf("Please plug an SD, MMC or SDIO card in slot.\n\r");

		/* Wait card present and ready */
		do {
			status = sd_mmc_test_unit_ready(0);
			if (CTRL_FAIL == status) {
				printf("Card install FAIL\n\r");
				printf("Please unplug and re-plug the card.\n\r");
				while (CTRL_NO_PRESENT != sd_mmc_check(0)) {
				}
			}
		} while (CTRL_GOOD != status);

		printf("Mount disk (f_mount)...\r\n");
		memset(&fs, 0, sizeof(FATFS));
		res = f_mount(LUN_ID_SD_MMC_0_MEM, &fs);
		if (FR_INVALID_DRIVE == res) {
			printf("[FAIL] res %d\r\n", res);
			goto main_end_of_test;
		}
		printf("[OK]\r\n");

		printf("Create a file (f_open)...\r\n");
		test_file_name[0] = LUN_ID_SD_MMC_0_MEM + '0';
		res = f_open(&file_object,
				(char const *)test_file_name,
				FA_CREATE_ALWAYS | FA_WRITE);
		if (res != FR_OK) {
			printf("[FAIL] res %d\r\n", res);
			goto main_end_of_test;
		}
		printf("[OK]\r\n");

		printf("Write to test file (f_puts)...\r\n");
		if (0 == f_puts("Test SD/MMC stack\n", &file_object)) {
			f_close(&file_object);
			printf("[FAIL]\r\n");
			goto main_end_of_test;
		}
		printf("[OK]\r\n");
		f_close(&file_object);
		printf("Test is successful.\n\r");

main_end_of_test:
		printf("Please unplug the card.\n\r");
		while (CTRL_NO_PRESENT != sd_mmc_check(0)) {
		}
	}
}
Esempio n. 27
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(LED4);        
            }
          }
        }
      }
    }
  }
  
  /* Unlink the USB disk I/O driver */
  FATFS_UnLinkDriver(USBDISKPath);
}
Esempio n. 28
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"); 
        }
      }
    }
  }
}
static BaseType_t prvPerformCopy( const char *pcSourceFile,
									int32_t lSourceFileLength,
									const char *pcDestinationFile,
									char *pxWriteBuffer,
									size_t xWriteBufferLen )
{
int32_t lBytesRead = 0, lBytesToRead, lBytesRemaining;
F_FILE *pxFile;
BaseType_t 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;
}
Esempio n. 30
0
int main(void) {
    // TODO disable JTAG

    /* 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();

    // set the system clock to be HSE
    SystemClock_Config();

    // enable GPIO clocks
    __GPIOA_CLK_ENABLE();
    __GPIOB_CLK_ENABLE();
    __GPIOC_CLK_ENABLE();
    __GPIOD_CLK_ENABLE();

    // enable the CCM RAM
    __CCMDATARAMEN_CLK_ENABLE();

#if 0
#if defined(NETDUINO_PLUS_2)
    {
        GPIO_InitTypeDef GPIO_InitStructure;
        GPIO_InitStructure.GPIO_Speed = GPIO_Speed_25MHz;
        GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT;
        GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
        GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;

#if MICROPY_HW_HAS_SDCARD
        // Turn on the power enable for the sdcard (PB1)
        GPIO_InitStructure.GPIO_Pin = GPIO_Pin_1;
        GPIO_Init(GPIOB, &GPIO_InitStructure);
        GPIO_WriteBit(GPIOB, GPIO_Pin_1, Bit_SET);
#endif

        // Turn on the power for the 5V on the expansion header (PB2)
        GPIO_InitStructure.GPIO_Pin = GPIO_Pin_2;
        GPIO_Init(GPIOB, &GPIO_InitStructure);
        GPIO_WriteBit(GPIOB, GPIO_Pin_2, Bit_SET);
    }
#endif
#endif

    // basic sub-system init
    pendsv_init();
    timer_tim3_init();
    led_init();
#if MICROPY_HW_HAS_SWITCH
    switch_init0();
#endif

    int first_soft_reset = true;

soft_reset:

    // check if user switch held to select the reset mode
    led_state(1, 0);
    led_state(2, 1);
    led_state(3, 0);
    led_state(4, 0);
    uint reset_mode = 1;

#if MICROPY_HW_HAS_SWITCH
    if (switch_get()) {
        for (uint i = 0; i < 3000; i++) {
            if (!switch_get()) {
                break;
            }
            HAL_Delay(20);
            if (i % 30 == 29) {
                if (++reset_mode > 3) {
                    reset_mode = 1;
                }
                led_state(2, reset_mode & 1);
                led_state(3, reset_mode & 2);
                led_state(4, reset_mode & 4);
            }
        }
        // flash the selected reset mode
        for (uint i = 0; i < 6; i++) {
            led_state(2, 0);
            led_state(3, 0);
            led_state(4, 0);
            HAL_Delay(50);
            led_state(2, reset_mode & 1);
            led_state(3, reset_mode & 2);
            led_state(4, reset_mode & 4);
            HAL_Delay(50);
        }
        HAL_Delay(400);
    }
#endif

#if MICROPY_HW_ENABLE_RTC
    if (first_soft_reset) {
        rtc_init();
    }
#endif

    // more sub-system init
#if MICROPY_HW_HAS_SDCARD
    if (first_soft_reset) {
        sdcard_init();
    }
#endif
    if (first_soft_reset) {
        storage_init();
    }

    // GC init
    gc_init(&_heap_start, &_heap_end);

    // Change #if 0 to #if 1 if you want REPL on UART_6 (or another uart)
    // as well as on USB VCP
#if 0
    {
        mp_obj_t args[2] = {
            MP_OBJ_NEW_SMALL_INT(PYB_UART_6),
            MP_OBJ_NEW_SMALL_INT(115200),
        };
        pyb_uart_global_debug = pyb_uart_type.make_new((mp_obj_t)&pyb_uart_type,
                                                       ARRAY_SIZE(args),
                                                       0, args);
    }
#else
    pyb_uart_global_debug = NULL;
#endif

    // Micro Python init
    qstr_init();
    mp_init();
    mp_obj_list_init(mp_sys_path, 0);
    mp_obj_list_append(mp_sys_path, MP_OBJ_NEW_QSTR(MP_QSTR_0_colon__slash_));
    mp_obj_list_append(mp_sys_path, MP_OBJ_NEW_QSTR(MP_QSTR_0_colon__slash_lib));
    mp_obj_list_init(mp_sys_argv, 0);

    readline_init();

    pin_init();
    extint_init();

#if MICROPY_HW_HAS_LCD
    // LCD init (just creates class, init hardware by calling LCD())
    lcd_init();
#endif

    // local filesystem init
    {
        // try to mount the flash
        FRESULT res = f_mount(&fatfs0, "0:", 1);
        if (reset_mode == 3 || res == FR_NO_FILESYSTEM) {
            // no filesystem, or asked to reset it, so create a fresh one

            // LED on to indicate creation of LFS
            led_state(PYB_LED_R2, 1);
            uint32_t start_tick = HAL_GetTick();

            res = f_mkfs("0:", 0, 0);
            if (res == FR_OK) {
                // success creating fresh LFS
            } else {
                __fatal_error("could not create LFS");
            }

            // create empty main.py
            FIL fp;
            f_open(&fp, "0:/main.py", FA_WRITE | FA_CREATE_ALWAYS);
            UINT n;
            f_write(&fp, fresh_main_py, sizeof(fresh_main_py) - 1 /* don't count null terminator */, &n);
            // TODO check we could write n bytes
            f_close(&fp);

            // create .inf driver file
            f_open(&fp, "0:/pybcdc.inf", FA_WRITE | FA_CREATE_ALWAYS);
            f_write(&fp, fresh_pybcdc_inf, sizeof(fresh_pybcdc_inf) - 1 /* don't count null terminator */, &n);
            f_close(&fp);

            // create readme file
            f_open(&fp, "0:/README.txt", FA_WRITE | FA_CREATE_ALWAYS);
            f_write(&fp, fresh_readme_txt, sizeof(fresh_readme_txt) - 1 /* don't count null terminator */, &n);
            f_close(&fp);

            // keep LED on for at least 200ms
            sys_tick_wait_at_least(start_tick, 200);
            led_state(PYB_LED_R2, 0);
        } else if (res == FR_OK) {
            // mount sucessful
        } else {
            __fatal_error("could not access LFS");
        }
    }

    // make sure we have a 0:/boot.py
    {
        FILINFO fno;
#if _USE_LFN
        fno.lfname = NULL;
        fno.lfsize = 0;
#endif
        FRESULT res = f_stat("0:/boot.py", &fno);
        if (res == FR_OK) {
            if (fno.fattrib & AM_DIR) {
                // exists as a directory
                // TODO handle this case
                // see http://elm-chan.org/fsw/ff/img/app2.c for a "rm -rf" implementation
            } else {
                // exists as a file, good!
            }
        } else {
            // doesn't exist, create fresh file

            // LED on to indicate creation of boot.py
            led_state(PYB_LED_R2, 1);
            uint32_t start_tick = HAL_GetTick();

            FIL fp;
            f_open(&fp, "0:/boot.py", FA_WRITE | FA_CREATE_ALWAYS);
            UINT n;
            f_write(&fp, fresh_boot_py, sizeof(fresh_boot_py) - 1 /* don't count null terminator */, &n);
            // TODO check we could write n bytes
            f_close(&fp);

            // keep LED on for at least 200ms
            sys_tick_wait_at_least(start_tick, 200);
            led_state(PYB_LED_R2, 0);
        }
    }

    // root device defaults to internal flash filesystem
    uint root_device = 0;

#if defined(USE_DEVICE_MODE)
    usb_storage_medium_t usb_medium = USB_STORAGE_MEDIUM_FLASH;
#endif

#if MICROPY_HW_HAS_SDCARD
    // if an SD card is present then mount it on 1:/
    if (reset_mode == 1 && sdcard_is_present()) {
        FRESULT res = f_mount(&fatfs1, "1:", 1);
        if (res != FR_OK) {
            printf("[SD] could not mount SD card\n");
        } else {
            // use SD card as root device
            root_device = 1;

            if (first_soft_reset) {
                // use SD card as medium for the USB MSD
#if defined(USE_DEVICE_MODE)
                usb_medium = USB_STORAGE_MEDIUM_SDCARD;
#endif
            }
        }
    }
#else
    // Get rid of compiler warning if no SDCARD is configured.
    (void)first_soft_reset;
#endif

    // run <root>:/boot.py, if it exists
    if (reset_mode == 1) {
        const char *boot_file;
        if (root_device == 0) {
            boot_file = "0:/boot.py";
        } else {
            boot_file = "1:/boot.py";
        }
        FRESULT res = f_stat(boot_file, NULL);
        if (res == FR_OK) {
            if (!pyexec_file(boot_file)) {
                flash_error(4);
            }
        }
    }

    // turn boot-up LEDs off
    led_state(2, 0);
    led_state(3, 0);
    led_state(4, 0);

#if defined(USE_HOST_MODE)
    // USB host
    pyb_usb_host_init();
#elif defined(USE_DEVICE_MODE)
    // USB device
    if (reset_mode == 1) {
        usb_device_mode_t usb_mode = USB_DEVICE_MODE_CDC_MSC;
        if (pyb_config_usb_mode != MP_OBJ_NULL) {
            if (strcmp(mp_obj_str_get_str(pyb_config_usb_mode), "CDC+HID") == 0) {
                usb_mode = USB_DEVICE_MODE_CDC_HID;
            }
        }
        pyb_usb_dev_init(usb_mode, usb_medium);
    } else {
        pyb_usb_dev_init(USB_DEVICE_MODE_CDC_MSC, usb_medium);
    }
#endif

    timer_init0();

#if MICROPY_HW_ENABLE_RNG
    rng_init0();
#endif

    i2c_init0();
    spi_init0();

#if MICROPY_HW_HAS_MMA7660
    // MMA accel: init and reset
    accel_init();
#endif

#if MICROPY_HW_ENABLE_SERVO
    // servo
    servo_init();
#endif

#if MICROPY_HW_ENABLE_DAC
    // DAC
    dac_init();
#endif

    // now that everything is initialised, run main script
    if (reset_mode == 1 && pyexec_mode_kind == PYEXEC_MODE_FRIENDLY_REPL) {
        vstr_t *vstr = vstr_new();
        vstr_printf(vstr, "%d:/", root_device);
        if (pyb_config_main == MP_OBJ_NULL) {
            vstr_add_str(vstr, "main.py");
        } else {
            vstr_add_str(vstr, mp_obj_str_get_str(pyb_config_main));
        }
        FRESULT res = f_stat(vstr_str(vstr), NULL);
        if (res == FR_OK) {
            if (!pyexec_file(vstr_str(vstr))) {
                flash_error(3);
            }
        }
        vstr_free(vstr);
    }

#if MICROPY_HW_ENABLE_CC3K
    // wifi using the CC3000 driver
    pyb_wlan_init();
    pyb_wlan_start();
#endif

    // enter REPL
    // REPL mode can change, or it can request a soft reset
    for (;;) {
        if (pyexec_mode_kind == PYEXEC_MODE_RAW_REPL) {
            if (pyexec_raw_repl() != 0) {
                break;
            }
        } else {
            if (pyexec_friendly_repl() != 0) {
                break;
            }
        }
    }

    printf("PYB: sync filesystems\n");
    storage_flush();

    printf("PYB: soft reboot\n");

    first_soft_reset = false;
    goto soft_reset;
}