Beispiel #1
0
int cfg_validity_check_recent_games() {
  int err = 0, index, index_max, write_indices[10], rewrite_lastfile = 0;
  TCHAR fntmp[10][256];
  file_open(LAST_FILE, FA_READ);
  if(file_status == FILE_ERR) {
    return 0;
  }
  for(index = 0; index < 10 && !f_eof(&file_handle); index++) {
    f_gets(fntmp[index], 255, &file_handle);
  }
  if(!f_eof(&file_handle))
    index_max = 10;
  else
    index_max = index;
  file_close();
  for(index = 0; index < index_max; index++) {
    file_open((uint8_t*)fntmp[index], FA_READ);
    write_indices[index] = file_status;
    if(file_status != FILE_OK)
      rewrite_lastfile = 1;
    file_close();
  }
  if(rewrite_lastfile) {
    f_rename ((TCHAR*)LAST_FILE, (TCHAR*)LAST_FILE_BAK);
    file_open(LAST_FILE, FA_CREATE_ALWAYS | FA_WRITE);
    for(index = 0; index < index_max; index++) {
      if(write_indices[index] == FILE_OK) {
        err = f_puts(fntmp[index], &file_handle);
        err = f_putc(0, &file_handle);
      }
    }
    file_close();
  }
  return err;
}
Beispiel #2
0
void
cmd_cat(BaseSequentialStream *chp, int argc, char *argv[])
{
  FIL fp;
  uint8_t buffer[32];
  int br;

  if (argc < 1)
    return;

  if (f_open(&fp, (TCHAR*) *argv, FA_READ) != FR_OK)
    return;

  do
    {
      if (f_read(&fp, (TCHAR*) buffer, 32, (UINT*) &br) != FR_OK)
        return;

      chSequentialStreamWrite(chp, buffer, br);
    }
  while (!f_eof(&fp));

  f_close(&fp);

  chprintf(chp, "\r\n");
}
Beispiel #3
0
static void HighLevelTest() {
    FATFS FatFs;
    FIL FHandle;

    if (f_mount(&FatFs, "", 0) != FR_OK) {
        xil_printf("Failed to mount filesystem.\n\r");
        return;
    }

    if (f_open(&FHandle, "foo.txt", FA_READ) != FR_OK) {
        xil_printf("Failed to open foo.txt.\n\r");
        return;
    }

    while (!f_eof(&FHandle)) {
        if (f_gets(Buff, 100, &FHandle) == NULL) {
            xil_printf("Failed to read a line from foo.txt.\r\n");
            return;
        }

        xil_printf("%s", Buff);
    }

    f_close(&FHandle);

    xil_printf("Test Successful!\n\r");
}
Beispiel #4
0
static bool_t fatfsEOF(GFILE* f)
{
	if ( f_eof( (FIL*)f->obj ) != 0)
		return TRUE;
	else
		return FALSE;
}
Beispiel #5
0
void OnGetEndOfFile(nwazetMessageContext_t* nmc){
  fileObjectMap_t* fileObj = GetFileObjectById(nmc);
  if(fileObj){
    uint8_t eof = f_eof(fileObj->file);
    StartResponse(nmc, FR_OK, false);
    Put(nmc->respContext, (void*)&eof, sizeof(eof), 1);
    EndResponse(nmc);
  }
}
Beispiel #6
0
static void copy_file_task( void * pvParameters )
{
	FIL File;
	spiffs_DIR sf_dir;
	struct spiffs_dirent e;
	struct spiffs_dirent *pe = &e;
	s32_t err;
	void *temp = NULL;
	uint32_t remain;
	char *p_path_file = pvParameters;
	mn_screen_event_t fileLoad;

    choosedLinePosition = 0;
    choosedLine = 0;

	f_open(&File,p_path_file,FA_READ);

	spiffs_file *fd = &uspiffs[0].f;
	spiffs *fs = &uspiffs[0].gSPIFFS;

	SPIFFS_opendir(fs, "/", &sf_dir);

	do{
		pe = SPIFFS_readdir(&sf_dir, pe);
	}while(strcmp((const char *)pe->name,"config.met") == 0);


	*fd = SPIFFS_open_by_dirent(fs, pe, SPIFFS_RDWR, 0);
	if(*fd >= SPIFFS_OK)
	{
		err = SPIFFS_fremove(fs, *fd);
	}

	*fd = SPIFFS_open(fs, p_path_file, SPIFFS_CREAT | SPIFFS_RDWR | SPIFFS_DIRECT, 0);

	temp = pvPortMalloc( FS_PAGE_SIZE );
	while(!f_eof(&File))
	{
		f_read(&File,temp,FS_PAGE_SIZE,(UINT *)&remain);
		err = SPIFFS_write(fs, *fd, (u8_t *)temp, remain);
	}

	vPortFree(temp);
	vPortFree(p_path_file);
	f_close(&File);
	SPIFFS_close(fs, *fd);

	fileLoad.event = FILE_LOAD_EVENT;
	xQueueSend( menu.qEvent, &fileLoad, 0 );

    vTaskDelete( xHdlTaskFilecopy );

	while(1)
	{

	}
}
Beispiel #7
0
void cfg_dump_recent_games_for_snes(uint32_t address) {
  TCHAR fntmp[256];
  int index;
  file_open(LAST_FILE, FA_READ);
  for(index = 0; index < 10 && !f_eof(&file_handle); index++) {
    f_gets(fntmp, 255, &file_handle);
    sram_writestrn(strrchr((const char*)fntmp, '/')+1, address+256*index, 256);
  }
  ST.num_recent_games = index;
  file_close();
}
Beispiel #8
0
void Sound_t::ITask() {
    while(true) {
        eventmask_t EvtMsk = chEvtWaitAny(ALL_EVENTS);
#if 1 // ==== DMA done ====
        if(EvtMsk & VS_EVT_DMA_DONE) {
            ISpi.WaitBsyLo();                   // Wait SPI transaction end
            if(Clk.AHBFreqHz > 12000000) Loop(450); // Make a solemn pause
            XCS_Hi();                           // }
            XDCS_Hi();                          // } Stop SPI
            // Send next data if VS is ready
            if(IDreq.IsHi()) ISendNextData();   // More data allowed, send it now
            else IDreq.EnableIrq(IRQ_PRIO_MEDIUM); // Enable dreq irq
        }
#endif

        if(EvtMsk & VS_EVT_DREQ_IRQ) {
            chThdSleepMilliseconds(1);  // Make a pause after IRQ rise
            ISendNextData();
        }

        // Play new request
        if(EvtMsk & VS_EVT_COMPLETED) {
//        	Uart.Printf("\rComp");
            AddCmd(VS_REG_MODE, 0x0004);    // Soft reset
            if(IFilename != NULL) IPlayNew();
            else {
//                AmpfOff();    // switch off the amplifier to save energy
                if(IPAppThd != nullptr) chEvtSignal(IPAppThd, EVTMSK_PLAY_ENDS);  // Raise event if nothing to play
            }
        }
        // Stop request
        else if(EvtMsk & VS_EVT_STOP) {
//            Uart.Printf("\rStop");
            PrepareToStop();
        }

#if 1 // ==== Read next ====
        else if(EvtMsk & VS_EVT_READ_NEXT) {
//            Uart.Printf("\rreadNext; L= %u %u", Buf1.DataSz, Buf2.DataSz);
            FRESULT rslt = FR_OK;
            bool Eof = f_eof(&IFile);
            // Read next if not EOF
            if(!Eof) {
                if     (Buf1.DataSz == 0) { /*Uart.Printf(" r1");*/ rslt = Buf1.ReadFromFile(&IFile); }
                else if(Buf2.DataSz == 0) { /*Uart.Printf(" r2");*/ rslt = Buf2.ReadFromFile(&IFile); }
            }
            if(rslt != FR_OK) Uart.Printf("\rsndReadErr=%u", rslt);
            if(rslt == FR_OK and !Eof) StartTransmissionIfNotBusy();
        }
#endif
    } // while true
}
SDFS_status_type SDFS_readString(FIL* fp, char* text, uint32_t len) {
	SDFS_status_type ret_wert = SDFS_RD_STRING_ERR;
	int check;

	f_gets(text, len, fp);
	check = f_eof(fp);
	if (check != 0)
		return (SDFS_EOF);
	check = f_error(fp);
	if (check != 0)
		return (SDFS_RD_STRING_ERR);
	ret_wert = SDFS_OK;

	return (ret_wert);
}
Beispiel #10
0
/*-----------------------------------------------------------------------------------*/
unsigned long
fs_read(fs_file *file, char *buffer, int count)
{
  unsigned long read;
  if(f_eof(file)) {
    return FS_READ_EOF;
  }
  read = f_size(file) - f_tell(file);
  if(read > count) {
    read = count;
  }
  unsigned int _read = 0;
  f_read(file, buffer, read, &_read);
  read = _read;
  return(read);
}
Beispiel #11
0
/*
*********************************************************************************************************
*                                            App_DanceTask()
*
* Description : 机器人舞蹈管理任务
*
* Argument(s) : pdata.
*
* Return(s)   : none.
*
*********************************************************************************************************
*/
static void App_DanceTask(void *pdata)
{
	FRESULT result;
 	char ContentOfTheLine[6] = {0};
	
	uint32_t action = 0;
	uint32_t action_delay  = 0;
	
	INT8U err;

	while(1)
	{	
		OSSemPend(DanceSem,0,&err);
		
		/*##-1- 打开表情配置文件 */
		result = f_open(&CfgFile, "0:/dance/apple.txt", FA_OPEN_EXISTING | FA_READ);

		/*##-2- 逐行读取表情配置文件内容 */	
			do
			{
				
				f_gets(ContentOfTheLine,6,&CfgFile);
//				f_lseek(&CfgFile, f_tell(&CfgFile) + 2);
				sscanf((const char *)ContentOfTheLine, "%u %u" ,&action, &action_delay);
				
				ExecuteAction(action);
				OSTimeDlyHMSM(0,0,action_delay,10);
				ExecuteAction(127);
				
				
				if(f_eof(&CfgFile) != 0) //若文件读完,则将移动指针到文件头
				{
					//文件读完的时候,也就是舞蹈跳完的时候,跳出循环
					break;
					
				}

				
			}while(1);
			
		/*##-3- 关闭表情配置文件 */
			f_close(&CfgFile);
			
			OSTimeDlyHMSM(0,0,0,10);
		
	}
}
Beispiel #12
0
void Sound_t::ITask() {
    while(true) {
        eventmask_t EvtMsk = chEvtWaitAny(ALL_EVENTS);
        if(EvtMsk & VS_EVT_DMA_DONE) {
            ISpi.WaitBsyLo();               // Wait SPI transaction end
            XCS_Hi();                       // }
            XDCS_Hi();                      // } Stop SPI
            if(IDreq.IsHi()) ISendNextData();   // More data allowed, send it now
            else {
                chThdSleepMilliseconds(1); // Allow VS to end up with data processing
                chSysLock();
                IDreq.EnableIrq(IRQ_PRIO_MEDIUM); // Enable dreq irq
                chSysUnlock();
            }
        }

        if(EvtMsk & VS_EVT_DREQ_IRQ) ISendNextData();

        // Play new request
        if(EvtMsk & VS_EVT_COMPLETED) {
//        	Uart.Printf("\rComp");
            AddCmd(VS_REG_MODE, 0x0004);    // Soft reset
            if(IFilename != NULL) IPlayNew();
            else if(IPThd != nullptr) chEvtSignal(IPThd, EVTMASK_PLAY_ENDS);  // Raise event if nothing to play
        }
        // Stop request
        else if(EvtMsk & VS_EVT_STOP) {
//            Uart.Printf("\rStop");
            PrepareToStop();
        }
        // Data read request
        else if(EvtMsk & VS_EVT_READ_NEXT) {
//            Uart.Printf("\rreadNext");
            FRESULT rslt = FR_OK;
            bool EofAtStart = f_eof(&IFile);
            // Read next if not EOF
            if(!EofAtStart) {
                if     (Buf1.DataSz == 0) { /*Uart.Printf("1");*/ rslt = Buf1.ReadFromFile(&IFile); }
                else if(Buf2.DataSz == 0) { /*Uart.Printf("2");*/ rslt = Buf2.ReadFromFile(&IFile); }
            }
            // Check if was EOF or if error occured during reading. Do not do it if EOF occured during reading.
//            if(rslt != FR_OK) Uart.Printf("\rsndReadErr=%u", rslt);
            if((rslt != FR_OK) or EofAtStart) PrepareToStop();
            else StartTransmissionIfNotBusy();
        }
    } // while true
}
Beispiel #13
0
/*******************************************************************************
* Function Name  : CanHexProg request, server
* Description    : dekodira in razbije vrstice hex fila na 	pakete 8 bytov in jih
*								 : pošlje na CAN bootloader
* Input          : pointer na string, zaporedne vrstice hex fila, <cr> <lf> ali <null> niso nujni
* Output         : 
* Return         : 0 ce je checksum error sicer eof(-1). bootloader asinhrono odgovarja z ACK message
*				 				 : za vsakih 8 bytov !!!
*******************************************************************************/							
int					HexrecOk(char *filename, FIL *f) {
int	 				xa=0,a,amax=0,amin=INT_MAX;
char				*p,s[64];
						if(f_open(f,filename,FA_READ)==FR_OK) {
							while(!f_eof(f)) {
								p=s;
								f_gets(p,64,f);
								if(*p != ':') {
									f_close(f);
									return 0;
								}
								if(HexChecksumError(++p)) {
									f_close(f);
									return 0;
								}
								a=(xa<<16)+str2hex(&p,4)+str2hex(&p,2);														// set address
								switch(str2hex(&p,2)) {
									case 00: 																												// data record
										if(a<amin)
											amin=a;
										if(a>amax)
											amax=a;
										break;
									case 04:
										xa=str2hex(&p,4);	
										break;
									default:
										break;
								}
							}
							if(amin == (int)__Vectors) {
								f_close(f);
								return 0;
							}
							f_lseek(f,0);
							return amin;
						}
						return NULL;
}
Beispiel #14
0
int TM_ETHERNETSERVER_ReadFileCallback(struct fs_file* file, char* buffer, int count) {
	uint32_t readed;
	
	/* print debug */
	printf("Trying to read %d bytes from file %s\n", count, file->file_name);
	
	/* End of file? */
	if (f_eof(&fil[file->id])) {
		return -1;
	}
	
	/* Read max block */
	if (count > 65535) {
		count = 65535;
	}
	
	/* Read data */
	f_read(&fil[file->id], buffer, count, &readed);
	
	/* Return number of bytes read */
	return readed;
}
Beispiel #15
0
// MP3 decode player
void MP3Player(void)
{
    FRESULT res;
    uint8_t *ReadStart;
    uint8_t *GuardPtr;
    volatile uint8_t u8PCMBufferTargetIdx = 0;
    volatile uint32_t pcmbuf_idx, i;
    volatile unsigned int Mp3FileOffset=0;
    uint16_t sampleL, sampleR;

    pcmbuf_idx = 0;
    memset((void *)&audioInfo, 0, sizeof(audioInfo));

    /* Parse MP3 header */
    MP3_ParseHeaderInfo(MP3_FILE);

    /* First the structures used by libmad must be initialized. */
    mad_stream_init(&Stream);
    mad_frame_init(&Frame);
    mad_synth_init(&Synth);

    /* Open MP3 file */
    res = f_open(&mp3FileObject, MP3_FILE, FA_OPEN_EXISTING | FA_READ);
    if (res != FR_OK) {
        printf("Open file error \r\n");
        return;
    }

    /* Open I2S1 interface and set to slave mode, stereo channel, I2S format */
    I2S_Open(I2S1, I2S_MODE_SLAVE, 16000, I2S_DATABIT_16, I2S_STEREO, I2S_FORMAT_I2S, I2S_I2S);

    /* Initialize WAU8822 codec */
    WAU8822_Setup();

    /* Configure wau8822 for specific sampling rate */
    WAU8822_ConfigSampleRate(audioInfo.mp3SampleRate);

    /* Set MCLK and enable MCLK */
    I2S_EnableMCLK(I2S1, 12000000);

    while(1) {
        if(Stream.buffer==NULL || Stream.error==MAD_ERROR_BUFLEN) {
            if(Stream.next_frame != NULL) {
                /* Get the remaining frame */
                Remaining = Stream.bufend - Stream.next_frame;
                memmove(MadInputBuffer, Stream.next_frame, Remaining);
                ReadStart = MadInputBuffer + Remaining;
                ReadSize = FILE_IO_BUFFER_SIZE - Remaining;
            } else {
                ReadSize = FILE_IO_BUFFER_SIZE,
                ReadStart = MadInputBuffer,
                Remaining = 0;
            }

            /* read the file from SDCard */
            res = f_read(&mp3FileObject, ReadStart, ReadSize, &ReturnSize);
            if((res != FR_OK) || f_eof(&mp3FileObject)) {
                printf("Stop !(%x)\n\r", res);
                goto stop;
            }

            /* if the file is over */
            if (ReadSize > ReturnSize) {
                GuardPtr=ReadStart+ReadSize;
                memset(GuardPtr,0,MAD_BUFFER_GUARD);
                ReadSize+=MAD_BUFFER_GUARD;
            }

            Mp3FileOffset = Mp3FileOffset + ReturnSize;
            /* Pipe the new buffer content to libmad's stream decoder
                     * facility.
            */
            mad_stream_buffer(&Stream,MadInputBuffer,ReadSize+Remaining);
            Stream.error=(enum  mad_error)0;
        }

        /* decode a frame from the mp3 stream data */
        if(mad_frame_decode(&Frame,&Stream)) {
            if(MAD_RECOVERABLE(Stream.error)) {
                /*if(Stream.error!=MAD_ERROR_LOSTSYNC ||
                   Stream.this_frame!=GuardPtr)
                {
                }*/
                continue;
            } else {
                /* the current frame is not full, need to read the remaining part */
                if(Stream.error==MAD_ERROR_BUFLEN) {
                    continue;
                } else {
                    printf("Something error!!\n");

                    /* play the next file */
                    audioInfo.mp3FileEndFlag = 1;
                    goto stop;
                }
            }
        }

        /* Once decoded the frame is synthesized to PCM samples. No errors
        * are reported by mad_synth_frame();
        */
        mad_synth_frame(&Synth,&Frame);

        //
        // decode finished, try to copy pcm data to audio buffer
        //

        if(audioInfo.mp3Playing) {
            //if next buffer is still full (playing), wait until it's empty
            if(aPCMBuffer_Full[u8PCMBufferTargetIdx] == 1)
                while(aPCMBuffer_Full[u8PCMBufferTargetIdx]);
        } else {

            if((aPCMBuffer_Full[0] == 1) && (aPCMBuffer_Full[1] == 1 )) {       //all buffers are full, wait
                StartPlay();
            }
        }

        for(i=0; i<(int)Synth.pcm.length; i++) {
            /* Get the left/right samples */
            sampleL = Synth.pcm.samples[0][i];
            sampleR = Synth.pcm.samples[1][i];

            /* Fill PCM data to I2S(PDMA) buffer */
            aPCMBuffer[u8PCMBufferTargetIdx][pcmbuf_idx++] = sampleR | (sampleL << 16);

            /* Need change buffer ? */
            if(pcmbuf_idx == PCM_BUFFER_SIZE) {
                aPCMBuffer_Full[u8PCMBufferTargetIdx] = 1;      //set full flag
                u8PCMBufferTargetIdx ^= 1;

                pcmbuf_idx = 0;
//               printf("change to ==>%d ..\n", u8PCMBufferTargetIdx);
                /* if next buffer is still full (playing), wait until it's empty */
                if((aPCMBuffer_Full[u8PCMBufferTargetIdx] == 1) && (audioInfo.mp3Playing))
                    while(aPCMBuffer_Full[u8PCMBufferTargetIdx]);
            }
        }
    }

stop:

    printf("Exit MP3\r\n");

    mad_synth_finish(&Synth);
    mad_frame_finish(&Frame);
    mad_stream_finish(&Stream);

    f_close(&mp3FileObject);
    StopPlay();
}
Beispiel #16
0
int flashIHexFile(FIL* file)
{
    IHexRecord irec;
    flashsector_t sector;
    bool erasedSectors[FLASH_SECTOR_COUNT] = { FALSE };
    flashaddr_t baseAddress = 0;
    flashaddr_t address = 0;

    while (Read_IHexRecord(&irec, file) == IHEX_OK)
    {
        switch (irec.type)
        {
        case IHEX_TYPE_00:    /**< Data Record */
            /* Compute the target address in flash */
            address = baseAddress + irec.address;

            /* Erase the corresponding addresses if needed */
            for (sector = flashSectorAt(address); sector <= flashSectorAt(address + irec.dataLen - 1); ++sector)
            {
                /* Check if the sector has been erased during this IHex flashing procedure to
                   prevent erasing already written data */
                if (erasedSectors[sector] == TRUE)
                    continue;

                /* Check if the sector in flash needs to be erased */
                if (flashIsErased(flashSectorBegin(sector), flashSectorSize(sector)) == FALSE)
                {
                    /* Erase the sector */
                    if (flashSectorErase(sector) != FLASH_RETURN_SUCCESS)
                        return BOOTLOADER_ERROR_BADFLASH;
                }

                /* Set the erased flag to prevent erasing the same sector twice during
                   the IHex flashing procedure */
                erasedSectors[sector] = TRUE;
            }

            /* Write the data in flash */
            if (flashWrite(address, (const char*)irec.data, irec.dataLen) != FLASH_RETURN_SUCCESS)
                return BOOTLOADER_ERROR_BADFLASH;
            break;

        case IHEX_TYPE_04:    /**< Extended Linear Address Record */
            /* Compute the base address of the following data records */
            baseAddress = irec.data[0];
            baseAddress <<= 8;
            baseAddress += irec.data[1];
            baseAddress <<= 16;
            break;

        case IHEX_TYPE_01:    /**< End of File Record */
            /* Check that the end of file record is at the end of the file... */
            return f_eof(file) ? BOOTLOADER_SUCCESS : BOOTLOADER_ERROR_BADHEX;

        case IHEX_TYPE_05:    /**< Start Linear Address Record */
            /* Ignored */
            break;

        case IHEX_TYPE_02:    /**< Extended Segment Address Record */
        case IHEX_TYPE_03:    /**< Start Segment Address Record */
            /* Not supported */
            return BOOTLOADER_ERROR_BADHEX;
        }
    }

    return BOOTLOADER_ERROR_BADHEX;
}
Beispiel #17
0
void Config_Read(void)
{
	char    buf[80];
	size_t  len;
	char    *name;
	char    *result;
	
	int32_t val;
	int32_t dz_elev = 0;

	FRESULT res;
	
	res = f_open(&Main_file, "config.txt", FA_READ);
	if (res != FR_OK)
	{
		res = f_open(&Main_file, "config.txt", FA_WRITE | FA_CREATE_ALWAYS);
		if (res != FR_OK) 
		{
			Main_activeLED = LEDS_RED;
			LEDs_ChangeLEDs(LEDS_ALL_LEDS, Main_activeLED);
			return ;
		}

		Config_WriteString_P(Config_default, &Main_file);
		f_close(&Main_file);

		res = f_open(&Main_file, "config.txt", FA_READ);
		if (res != FR_OK)
		{
			Main_activeLED = LEDS_RED;
			LEDs_ChangeLEDs(LEDS_ALL_LEDS, Main_activeLED);
			return ;
		}
	}
	
	while (!f_eof(&Main_file))
	{
		f_gets(buf, sizeof(buf), &Main_file);

		len = strcspn(buf, ";");
		buf[len] = 0;
		
		name = strtok(buf, " \t:");
		if (name == 0) continue ;
		
		result = strtok(0, " \t:");
		if (result == 0) continue ;
		
		val = atol(result);
		
		#define HANDLE_VALUE(s,w,r,t) \
			if ((t) && !strcmp_P(name, (s))) { (w) = (r); }

		HANDLE_VALUE(Config_Model,     UBX_model,        val, val >= 0 && val <= 8);
		HANDLE_VALUE(Config_Rate,      UBX_rate,         val, val >= 100);
		HANDLE_VALUE(Config_Mode,      UBX_mode,         val, val >= 0 && val <= 4);
		HANDLE_VALUE(Config_Min,       UBX_min,          val, TRUE);
		HANDLE_VALUE(Config_Max,       UBX_max,          val, TRUE);
		HANDLE_VALUE(Config_Limits,    UBX_limits,       val, val >= 0 && val <= 2);
		HANDLE_VALUE(Config_Volume,    Tone_volume,      8 - val, val >= 0 && val <= 8);
		HANDLE_VALUE(Config_Mode_2,    UBX_mode_2,       val, (val >= 0 && val <= 4) || (val >= 8 && val <= 9));
		HANDLE_VALUE(Config_Min_Val_2, UBX_min_2,        val, TRUE);
		HANDLE_VALUE(Config_Max_Val_2, UBX_max_2,        val, TRUE);
		HANDLE_VALUE(Config_Min_Rate,  UBX_min_rate,     val * TONE_RATE_ONE_HZ / 100, val >= 0);
		HANDLE_VALUE(Config_Max_Rate,  UBX_max_rate,     val * TONE_RATE_ONE_HZ / 100, val >= 0);
		HANDLE_VALUE(Config_Flatline,  UBX_flatline,     val, val == 0 || val == 1);
		HANDLE_VALUE(Config_Sp_Mode,   UBX_sp_mode,      val, val >= 0 && val <= 6);
		HANDLE_VALUE(Config_Sp_Units,  UBX_sp_units,     val, val >= 0 && val <= 1);
		HANDLE_VALUE(Config_Sp_Rate,   UBX_sp_rate,      val * 1000, val >= 0 && val <= 32);
		HANDLE_VALUE(Config_Sp_Dec,    UBX_sp_decimals,  val, val >= 0 && val <= 2);
		HANDLE_VALUE(Config_Sp_Volume, Tone_sp_volume,   8 - val, val >= 0 && val <= 8);
		HANDLE_VALUE(Config_V_Thresh,  UBX_threshold,    val, TRUE);
		HANDLE_VALUE(Config_H_Thresh,  UBX_hThreshold,   val, TRUE);
		HANDLE_VALUE(Config_Use_SAS,   UBX_use_sas,      val, val == 0 || val == 1);
		HANDLE_VALUE(Config_Window,    UBX_alarm_window, val * 1000, TRUE);
		HANDLE_VALUE(Config_DZ_Elev,   dz_elev,          val * 1000, TRUE);
		HANDLE_VALUE(Config_TZ_Offset, Log_tz_offset,    val, TRUE);
		HANDLE_VALUE(Config_Sp_Test,   UBX_sp_test,      val, val == 0 || val == 1);
		
		#undef HANDLE_VALUE
		
		if (!strcmp_P(name, Config_Alarm_Elev))
		{
			UBX_alarms[UBX_num_alarms].elev = val * 1000 + dz_elev;
		}
		if (!strcmp_P(name, Config_Alarm_Type) && val != 0)
		{
			UBX_alarms[UBX_num_alarms].type = val;
			++UBX_num_alarms;
		}
	}
	
	f_close(&Main_file);
}
Beispiel #18
0
void HandleEvent()
{
	U8 RefrashCounter;
	EVENT Evt = Player.Event;

	ClearEvent();
	switch(Evt)
	{
		case EV_NULL:
			break;

		case EV_DREQ:
			if(BufCnt>=32)
			{
				VS_Send32Byte(DataPtr);
				DataPtr += 32;
				BufCnt -= 32;
			}
			else
				GenerateEvent(EV_BUFEMPTY);
			break;

		case EV_BUFEMPTY:
			if(f_eof(Player.currFile))
				GenerateEvent(EV_END);
			else
			{
				f_read((Player.currFile), DataBuf, BUFSIZE, &BufCnt);
				DataPtr = DataBuf;
			}
			RefrashCounter++;
			if(RefrashCounter == Refrash){
			LCDClean();
			LCDPutString("Now Playing #");
			LCDPutUInt(Player.SongNum);}
			break;

		case EV_NEXT:
			VS_CancelDecoding();
			if(++Player.SongNum  > Player.TotalSongNum)
				Player.SongNum= 1;
			scan_files_open (Player.currFile,"/",Player.SongNum);
			GenerateEvent(EV_BUFEMPTY);
			RefrashCounter = Reset;
			break;

		case EV_PREVIOUS:
			VS_CancelDecoding();
			if(--Player.SongNum  == 0)
				Player.SongNum= Player.TotalSongNum;
			scan_files_open (Player.currFile,"/",Player.SongNum);
			GenerateEvent(EV_BUFEMPTY);
			RefrashCounter = Reset;
			break;

		case EV_MODE:
			Player.Mode++;
			Player.Mode %= 3;
			SetLED(Player.Mode);
			LCDClean();
			LCDPutString("Mode: ");
			if(Player.Mode==SM_BASS)
			LCDPutString("Bass");
			if(Player.Mode==SM_TREBLE)
			LCDPutString("Treble");
			if(Player.Mode==SM_SONG)
			LCDPutString("Song");
			RefrashCounter = Reset;
			break;

		case EV_BASSTREB:
			VS_SetBassTreble(Player.Bass,Player.Treble);
			LCDClean();
			LCDPutString("Bass: ");
			LCDPutUInt(Player.Bass);
			if(Player.Mode==SM_BASS)
			LCDPutString(" <--");
			LCDChangeLine();
			LCDPutString("Treble: ");
			LCDPutInt(Player.Treble);
			if(Player.Mode==SM_TREBLE)
			LCDPutString(" <--");
			RefrashCounter = Reset;
			break;

		case EV_VOLUME:
			VS_SetVol(Player.Volume);
			LCDClean();
			LCDPutString("Now Playing #");
			LCDPutUInt(Player.SongNum);
			LCDChangeLine();
			LCDPutString("Volume: ");
			LCDPutUInt(((ADC0+48)/41));//0~100
			LCD_DataWrite('%');
			RefrashCounter = Reset;
			break;

		case EV_PAUSE:
//			ConsoleWrite("Paused.\n");
			Player.Status = PS_PAUSED;
			LCDClean();
			LCDPutString("|| Paused....");
			break;

		case EV_PLAY:
//			ConsoleWrite("Resume Playing...\n");
			Player.Status = PS_PLAYING;
			LCDClean();
			LCDPutString("Now Playing: #");
			LCDPutUInt(Player.SongNum);
			break;

		case EV_END:
			Player.Event = EV_NEXT;
			LCDClean();
			LCDPutString("End.");
			break;

		default:
			break;
	}
}
Beispiel #19
0
int vfs_eof( vfs_file_t *fp )
{
	return f_eof( (FIL*)fp );
}
Beispiel #20
0
static bool fill_mp3_buffer(FIL *fp, int buffer_number) {

	unsigned int   br;
	unsigned int   btr;

	static char    file_read_buffer[FILE_READ_BUFFER_SIZE];
	static char *  file_read_ptr = file_read_buffer;
	static uint    file_bytes = 0;

	// Copy of above pointers/indicators for roll back if MP3 frame decode failure.
	char *         copy_file_read_ptr;
	uint           copy_file_bytes;

	bool   		   need_data= true;

	FRESULT res;
	int offset,err;
	bool out_of_data = false;

	int copy_samples;

	int i;

	// Turn on blue LED to indicate decoding start.
	GPIO_SetBits(GPIOD, GPIO_Pin_15);

	do {
		if ( need_data ) {
			// Reset the file read buffer
			memmove(file_read_buffer,file_read_ptr,file_bytes);
			file_read_ptr = file_read_buffer;

			// Fill the file read buffer
			btr =      FILE_READ_BUFFER_SIZE - file_bytes;
			res =      f_read(fp, file_read_buffer + file_bytes , btr, &br);
			file_bytes += br;

			if ( res != FR_OK ) {
				// File access failure, dump out.
				out_of_data  = true;
				break;
			}

			// Flag when file is completely read complete.
			out_of_data = f_eof(fp);

			// Clear flag for needing more data.
			need_data = false;
		}

		// Find the next frame in the MP3 file
		offset = MP3FindSyncWord((unsigned char*)file_read_ptr, file_bytes);

		if ( offset < 0 ) {
			// This should never happen unless we have a badly formatted frame.
			// Just exit out and hope the next call gets a good frame.
			need_data = true;
			continue;
		}

		copy_file_bytes    = file_bytes - offset;
		copy_file_read_ptr = file_read_ptr + offset;

		// Decode this frame.
		err = MP3Decode(hMP3Decoder, (unsigned char**)&copy_file_read_ptr, (uint*)&copy_file_bytes, audio_read_buffer + buffer_number * AUDIO_LOCAL_BUFFER_SIZE, 0);

		if (err) {
			/* error occurred */
			switch (err) {
			case ERR_MP3_INDATA_UNDERFLOW:
				// Next loop will refill buffer.
				need_data = true;
				continue;
			case ERR_MP3_MAINDATA_UNDERFLOW:
				// Next loop will refill buffer.
				need_data = true;
				continue;
			case ERR_MP3_FREE_BITRATE_SYNC:
			default:
				out_of_data = true;
				break;
			}
		} else {

			file_bytes    = copy_file_bytes;
			file_read_ptr = copy_file_read_ptr;

			// no error
			MP3GetLastFrameInfo(hMP3Decoder, &mp3FrameInfo);

			// Duplicate data in case of mono to maintain playback speed
			if (mp3FrameInfo.nChans == 1) {
				for(i = mp3FrameInfo.outputSamps;i >= 0;i--) 	{
					audio_read_buffer[ buffer_read * AUDIO_LOCAL_BUFFER_SIZE + 2 * i]     = audio_read_buffer[ buffer_read * AUDIO_LOCAL_BUFFER_SIZE + i];
					audio_read_buffer[ buffer_read * AUDIO_LOCAL_BUFFER_SIZE + 2 * i + 1] = audio_read_buffer[ buffer_read * AUDIO_LOCAL_BUFFER_SIZE + i];
				}
				mp3FrameInfo.outputSamps *= 2;
			}

			audio_buffer_length[ buffer_number ] = mp3FrameInfo.outputSamps;
		}

	} while( offset < 0 && res == FR_OK && !out_of_data );

	// Turn off blue LED to indicate decoding finish.
	GPIO_ResetBits(GPIOD, GPIO_Pin_15);
	return(out_of_data);
}
Beispiel #21
0
bool FatFs::File::eof()
{
    return f_eof(&file);
}
Beispiel #22
0
int SDFile::available(void) {
  if ( f_eof(&file) ) 
    return 0;
  return f_size(&file) - f_tell(&file);
}
Beispiel #23
0
/*
 * read_file()
 *
 * Reads the file with the given name.
 * This function reads blocks of 512 bytes
 */
void read_file_test()
{
	FIL file;
	FRESULT res;
	UINT read;
	uint32_t sum_read;
	uint32_t i, idx;
	uint32_t data_err;
	res = f_open(&file, "test.txt", FA_READ);
	if(res != FR_OK)
	{
		printf("Cannot open file for reading:%u\r\n", res);
		return;
	}
	sum_read = 0;
	i=0;
	data_err = 0;
	uint8_t Buffer[512];
	uint32_t elapsed=0;
	while(!f_eof(&file))
	{
		uint32_t start=HAL_GetTick();
		res = f_read(&file, Buffer, 512, &read);
		uint32_t end = HAL_GetTick();
		elapsed+=(end-start);

		sum_read += read;

		if(res != FR_OK)
		{
			printf("Error reading file: %u", res);
			break;
		} else
		{
			/*
			 * Check data
			 */
			for(idx=0; idx<read; idx++)
			{
				if(Buffer[idx] != (((i * 3) + (idx * 5)) & 0xff)) data_err++;
			}
			i++;


			if(read != 512)
			{
				printf("Read incomplete - read %d bytes\n", (int)read);
			}
		}
	}
	if(data_err) printf("Error: data does not match expected pattern\n\r");

	res = f_close(&file);
	if(res != FR_OK)
		printf("Error closing file%u\r\n", res);


	uint32_t speed= sum_read / elapsed;
	printf("Read test complete: %u kbytes/s\n\r", (unsigned int)(speed));
	delete_file("test.txt");
}
/****************************************************
  Function:
    int FSfeof( FSFILE * stream )
  Summary:
    Indicate whether the current file position is at the end
  Conditions:
    File is open in a read mode
  Input:
    stream -  Pointer to the target file
  Return Values:
    Non-Zero - EOF reached
    0 - Not at end of File
  Description:
    Wrapper function for Microchip MDDFS Library.
  ****************************************************/
int FSfeof( FSFILE * stream )
{
    return f_eof(stream);
}
Beispiel #25
0
bool CFile::eof()
{
    bool rc;
    rc = f_eof(&mFileDescriptor) != 0;
    return rc;
}
Beispiel #26
0
int
main(int argc, char* argv[])
{
	volatile FATFS 		fatfs = {0};
	volatile FRESULT 	result;
	uint8_t 			fifo_command = 0;
	uint8_t				file_index = 0;



    ResetRCC();
    RCC_SetClockFrequency(PLLM_macro, PLLN_macro, PLLQ_macro, PLLP_macro);

    //  Enable clocks for the peripherals
    /*
     * 	GPIOA	-	NEC_CONTROLLER, TIM1 PWM, DAC
     * 	GPIOB	- 	SPI2
     * 	GPIOC	-	HD44780 Led Display
     * 	GPIOD	-	LED diodes, USART2(Log)
     */
    RCC->AHB1ENR |= RCC_AHB1ENR_GPIOAEN | RCC_AHB1ENR_GPIOBEN |  RCC_AHB1ENR_GPIOCEN | RCC_AHB1ENR_GPIODEN;
    RCC->APB2ENR |= RCC_APB2ENR_TIM1EN;
    RCC->APB1ENR |= RCC_APB1ENR_TIM7EN | RCC_APB1ENR_SPI2EN | RCC_APB1ENR_USART2EN | RCC_APB1ENR_DACEN;


    /*< Configure board's leds to signal states */
    GPIO_OutputConfigure(GPIOD, PIN_12 | PIN_13 | PIN_14 | PIN_15, gpio_otyper_push_pull, gpio_speed_high, gpio_pupd_pull_down);
    /*< Configure NVIC Interrupt controller */
    //  Set two bits (out of four) as the main priority. The rest bits are used for preemptive priorities
    NVIC_SetPriorityGrouping(NVIC_PriorityGroup_2);
    NVIC_Enable_Interrupts();

    /*< Configure USART2 module to create program log */
    UART_Config(USART2, USART_CR1_UE | USART_CR1_TE, 19200,false);
    GPIO_AlternateFunctionPrepare(GPIOD, PIN_5, gpio_otyper_push_pull, gpio_speed_medium, gpio_pupd_pull_up);
    GPIO_AlternateFunctionSet(GPIOD,PIN_5, AF7);
    Log_Uart("##### LOG START #####\n\r");

    /*<	MCO2 Pin configuration to watch the CPU Clock signal with an oscilloscope*/
    Log_Uart("Clock output pin configuration in progress...\n\r");
    RCC->CFGR |= RCC_CFGR_MCO2PRE_2 | RCC_CFGR_MCO2PRE_1;
    RCC->CFGR &= ~RCC_CFGR_MCO2;
    GPIO_AlternateFunctionPrepare(GPIOC, PIN_9, gpio_otyper_push_pull, gpio_speed_fast, gpio_pupd_no_pull);
    GPIO_AlternateFunctionSet(GPIOC,PIN_9, AF0);

    /*<	SysTick configuration */
    Log_Uart("SysTick configuration in progress...\n\r");
    SysTick_Config(SYSTICK_CLK_DIVIDER);	//	Configure SysTick to make a tick every 1 us
    SysTick_CLKSourceConfig(SysTick_CLKSource_HCLK);


    /*< PWM signal configuration */
    Log_Uart("PWM generation module configuration in progress...\n\r");
    GPIO_AlternateFunctionPrepare(GPIOA, PIN_8, gpio_otyper_push_pull, gpio_speed_fast, gpio_pupd_pull_down);
    GPIO_AlternateFunctionSet(GPIOA, PIN_8, AF1);	//	Pin for PWM signal
    TIM_PWMConfigure(TIM1, 168, 5000, 4000, TIM_Channel_1);
    TIM_Start(TIM1);
    /*< HD44780 display configuration */
    LCD_Config();


    /*< Remote controller receiver initialization */
    Log_Uart("IR remote controller configuration in progress...\n\r");
    NEC_Remote_Init();
    TIM_Start(TIM6);

    /*< SPI Module configuration. It is used to communicate with the SD card */
    Log_Uart("SPI module configuration in progress...\n\r");
    SPI_Master_Init(SPI2, SPI_FREQ_PCLK_DIV_256, SPI_CPOL0_CPHA0, SPI_BIT_ORDER_MSB_FIRST, true);

    /*< DAC configuration */
    DAC_Init(dac_dual_channel_simultanous, dac_trigger_tim7, true);

    /*< Timer 7 used to trigger the DAC config */
    TIM_Basic_Continuous_Counting(TIM7, 12);

    /*< Remote Controller command fifo configuration */
    Log_Uart("FIFO configuration in progress...\n\r");
    Fifo_Init(&remote_command_fifo, remote_command_queue, sizeof(remote_command_queue));


    TIM6->CR1 |= TIM_CR1_CEN;	/*< Continuously ticking timer, used in NEC IR remote */

    Log_Uart("Configuration OK!\n\r");




    TCHAR disk[] = "0";
    UINT byte_number;
    result = f_mount(&fatfs, disk, 1);

    uint16_t bytes;
   /* result = SD_Find_File_Name_Containing("/", "*.wav");
    result = SD_Get_File_List("/");
    result = f_open(&sd_current_file, &sd_files_list[3], FA_READ);
    result = Wav_Get_File_Header(&sd_current_file);
*/
    //	Initially, get the files list
    state = STATE_GET_FILES_LIST;

  while(1)
  {
	  switch(state)
	  {
		 /* case STATE_WAIT:
			  break;*/

		  case	STATE_GET_FILES_LIST:
		  {
			  result = SD_Find_File_Name_Containing("/", "*.wav");
			  if(result == FR_NO_FILE)
			  {
				  LCD_WriteText("Brak plikow .wav");
				  // Go to sleep in this case
				  while(1)
				  {
					  __WFI();
				  }
			  }
			  else
			  {
				  LCD_WriteText(sd_files_list[0]);
			  }
			  state = STATE_EXECUTE_USER_REQUESTS;
			  break;
		  }

		  case STATE_READ_SAMPLES:
		  {
			  //	If we didn't get to the end of file yet...
			  if(!f_eof(&sd_current_file))
				  //	... Then read next sample chunk
				  f_read(&sd_current_file, empty_data_buf_ptr, 512, &read_data_byte_counter);
			  else
				  // 	...	Else set the end of file flag
				  wav_eof = true;
			  state = STATE_EXECUTE_USER_REQUESTS;
			  break;
		  }

		  case STATE_EXECUTE_USER_REQUESTS:
		  {
			  do
			  {
				  Fifo_Get(&remote_command_fifo, &fifo_command);

				  switch(fifo_command)
				  {
					  case NEC_CH_PLUS:
					  {
						  //	Disable when the wav_file is currently played
						  if(!wav_file_playing)
						  {
							  wav_file_chosen = false;
							  if(file_index < sd_number_of_files_in_dir-1)
								  file_index++;

							  LCD_WriteText(sd_files_list[file_index]);
						  }
						  break;
					  }
					  case NEC_CH_MINUS:
					  {
						  //	Disable when the wav_file is currently played
						  if(!wav_file_playing)
						  {
							  wav_file_chosen = false;
							  if(file_index > 0)
								  file_index--;
							  LCD_WriteText(sd_files_list[file_index]);
						  }
						  break;
					  }
					  case NEC_CH:
					  {
						  //	Disable when the wav_file is currently played
						  if(!wav_file_chosen)
						  {

							  //	If the file is already opened then close it
							  if(sd_current_file.fs != 0)
								  f_close(&sd_current_file);
							  //	...Open the chosen file
							  f_open(&sd_current_file, sd_files_list[file_index], FA_READ);
							  //	Get the chosen files header
							  WAV_Get_File_Header(&sd_current_file);
							  //	Prepare the triggering timer frequency
							 // WAV_Set_Trigger_Frequency(TIM7);
							  TIM_Set_Timer_Max_Count(TIM7, (uint16_t)(TIM7_FREQ/current_wave_header.byte_field.sample_rate));
							  //	Get the rest audio file info
							  //f_read(&sd_current_file, sd_data_buffer, current_wave_header.byte_field.subchunk_2_size, &read_data_byte_counter);
							  //	Get the first portion of data

							  //	Set the wav_file_chosen flag
							  wav_file_chosen = true;
							  //	Clear the wav_eof flag
							  wav_eof  = false;

						  }
						  break;
					  }
					  case NEC_PLAY_PAUSE:
					  {
						 if(!wav_file_playing && wav_file_chosen)
						 {
							//	Clear the timer's counter
							TIM_Clear(TIM7);
							TIM7->DIER |= TIM_DIER_UIE;
							empty_data_buf_ptr = sd_data_buffer;
							  f_read(&sd_current_file, sd_data_buffer, sizeof(sd_data_buffer), &read_data_byte_counter);

							  f_read(&sd_current_file, sd_data_buffer_additional, sizeof(sd_data_buffer_additional), &read_data_byte_counter);
							//	Start the DAC triggering timer
							TIM_Start(TIM7);
							//	Set the wav_file_playing_flag
							wav_file_playing = true;
						 }
						 else
						 {
							 //	Stop the DAC triggering timer
							 TIM_Stop(TIM7);

							 //	Clear the wav_file_playing_ flag
							 wav_file_playing = false;
						 }
						 break;
					  }

					  default:
						  break;
				  }
				  fifo_command = 0;
			  }while(!Fifo_Empty(&remote_command_fifo));
			  break;
		  }
	  }
  }
}
Beispiel #27
0
/**************************************************************************//**
 * @brief  Main function
 *****************************************************************************/
int main(void)
{
  bool     redraw, firstRun;
  FRESULT  res;
  int      mountStatus;
  /* Used when iterating through directory */
  FILINFO Finfo;
  DIR     dir;
  FRESULT listDirStatus = FR_OK;
  /* Used for manifest operation */
  bool useManifest = false;
  char buffer[20];

  /* Use 32MHZ HFXO as core clock frequency */
  CMU_ClockSelectSet(cmuClock_HF, cmuSelect_HFXO);

  /* Initialize DK board register access */
  BSP_Init(BSP_INIT_DEFAULT);

  /* If first word of user data page is non-zero, enable eA Profiler trace */
  BSP_TraceProfilerSetup();

  /* Setup SysTick Timer for 10 msec interrupts  */
  if (SysTick_Config(CMU_ClockFreqGet(cmuClock_CORE) / 100))
  {
    while (1) ;
  }

  /* Enable SPI access to MicroSD card */
  BSP_PeripheralAccess(BSP_MICROSD, true);

  /* Initialize filesystem */
  mountStatus = initFatFS();

  /* Open Manifest file. If a manifest file is not present, iterate through the
   * File system in filesystem order. */
  if (f_open(&manifest, "files.txt", FA_READ) == FR_OK)
    useManifest = true;

  firstRun = true;
  /* Update TFT display forever */
  while (1)
  {
    if (!useManifest)
    {
      /* Open root directory */
      strcpy(path, "");
      listDirStatus = f_opendir(&dir, path);
    }
    /* Iterate through files */
    while (1)
    {
      /* Check if we should control TFT display instead of
       * AEM/board control application. Read state of AEM pushbutton */
      redraw = TFT_AddressMappedInit();
      if (redraw)
      {
        if ( firstRun )
        {
          firstRun = false;
          SLIDES_init();
        }

        /* Check disk status */
        if (disk_status(0) != 0)
        {
          /* Filesystem not mounted, show fatal error. */
          SLIDES_showError(true, "Fatal:\n  Filesystem is not ready.\n  (%d)", disk_status(0));
        }

        /* Check if filesystem was successfully mounted. */
        if (mountStatus != 0)
        {
          /* Filesystem not mounted, show fatal error. */
          SLIDES_showError(true, "Fatal:\n  Filesystem could not be mounted.\n  (%d)", mountStatus);
        }

        /* Is there a manifest file present? */
        if (useManifest)
        {
          /* If we are at the end of the file, reset filepointer */
          if (f_eof(&manifest))
            f_lseek(&manifest, 0);
          /* Read next file from manifest file */
          f_gets(buffer, 20, &manifest);
          /* Display Bitmap */
          SLIDES_showBMP(buffer);
        }
        else
        {
          /* Check to see if the root directory was correctly opened. */
          if (listDirStatus != FR_OK)
          {
            SLIDES_showError(true, "Fatal:\n  Could not read root directory.\n  (%d)", listDirStatus);
          }

          /* Open the next entry in directory */
          res = f_readdir(&dir, &Finfo);
          if ((res != FR_OK) || !Finfo.fname[0])
          {
            /* End of directory listing. Break out of inner loop and reopen
             * directory entry */
            break;
          }
          /* Update display */
          SLIDES_showBMP(Finfo.fname);
        }

        /* Delay to allow the user to see the BMP file. */
        Delay(200);
      }
    }
  }
}
Beispiel #28
0
static FRESULT Config_ReadSingle(
	const char *dir,
	const char *filename)
{
	size_t  len;
	char    *name;
	char    *result;
	int32_t val;

	FRESULT res;

	res = f_chdir(dir);
	if (res != FR_OK) return res;
	
	res = f_open(&Main_file, filename, FA_READ);
	if (res != FR_OK) return res;

	while (!f_eof(&Main_file))
	{
		f_gets(Config_buf, sizeof(Config_buf), &Main_file);

		len = strcspn(Config_buf, ";");
		Config_buf[len] = 0;
		
		name = strtok(Config_buf, " \r\n\t:");
		if (name == 0) continue ;
		
		result = strtok(0, " \r\n\t:");
		if (result == 0) continue ;
		
		val = atol(result);
		
		#define HANDLE_VALUE(s,w,r,t) \
			if ((t) && !strcmp_P(name, (s))) { (w) = (r); }

		HANDLE_VALUE(Config_Model,     UBX_model,        val, val >= 0 && val <= 8);
		HANDLE_VALUE(Config_Rate,      UBX_rate,         val, val >= 100);
		HANDLE_VALUE(Config_Mode,      UBX_mode,         val, val >= 0 && val <= 4);
		HANDLE_VALUE(Config_Min,       UBX_min,          val, TRUE);
		HANDLE_VALUE(Config_Max,       UBX_max,          val, TRUE);
		HANDLE_VALUE(Config_Limits,    UBX_limits,       val, val >= 0 && val <= 2);
		HANDLE_VALUE(Config_Volume,    Tone_volume,      8 - val, val >= 0 && val <= 8);
		HANDLE_VALUE(Config_Mode_2,    UBX_mode_2,       val, (val >= 0 && val <= 4) || (val >= 8 && val <= 9));
		HANDLE_VALUE(Config_Min_Val_2, UBX_min_2,        val, TRUE);
		HANDLE_VALUE(Config_Max_Val_2, UBX_max_2,        val, TRUE);
		HANDLE_VALUE(Config_Min_Rate,  UBX_min_rate,     val * TONE_RATE_ONE_HZ / 100, val >= 0);
		HANDLE_VALUE(Config_Max_Rate,  UBX_max_rate,     val * TONE_RATE_ONE_HZ / 100, val >= 0);
		HANDLE_VALUE(Config_Flatline,  UBX_flatline,     val, val == 0 || val == 1);
		HANDLE_VALUE(Config_Sp_Mode,   UBX_sp_mode,      val, val >= 0 && val <= 6);
		HANDLE_VALUE(Config_Sp_Units,  UBX_sp_units,     val, val >= 0 && val <= 1);
		HANDLE_VALUE(Config_Sp_Rate,   UBX_sp_rate,      val * 1000, val >= 0 && val <= 32);
		HANDLE_VALUE(Config_Sp_Dec,    UBX_sp_decimals,  val, val >= 0 && val <= 2);
		HANDLE_VALUE(Config_Sp_Volume, Tone_sp_volume,   8 - val, val >= 0 && val <= 8);
		HANDLE_VALUE(Config_V_Thresh,  UBX_threshold,    val, TRUE);
		HANDLE_VALUE(Config_H_Thresh,  UBX_hThreshold,   val, TRUE);
		HANDLE_VALUE(Config_Use_SAS,   UBX_use_sas,      val, val == 0 || val == 1);
		HANDLE_VALUE(Config_Window,    UBX_alarm_window, val * 1000, TRUE);
		HANDLE_VALUE(Config_DZ_Elev,   UBX_dz_elev,      val * 1000, TRUE);
		HANDLE_VALUE(Config_TZ_Offset, Log_tz_offset,    val, TRUE);
		HANDLE_VALUE(Config_Init_Mode, UBX_init_mode,    val, val >= 0 && val <= 2);
		
		#undef HANDLE_VALUE
		
		if (!strcmp_P(name, Config_Init_File))
		{
			result[8] = '\0';
			strcpy(UBX_init_filename, result);
		}
		
		if (!strcmp_P(name, Config_Alarm_Elev) && UBX_num_alarms < UBX_MAX_ALARMS)
		{
			++UBX_num_alarms;
			UBX_alarms[UBX_num_alarms - 1].elev = val * 1000 + UBX_dz_elev;
			UBX_alarms[UBX_num_alarms - 1].type = 0;
			UBX_alarms[UBX_num_alarms - 1].filename[0] = '\0';
		}
		if (!strcmp_P(name, Config_Alarm_Type) && UBX_num_alarms <= UBX_MAX_ALARMS)
		{
			UBX_alarms[UBX_num_alarms - 1].type = val;
		}
		if (!strcmp_P(name, Config_Alarm_File) && UBX_num_alarms <= UBX_MAX_ALARMS)
		{
			result[8] = '\0';
			strcpy(UBX_alarms[UBX_num_alarms - 1].filename, result);
		}
		
		if (!strcmp_P(name, Config_Win_Top) && UBX_num_windows < UBX_MAX_WINDOWS)
		{
			++UBX_num_windows;
			UBX_windows[UBX_num_windows - 1].top = val * 1000 + UBX_dz_elev;
		}
		if (!strcmp_P(name, Config_Win_Bottom) && UBX_num_windows <= UBX_MAX_WINDOWS)
		{
			UBX_windows[UBX_num_windows - 1].bottom = val * 1000 + UBX_dz_elev;
		}
	}
	
	f_close(&Main_file);
	
	return FR_OK;
}
/**
 *	Provides End Of File for opened stream file
 *
 *	\param FIL* fobj - file object to be used (NOTE: remember to use '&' operator)
 *	\return TRUE - EOF reached
 *  \return FALSE - EOF not reached
 */
BOOL SDStreamEOF(FIL* fobj)
{
	return f_eof(fobj);
}
Beispiel #30
0
bool SDFile::eof(void) {
  // both cache and file is at the end.
  return f_eof(&file);
}