Esempio n. 1
0
/*------------------------------------------------------------------------------------*/
s08 MCP_read( u08 deviceId, u08 byteAddr, u08 *retValue )
{
size_t xReturn = 0U;
u16 val = 0;
u08 xBytes = 0;

	// Lo primero es obtener el semaforo
	FreeRTOS_ioctl(&pdI2C,ioctlOBTAIN_BUS_SEMPH, NULL);
	// Luego indicamos el periferico i2c en el cual queremos leer
	val = deviceId;
	FreeRTOS_ioctl(&pdI2C,ioctl_I2C_SET_DEVADDRESS, &val);
	// Luego indicamos en que posicion del periferico queremos leer: largo
	val = 1;
	FreeRTOS_ioctl(&pdI2C,ioctl_I2C_SET_BYTEADDRESSLENGTH, &val);
	// y direccion
	val = byteAddr;
	FreeRTOS_ioctl(&pdI2C,ioctl_I2C_SET_BYTEADDRESS,&val);
	// Por ultimo leemos 1 byte.
	xBytes = 1;
	xReturn = FreeRTOS_read(&pdI2C, retValue, xBytes);
	// Y libero el semaforo.
	FreeRTOS_ioctl(&pdI2C,ioctlRELEASE_BUS_SEMPH, NULL);

	if (xReturn != xBytes ) {
		return ( FALSE );
	}

	return(TRUE);

}
Esempio n. 2
0
//------------------------------------------------------------------------------------
void tkGprsRx(void * pvParameters)
{
// Esta tarea lee y procesa las respuestas del GPRS.

u08 c;
size_t pos;

( void ) pvParameters;

	while ( !startTask )
		vTaskDelay( ( TickType_t)( 100 / portTICK_RATE_MS ) );

	snprintf_P( gprsRX_printfBuff,sizeof(gprsRX_printfBuff),PSTR("starting tkGprsRx..\r\n\0"));
	FreeRTOS_write( &pdUART1, gprsRX_printfBuff, sizeof(gprsRX_printfBuff) );

	g_setSocketStatus(SOCKET_CLOSED);
	g_setModemResponse(MRSP_NONE);
	g_flushRXBuffer();

	// loop
	for( ;; )
	{
		u_clearWdg(WDG_GPRSRX);

		// el read se bloquea 50ms. lo que genera la espera.
		while ( FreeRTOS_read( &pdUART0, &c, 1 ) == 1 ) {
			gprsRx.buffer[gprsRx.ptr] = c;
			// Avanzo en modo circular
			gprsRx.ptr = ( gprsRx.ptr  + 1 ) % ( UART0_RXBUFFER_LEN );

			// Los comandos vienen terminados en CR
			if (c == '\r') {

				if ( g_strstr("OK\r", &pos ) == TRUE ) {
				//	FreeRTOS_write( &pdUART1, "DEBUG ** MRSP_OK\r\n\0", sizeof("DEBUG ** MRSP_OK\r\n\0") );
				// No podemos asumir que el socket este cerrado ya que en las respuestas HTTP puede venir
				// un OK\r.
				}

				if ( g_strstr("ERROR\r", &pos ) == TRUE ) {
					//FreeRTOS_write( &pdUART1, "DEBUG ** MRSP_ERROR\r\n\0", sizeof("DEBUG ** MRSP_ERROR\r\n\0") );
				}

				if ( g_strstr("CONNECT", &pos ) == TRUE ) {
					g_setSocketStatus(SOCKET_OPEN);
				//	FreeRTOS_write( &pdUART1, "DEBUG ** MRSP_CONNECT\r\n\0", sizeof("DEBUG ** MRSP_CONNECT\r\n\0") );
				}

				if ( g_strstr("NO CARRIER", &pos ) == TRUE ) {
					g_setSocketStatus(SOCKET_CLOSED);
				//	FreeRTOS_write( &pdUART1, "DEBUG ** MRSP_NO CARRIER\r\n\0", sizeof("DEBUG ** MRSP_NO CARRIER\r\n\0") );
				}
			}
		}
	}
}
Esempio n. 3
0
/*------------------------------------------------------------------------------------*/
void tkCmd(void * pvParameters)
{

u08 c;
u08 ticks;
( void ) pvParameters;

	while ( !startTask )
		vTaskDelay( ( TickType_t)( 100 / portTICK_RATE_MS ) );

	cmdlineInit();
	cmdlineSetOutputFunc(pvFreeRTOS_UART1_writeChar);

	cmdlineAddCommand((u08 *)("cls"), cmdClearScreen );
	cmdlineAddCommand((u08 *)("help"), cmdHelpFunction);
	cmdlineAddCommand((u08 *)("reset"), cmdResetFunction);
	cmdlineAddCommand((u08 *)("read"), cmdReadFunction);
	cmdlineAddCommand((u08 *)("write"), cmdWriteFunction);
	cmdlineAddCommand((u08 *)("redial"), cmdRedialFunction);
	cmdlineAddCommand((u08 *)("status"), cmdStatusFunction);


	// Espero la notificacion para arrancar
	vTaskDelay( ( TickType_t)( 500 / portTICK_RATE_MS ) );

	snprintf_P( cmd_printfBuff,sizeof(cmd_printfBuff),PSTR("starting tkCmd..\r\n\0"));
	FreeRTOS_write( &pdUART1, cmd_printfBuff, sizeof(cmd_printfBuff) );

	ticks = 1;
	FreeRTOS_ioctl( &pdUART1,ioctlSET_TIMEOUT, &ticks );

	// loop
	for( ;; )
	{
		u_clearWdg(WDG_CMD);

		c = '\0';	// Lo borro para que luego del un CR no resetee siempre el timer.
		// el read se bloquea 50ms. lo que genera la espera.
		while ( FreeRTOS_read( &pdUART1, &c, 1 ) == 1 ) {
			cmdlineInputFunc(c);
		}

		/* run the cmdline execution functions */
		cmdlineMainLoop();
	}
}
Esempio n. 4
0
void prvUARTReceiver( void * prvParameters ) {
	int8_t cRxedChar, cInputIndex = 0;
	static int8_t cInputString[ pwmctrlMAX_INPUT_SIZE ];
	portBASE_TYPE xReturned;

	( void ) prvParameters;

	/* Open the UART port used for console input.  The second parameter
	(ulFlags) is not used in this case.  The default board rate is set by the
	boardDEFAULT_UART_BAUD parameter.  The baud rate can be changed using a
	FreeRTOS_ioctl() call with the ioctlSET_SPEED command. */
	xUART3 = FreeRTOS_open( boardUART3, ( uint32_t ) pwmctrlPARAMETER_NOT_USED );
	configASSERT( xUART3 );

	/* Change the Tx usage model from straight polled mode to use zero copy
	buffers with interrupts.  In this mode, the UART will transmit characters
	directly from the buffer passed to the FreeRTOS_write()	function. */
	xReturned = FreeRTOS_ioctl( xUART3, ioctlUSE_ZERO_COPY_TX, pwmctrlPARAMETER_NOT_USED );
	configASSERT( xReturned );

	/* Change the Rx usage model from straight polled mode to use a character
	queue.  Character queue reception is appropriate in this case as characters
	can only be received as quickly as they can be typed, and need to be parsed
	character by character. */
	xReturned = FreeRTOS_ioctl( xUART3, ioctlUSE_CHARACTER_QUEUE_RX, ( void * ) pwmctrlMAX_INPUT_SIZE );
	configASSERT( xReturned );

	/* By default, the UART interrupt priority will have been set to the lowest
	possible.  It must be kept at or below configMAX_LIBRARY_INTERRUPT_PRIORITY,
	but	can be raised above its default priority using a FreeRTOS_ioctl() call
	with the ioctlSET_INTERRUPT_PRIORITY command. */
	xReturned = FreeRTOS_ioctl( xUART3, ioctlSET_INTERRUPT_PRIORITY, ( void * ) ( configMIN_LIBRARY_INTERRUPT_PRIORITY - 1 ) );
	configASSERT( xReturned );

	for(;;) {
		/* Only interested in reading one character at a time (for now). */
		FreeRTOS_read( xUART3, &cRxedChar, sizeof( cRxedChar ) );

		/* For debugging purposes, echo back each character received to the terminal */
#if pwmctrlDEBUG
		if( FreeRTOS_ioctl( xUART3, ioctlOBTAIN_WRITE_MUTEX, pwmctrl50ms ) == pdPASS ) {
			FreeRTOS_write( xUART3, &cRxedChar, sizeof( cRxedChar ) );
		}
#endif
		/* If we receive the STOP character, stop taking input and begin parsing the command. */
		if ( cRxedChar == pwmctrlSTOP ) {

		/* Again, for debugging we're just adding a carriage return to make the output look nice. */
#if pwmctrlDEBUG
			if( FreeRTOS_ioctl( xUART3, ioctlOBTAIN_WRITE_MUTEX, pwmctrl50ms ) == pdPASS ) {
				FreeRTOS_write( xUART3, "\r", 1 );
			}
#endif
			/* Run the method to parse the input received over UART, then reset cInputString to be ready for the next command  */
			prvParseCommand( cInputString );
			cInputIndex = 0;
			memset( cInputString, 0x00, pwmctrlMAX_INPUT_SIZE );

		/* Otherwise, increment the cInputIndex and continue receiving bytes */
		} else {
			if( cInputIndex < pwmctrlMAX_INPUT_SIZE ) {
				cInputString[ cInputIndex ] = cRxedChar;
				cInputIndex++;
			}
		}
	}
}
Esempio n. 5
0
/*------------------------------------------------------------------------------------*/
s08 pvMCP_testAndSet( u08 deviceId, u08 byteAddr, u08 value, u08 bitMask )
{
size_t xReturn = 0U;
u16 val = 0;
u08 xBytes = 0;
u08 regValue;
s08 retS = FALSE;

//	snprintf_P( debug_printfBuff,sizeof(debug_printfBuff),PSTR("MCPT&S [dev=%d][addr=%d][val=%d][msk=%d].\r\n\0"),deviceId, byteAddr, value,bitMask );
//	FreeRTOS_write( &pdUART1, debug_printfBuff, sizeof(debug_printfBuff) );

	// CONTROLO QUE SI EL MCP ES 23018 ESTE BIEN CONFIGURADO ANTES
	if ( deviceId == MCP1_ADDR ) {
		pvMCP_checkConfiguration();
	}

	// Lo primero es obtener el semaforo
	FreeRTOS_ioctl(&pdI2C,ioctlOBTAIN_BUS_SEMPH, NULL);
	// Luego indicamos el periferico i2c en el cual queremos leer
	val = deviceId;
	FreeRTOS_ioctl(&pdI2C,ioctl_I2C_SET_DEVADDRESS, &val);
	// Luego indicamos cuantos bytes queremos leer del dispositivo: largo.
	// En los MCP se lee y escribe de a 1 registro.
	val = 1;
	FreeRTOS_ioctl(&pdI2C,ioctl_I2C_SET_BYTEADDRESSLENGTH, &val);
	// Ahora indicamos desde que posicion queremos leer: direccion
	val = byteAddr;
	FreeRTOS_ioctl(&pdI2C,ioctl_I2C_SET_BYTEADDRESS,&val);
	// Por ultimo leemos.
	xBytes = 1;
	xReturn = FreeRTOS_read(&pdI2C, &regValue, xBytes);

	if (xReturn != xBytes ) {
		goto quit;
	}

//	snprintf_P( debug_printfBuff,sizeof(debug_printfBuff),PSTR("MCPT&S [rdVal=%d]\r\n\0"),regValue );
//	FreeRTOS_write( &pdUART1, debug_printfBuff, sizeof(debug_printfBuff) );

	// Modifico el registro
	if  (value == 0) {
		regValue &= ~BV(bitMask);
	} else {
		regValue |= BV(bitMask);
	}

	// Escribo en el MCP
	xBytes = 1;
	xReturn = FreeRTOS_write(&pdI2C, &regValue, xBytes);
	if (xReturn != xBytes ) {
		goto quit;
	}

//	snprintf_P( debug_printfBuff,sizeof(debug_printfBuff),PSTR("MCPT&S [wrVal=%d]\r\n\0"),regValue );
//	FreeRTOS_write( &pdUART1, debug_printfBuff, sizeof(debug_printfBuff) );

	retS = TRUE;

quit:
	// Y libero el semaforo.
	FreeRTOS_ioctl(&pdI2C,ioctlRELEASE_BUS_SEMPH, NULL);
	return(retS);
}
Esempio n. 6
0
void vCommandConsoleTask( void *pvParameters )
{
(void)pvParameters;
unsigned portCHAR cRxedChar, cInputIndex = 0;
portBASE_TYPE xMoreDataToFollow;
/* The input and output buffers are declared static to keep them off the stack. */
portCHAR *pcOutputString;
static unsigned portCHAR pcInputString[ MAX_INPUT_LENGTH ];

    /* This code assumes the peripheral being used as the console has already 
    been opened and configured, and is passed into the task as the task
    parameter.  Cast the task parameter to the correct type. */
	pcOutputString = (portCHAR *) FreeRTOS_CLIGetOutputBuffer();

	strcpy_P(pcOutputString, pm_cstr_WelcomeMessage);
	
    /* Send a welcome message to the user knows they are connected. */
    FreeRTOS_write( pcOutputString, strlen(pcOutputString) );

    for( ;; )
    {
        /* This implementation reads a single character at a time.  Wait in the
        Blocked state until a character is received. */
        FreeRTOS_read( &cRxedChar, sizeof( cRxedChar ) );

        if( cRxedChar == '\n' )
        {
            /* A newline character was received, so the input command stirng is
            complete and can be processed.  Transmit a line separator, just to 
            make the output easier to read. */
            FreeRTOS_write( "\r\n", strlen( "\r\n" ));

            /* The command interpreter is called repeatedly until it returns 
            pdFALSE.  See the "Implementing a command" documentation for an 
            exaplanation of why this is. */
            do
            {
                /* Send the command string to the command interpreter.  Any
                output generated by the command interpreter will be placed in the 
                pcOutputString buffer. */
				FreeRTOS_CLITakeOutputBuffer();
                xMoreDataToFollow = FreeRTOS_CLIProcessCommand
                              (     
                                  (const int8_t * const)pcInputString,   /* The command string.*/
                                  (int8_t *)pcOutputString,  /* The output buffer. */
                                  configCOMMAND_INT_MAX_OUTPUT_SIZE/* The size of the output buffer. */
                              );

                /* Write the output generated by the command interpreter to the 
                console. */
                FreeRTOS_write( pcOutputString, strlen(pcOutputString ) );
				FreeRTOS_CLIGiveOutputBuffer();
            } while( xMoreDataToFollow != pdFALSE );

            /* All the strings generated by the input command have been sent.
            Processing of the command is complete.  Clear the input string ready 
            to receive the next command. */
            cInputIndex = 0;
            memset( pcInputString, 0x00, MAX_INPUT_LENGTH );
        }
        else
        {
            /* The if() clause performs the processing after a newline character
            is received.  This else clause performs the processing if any other
            character is received. */
		
            if( cRxedChar == '\r' )
            {
                /* Ignore carriage returns. */
            }
            else if( cRxedChar == '\b' )
            {
                /* Backspace was pressed.  Erase the last character in the input
                buffer - if there are any. */
                if( cInputIndex > 0 )
                {
                    cInputIndex--;
                    pcInputString[ cInputIndex ] = '\0';
                }
            }
            else
            {
                /* A character was entered.  It was not a new line, backspace
                or carriage return, so it is accepted as part of the input and
                placed into the input buffer.  When a \n is entered the complete
                string will be passed to the command interpreter. */
                if( cInputIndex < MAX_INPUT_LENGTH )
                {
                    pcInputString[ cInputIndex ] = cRxedChar;
                    cInputIndex++;
                }
            }
        }
    }
}        
Esempio n. 7
0
void vI2C_EEPROMTest( Peripheral_Descriptor_t xI2CPort )
{
uint32_t ulStartAddress = 0UL, ulPage;
const uint32_t ulMaxDelay = 500UL / portTICK_RATE_MS;
static uint8_t ucByte, ucValue;
int32_t lReturned;

	/* The I2C port is opened and configured in the I2C-coordinator.c file.
	The opened handle is passed in to this file - which just uses the I2C
	FreeRTOS+IO driver with whatever configuration it happens to have at that
	time.  Sometimes it	will be operating in polled mode, and other in
	interrupt driven zero copy Tx with interrupt driven circular buffer Rx. */

	/* Set the clock frequency to be correct for the EEPROM. */
	FreeRTOS_ioctl( xI2CPort, ioctlSET_SPEED, i2cEEPROM_CLOCK );

	/* The write mutex is obtained in the code below, but it is possible that
	it is already held by this task - in which case the attempt to obtain it
	will fail.  Release the mutex first, just in case. */
	FreeRTOS_ioctl( xI2CPort, ioctlRELEASE_WRITE_MUTEX, i2cPARAMETER_NOT_USED );

	/* Wait until any writes already in progress have completed. */
	FreeRTOS_ioctl( xI2CPort, ioctlOBTAIN_WRITE_MUTEX, ( void * ) ulMaxDelay );

	/* Fill the EEPROM with 0x00, one page at a time. */
	memset( ucDataBuffer, 0x00, sizeof( ucDataBuffer ) );
	for( ulPage = 0UL; ulPage < ( i2cTOTAL_EEPROM_SIZE / i2cPAGE_SIZE ); ulPage++ )
	{
		prvWritePageToEEPROM( xI2CPort, ulStartAddress );

		/* Move to the next page. */
		ulStartAddress += i2cPAGE_SIZE;
	}

	/* Check all data read from the EEPROM reads as 0x00.  Start by setting the
	read address back to the start of the EEPROM. */
	ucDataBuffer[ 0 ] = 0x00;
	lReturned = FreeRTOS_write( xI2CPort, ucDataBuffer, sizeof( ucDataBuffer[ 0 ] ) );
	configASSERT( lReturned == sizeof( ucDataBuffer[ 0 ] ) );

	/* Wait until the write completes. */
	FreeRTOS_ioctl( xI2CPort, ioctlOBTAIN_WRITE_MUTEX, ( void * ) ulMaxDelay );

	for( ulPage = 0UL; ulPage < ( i2cTOTAL_EEPROM_SIZE / i2cPAGE_SIZE ); ulPage++ )
	{
		/* Ensure the data buffer does not contain 0x00 already. */
		memset( ucDataBuffer, 0xff, sizeof( ucDataBuffer ) );

		/* Read a page back from the EEPROM. */
		lReturned = FreeRTOS_read( xI2CPort, ucDataBuffer, i2cPAGE_SIZE );
		configASSERT( lReturned == i2cPAGE_SIZE );

		/* Check each byte in the page just read contains 0. */
		for( ucByte = 0U; ucByte < i2cPAGE_SIZE; ucByte++ )
		{
			configASSERT( ucDataBuffer[ ucByte ] == 0U );
		}
	}

	/* Do the same, but this time write a different value into each location
	(the value will overflow). */
	ucValue = 0x00U;
	ulStartAddress = 0UL;
	for( ulPage = 0UL; ulPage < ( i2cTOTAL_EEPROM_SIZE / i2cPAGE_SIZE ); ulPage++ )
	{
		for( ucByte = 0U; ucByte < i2cPAGE_SIZE; ucByte++ )
		{
			/* ucDataBuffer[ 0 ] holds the byte address so is skipped. */
			ucDataBuffer[ ucByte + 1 ] = ucValue;
			ucValue++;
		}

		prvWritePageToEEPROM( xI2CPort, ulStartAddress );

		/* Move to the next page. */
		ulStartAddress += i2cPAGE_SIZE;
	}

	/* Check all data read from the EEPROM reads as written.  Start by setting
	the	read address back to the start of the EEPROM. */
	ucDataBuffer[ 0 ] = 0x00;
	lReturned = FreeRTOS_write( xI2CPort, ucDataBuffer, sizeof( ucDataBuffer[ 0 ] ) );
	configASSERT( lReturned == sizeof( ucDataBuffer[ 0 ] ) );

	/* Wait until the write completes. */
	FreeRTOS_ioctl( xI2CPort, ioctlOBTAIN_WRITE_MUTEX, ( void * ) ulMaxDelay );

	ucValue = 0U;
	for( ulPage = 0UL; ulPage < ( i2cTOTAL_EEPROM_SIZE / i2cPAGE_SIZE ); ulPage++ )
	{
		/* Ensure the data buffer starts clear. */
		memset( ucDataBuffer, 0xff, sizeof( ucDataBuffer ) );

		/* Read a page back from the EEPROM. */
		lReturned = FreeRTOS_read( xI2CPort, ucDataBuffer, i2cPAGE_SIZE );
		configASSERT( lReturned == i2cPAGE_SIZE );

		/* Check each byte in the page contains the expected value. */
		for( ucByte = 0U; ucByte < i2cPAGE_SIZE; ucByte++ )
		{
			configASSERT( ucDataBuffer[ ucByte ] == ucValue );
			ucValue++;
		}
	}
}
//
//
//
//lecture - many features are from FREERTOS+CLI subsystem - explore related headers and
//          source files as needed ???
//
//lecture - several calls are to FREERTOS+IO subsystems - explore related headers and
//          source files as needed ???
//
//
//
//
//
static void prvUARTCommandConsoleTask( void *pvParameters )
{
int8_t cRxedChar, cInputIndex = 0, *pcOutputString;
static int8_t cInputString[ cmdMAX_INPUT_SIZE ], cLastInputString[ cmdMAX_INPUT_SIZE ];
portBASE_TYPE xReturned;

	( void ) pvParameters;

	/* Obtain the address of the output buffer.  Note there is no mutual
	exclusion on this buffer as it is assumed only one command console
	interface will be used at any one time. */
	pcOutputString = FreeRTOS_CLIGetOutputBuffer();

	/* Open the UART port used for console input.  The second parameter
	(ulFlags) is not used in this case.  The default board rate is set by the
	boardDEFAULT_UART_BAUD parameter.  The baud rate can be changed using a
	FreeRTOS_ioctl() call with the ioctlSET_SPEED command. */
	//lecture - UART - refer to FreeRTOS_DriverInterface.c for FreeRTOS_open() api
	//        - UART - refer to LPCXpresso17xx-base-board.h for
	//                 boardCOMMAND_CONSOLE_UART - it is UART3 of the four UARTs
	//
	//
	//lecture - UART - we will receive NULL, if there is a failure
	//
	//
	xConsoleUART = FreeRTOS_open( boardCOMMAND_CONSOLE_UART, ( uint32_t ) cmdPARAMTER_NOT_USED );
	configASSERT( xConsoleUART );

	//
	//lecture - UART - refer to FreeRTOS_DriverInterface.c for FreeRTOS_ioctl() api
	//
	//
#if 1
	/* Change the Tx usage model from straight polled mode to use zero copy
	buffers with interrupts.  In this mode, the UART will transmit characters
	directly from the buffer passed to the FreeRTOS_write()	function. */
//	xReturned = FreeRTOS_ioctl( xConsoleUART, ioctlUSE_ZERO_COPY_TX, cmdPARAMTER_NOT_USED );
	//configASSERT( xReturned );

	xReturned = FreeRTOS_ioctl( xConsoleUART, ioctlUSE_TASKNOTIFICATION_TX, uartstCIRCULAR_BUFFER_SIZE );
	configASSERT( xReturned );


#endif


#if 1

	//xReturned = FreeRTOS_ioctl( xConsoleUART, ioctlUSE_CIRCULAR_BUFFER_RX, uartstCIRCULAR_BUFFER_SIZE );
	//configASSERT( xReturned );
	xReturned = FreeRTOS_ioctl( xConsoleUART, ioctlUSE_TASKNOTIFICATION_RX, uartstCIRCULAR_BUFFER_SIZE );
	configASSERT( xReturned );
#endif

    //
	//
	//
	//lecture -UART - refer to FreeRTOS_DriverInterface.c for FreeRTOS_ioctl() api
	//
    //
	/* Change the Rx usage model from straight polled mode to use a character
	queue.  Character queue reception is appropriate in this case as characters
	can only be received as quickly as they can be typed, and need to be parsed
	character by character. */
	//xReturned = FreeRTOS_ioctl( xConsoleUART, ioctlUSE_CHARACTER_QUEUE_RX, ( void * ) cmdMAX_INPUT_SIZE );
	//configASSERT( xReturned );

	//
	//lecture - UART - refer to refer to FreeRTOS_DriverInterface.c for FreeRTOS_ioctl() api -
	//                 eventually, invokes the uart specific ioctl method and respective setting
	//
	//lecture - UART - may set different priorities and check ???
	//
	/* By default, the UART interrupt priority will have been set to the lowest
	possible.  It must be kept at or below configMAX_LIBRARY_INTERRUPT_PRIORITY,
	but	can be raised above its default priority using a FreeRTOS_ioctl() call
	with the ioctlSET_INTERRUPT_PRIORITY command. */
	xReturned = FreeRTOS_ioctl( xConsoleUART, ioctlSET_INTERRUPT_PRIORITY, ( void * ) ( configMIN_LIBRARY_INTERRUPT_PRIORITY - 1 ) );
	configASSERT( xReturned );
    //
	//
	//
	//lecture - UART - as per zero copy tx mode, we must first acquire the mutex, before we can
	//                 initiate a write on the device instance - in this case, it is uart
	//
	//lecture - UART - refer to FreeRTOS_DriverInterface.c for code and details of FreeRTOS_ioctl()
	//
	//
#if 1
	//
	/* Send the welcome message. */
//	if( FreeRTOS_ioctl( xConsoleUART, ioctlOBTAIN_WRITE_MUTEX, cmd50ms ) == pdPASS )
	{
		FreeRTOS_write( xConsoleUART, pcWelcomeMessage, strlen( ( char * ) pcWelcomeMessage ) );
	}
#endif

#if 0
	if(FreeRTOS_ioctl( xConsoleUART, ioctlRELEASE_WRITE_MUTEX, cmd50ms ) == pdPASS )
	{
	   printf("mutex released\n");
	}
#endif

	//FreeRTOS_write( xConsoleUART, pcWelcomeMessage, strlen( ( char * ) pcWelcomeMessage ) );
	//for(;;); //aaa-zzz  : for testing

	for( ;; )
	{
		xReturned = FreeRTOS_read( xConsoleUART, &cRxedChar, sizeof( cRxedChar ) );
		configASSERT( xReturned );

		//printf("LSR=%d",)
		/* Echo the character back. */
		if( FreeRTOS_ioctl( xConsoleUART, ioctlOBTAIN_WRITE_MUTEX, cmd50ms ) == pdPASS )
		{
			FreeRTOS_write( xConsoleUART, &cRxedChar, sizeof( cRxedChar ) );
		}

		if( cRxedChar == '\n' )
		{
			/* The input command string is complete.  Ensure the previous
			UART transmission has finished before sending any more data.
			This task will be held in the Blocked state while the Tx completes,
			if it has not already done so, so no CPU time will be wasted by
			polling. */
	//		if( FreeRTOS_ioctl( xConsoleUART, ioctlOBTAIN_WRITE_MUTEX, cmd50ms ) == pdPASS )
			{
				/* Start to transmit a line separator, just to make the output
				easier to read. */
				FreeRTOS_write( xConsoleUART, pcNewLine, strlen( ( char * ) pcNewLine ) );
			}

			/* See if the command is empty, indicating that the last command is
			to be executed again. */
			if( cInputIndex == 0 )
			{
				strcpy( ( char * ) cInputString, ( char * ) cLastInputString );
			}

			/* Pass the received command to the command interpreter.  The
			command interpreter is called repeatedly until it returns
			pdFALSE as it might generate more than one string. */
			do
			{
				/* Once again, just check to ensure the UART has completed
				sending whatever it was sending last.  This task will be held
				in the Blocked state while the Tx completes, if it has not
				already done so, so no CPU time	is wasted polling. */
				xReturned = FreeRTOS_ioctl( xConsoleUART, ioctlOBTAIN_WRITE_MUTEX, cmd50ms );
				if( xReturned == pdPASS )
				{
					/* Get the string to write to the UART from the command
					interpreter. */
					xReturned = FreeRTOS_CLIProcessCommand( cInputString, pcOutputString, configCOMMAND_INT_MAX_OUTPUT_SIZE );

					/* Write the generated string to the UART. */
					FreeRTOS_write( xConsoleUART, pcOutputString, strlen( ( char * ) pcOutputString ) );
				}

			} while( xReturned != pdFALSE );

			/* All the strings generated by the input command have been sent.
			Clear the input	string ready to receive the next command.  Remember
			the command that was just processed first in case it is to be
			processed again. */
			strcpy( ( char * ) cLastInputString, ( char * ) cInputString );
			cInputIndex = 0;
			memset( cInputString, 0x00, cmdMAX_INPUT_SIZE );

			/* Ensure the last string to be transmitted has completed. */
			if( FreeRTOS_ioctl( xConsoleUART, ioctlOBTAIN_WRITE_MUTEX, cmd50ms ) == pdPASS )
			{
				/* Start to transmit a line separator, just to make the output
				easier to read. */
				FreeRTOS_write( xConsoleUART, pcEndOfCommandOutputString, strlen( ( char * ) pcEndOfCommandOutputString ) );
			}
		}
		else
		{
			if( cRxedChar == '\r' )
			{
				/* Ignore the character. */
			}
			else if( cRxedChar == '\b' )
			{
				/* Backspace was pressed.  Erase the last character in the
				string - if any. */
				if( cInputIndex > 0 )
				{
					cInputIndex--;
					cInputString[ cInputIndex ] = '\0';
				}
			}
			else
			{
				/* A character was entered.  Add it to the string
				entered so far.  When a \n is entered the complete
				string will be passed to the command interpreter. */
				if( ( cRxedChar >= ' ' ) && ( cRxedChar <= '~' ) )
				{
					if( cInputIndex < cmdMAX_INPUT_SIZE )
					{
						cInputString[ cInputIndex ] = cRxedChar;
						cInputIndex++;
					}
				}
			}
		}
	}
}
static void prvUARTRxOperationModesTestTask( void *pvParameters )
{
portBASE_TYPE xTestLoops, xReturned;
uint8_t *pcRxBuffer;
size_t xRxedChars, xStringLength, xReceivedCharacters;
const size_t xRxBufferSize = strlen( ( char * ) pcTestMessage3 ) + ( size_t ) 1;
portTickType xTimeBefore, xTimeAfter;

	( void ) pvParameters;

	/* Create a buffer that is large enough to receive the longest of the
	strings. */
	pcRxBuffer = pvPortMalloc( xRxBufferSize );
	prvCheckTestResult( ( pcRxBuffer != NULL ), __LINE__ );

	/* At this point the Tx task should not have executed, and therefore the
	UART should not have been opened. */
	prvCheckTestResult( ( xTestUART == NULL ), __LINE__);

	/*************************************************************************
	 * Test 1.  Polling Tx and polling Rx.
	 *************************************************************************/

	/* This task has the higher priority so will run before the Tx task.
	Suspend this task to allow the lower priority Tx task to run.  The Tx task
	will unsuspend (resume) this task when it is ready. */
	vTaskSuspend( NULL );

	/* The Tx task should have opened the UART before unsuspending this
	task. */
	prvCheckTestResult( ( xTestUART != NULL ), __LINE__ );

	/* Clear any characters that may already be in the UART buffers/FIFO. */
	while( FreeRTOS_read( xTestUART, &( pcRxBuffer[ 0 ] ), sizeof( uint8_t ) ) != 0 );

	/* The UART has been opened, but not yet configured.  It will
	use the default configuration, which is to poll rather than use interrupts,
	and to use 115200 baud.  Try reading out a message a few times to check the
	default functionality.  The task must block when no characters are
	available otherwise the lower priority Tx task will be starved of CPU
	time. */
	xStringLength = strlen( ( char * ) pcTestMessage1 );
	for( xTestLoops = 0; xTestLoops < uartstNUM_TEST_TRANSACTIONS; xTestLoops++ )
	{
		/* Clear the Rx buffer, then poll for characters one at a time, placing
		them in the Rx buffer. */
		memset( pcRxBuffer, 0x00, xRxBufferSize );
		xRxedChars = 0;
		while( xRxedChars < xStringLength )
		{
			xReturned = FreeRTOS_read( xTestUART, &( pcRxBuffer[ xRxedChars ] ), sizeof( uint8_t ) );

			/* It should only be possible to have received either 1 of zero
			bytes. */
			prvCheckTestResult( ( ( xReturned == 1 ) || ( xReturned == 0 ) ), __LINE__ );

			if( xReturned == 0 )
			{
				/* No characters were returned, so allow the Tx task to
				execute. */
				vTaskDelay( ( portTickType ) uartstEXTREMELY_SHORT_BLOCK_TIME );
			}
			else
			{
				xRxedChars++;
			}
		}

		/* The whole string should now have been received.  Is it correct? */
		xReturned = strcmp( ( char * ) pcRxBuffer, ( char * ) pcTestMessage1 );
		prvCheckTestResult( ( xReturned == 0 ), __LINE__ );
	}


	for( ;; )
	{
		/* Suspend again to wait for the Tx task to be ready for test 2. */
		vTaskSuspend( NULL );


		/*************************************************************************
		 * Test 2.  Interrupt driven, zero copy Tx, circular buffer Rx.
		 *************************************************************************/

		/* The Tx task will now have configured the UART to use interrupts and
		a circular buffer for receiving.  The default configuration will have
		an infinite block time.  Set this down, but leave the block time long
		enough for the entire string to be received. */
		xReturned = FreeRTOS_ioctl( xTestUART, ioctlSET_RX_TIMEOUT, uartstVERY_LONG_BLOCK_TIME );
		prvCheckTestResult( xReturned, __LINE__ );

		xStringLength = strlen( ( char * ) pcTestMessage2 );
		for( xTestLoops = 0; xTestLoops < uartstNUM_TEST_TRANSACTIONS; xTestLoops++ )
		{
			/* Clear the Rx buffer. */
			memset( pcRxBuffer, 0x00, xRxBufferSize );

			/* Read as many characters as possible in one go, up to the total
			number of expected characters in the string being received. */
			xReturned = FreeRTOS_read( xTestUART, pcRxBuffer, xStringLength );

			prvCheckTestResult( ( xReturned == ( portBASE_TYPE ) xStringLength ), __LINE__ );

			/* The whole string should now have been received.  Is it
			correct? */
			xReturned = strcmp( ( char * ) pcRxBuffer, ( char * ) pcTestMessage2 );
			prvCheckTestResult( ( xReturned == 0 ), __LINE__ );
		}

		/* This time, try receiving the characters one at a time. */
		for( xTestLoops = 0; xTestLoops < uartstNUM_TEST_TRANSACTIONS; xTestLoops++ )
		{
			/* Clear the Rx buffer. */
			memset( pcRxBuffer, 0x00, xRxBufferSize );
			xReceivedCharacters = 0;

			/* Read one character at a time until the total number of expected
			characters in the string have been received. */
			while( xReceivedCharacters < xStringLength )
			{
				xReturned = FreeRTOS_read( xTestUART, &( pcRxBuffer[ xReceivedCharacters ] ), sizeof( uint8_t ) );
				prvCheckTestResult( ( xReturned == ( portBASE_TYPE ) sizeof( uint8_t ) ), __LINE__ );
				xReceivedCharacters += sizeof( uint8_t );

				/* Make sure not to get stuck here. */
				if( xReturned == 0 )
				{
					break;
				}
			}

			/* The whole string should now have been received.  Is it
			correct? */
			xReturned = strcmp( ( char * ) pcRxBuffer, ( char * ) pcTestMessage2 );
			prvCheckTestResult( ( xReturned == 0 ), __LINE__ );
		}

		/* Next, shorten the block time and try receiving more characters.  At
		this time, the Tx task will not be transmitting, so the read commands
		should	return after the configured block time has expired.

		First change the block time itself. */
		xReturned = FreeRTOS_ioctl( xTestUART, ioctlSET_RX_TIMEOUT, uartstVERY_SHORT_TX_BLOCK_TIME );
		prvCheckTestResult( xReturned, __LINE__ );

		/* Attempt a read, taking note of the time both before and after the
		call to read(). */
		memset( pcRxBuffer, 0x00, xRxBufferSize );
		xTimeBefore = xTaskGetTickCount();
		xReturned = FreeRTOS_read( xTestUART, pcRxBuffer, xStringLength );
		prvCheckTestResult( ( ( xTaskGetTickCount() - xTimeBefore ) <= ( ( portTickType ) uartstVERY_SHORT_TX_BLOCK_TIME + uartstTIME_MARGIN ) ), __LINE__ );

		/* Nothing should have been returned. */
		prvCheckTestResult( ( xReturned == 0 ), __LINE__ );

		/* Repeat, using a different block time. */
		xReturned = FreeRTOS_ioctl( xTestUART, ioctlSET_RX_TIMEOUT, ( void * ) ( ( portTickType ) uartstVERY_SHORT_TX_BLOCK_TIME * 2U ) );
		prvCheckTestResult( xReturned, __LINE__ );
		xTimeBefore = xTaskGetTickCount();
		xReturned = FreeRTOS_read( xTestUART, pcRxBuffer, xStringLength );
		prvCheckTestResult( ( ( xTaskGetTickCount() - xTimeBefore ) <= ( ( ( portTickType ) uartstVERY_SHORT_TX_BLOCK_TIME * 2U ) + uartstTIME_MARGIN ) ), __LINE__ );
		prvCheckTestResult( ( xReturned == 0 ), __LINE__ );

		/* Suspend again to wait for the Tx task to be ready for test 3. */
		vTaskSuspend( NULL );




		/*************************************************************************
		 * Test 3.  Character queue Rx/Tx
		 *************************************************************************/

		/* The Tx task will have set both the Rx and Tx models to use a
		character by character queue.  Set the Rx block time back up so it is
		long enough to read the entire string. */
		xReturned = FreeRTOS_ioctl( xTestUART, ioctlSET_RX_TIMEOUT, uartstVERY_LONG_BLOCK_TIME );
		prvCheckTestResult( xReturned, __LINE__ );

		xStringLength = strlen( ( char * ) pcTestMessage3 );
		for( xTestLoops = 0; xTestLoops < uartstNUM_TEST_TRANSACTIONS; xTestLoops++ )
		{
			/* Clear the Rx buffer. */
			memset( pcRxBuffer, 0x00, xRxBufferSize );

			/* Read as many characters as possible in one go, up to the total
			number of expected characters in the string being received. */
			xReturned = FreeRTOS_read( xTestUART, pcRxBuffer, xStringLength );

			prvCheckTestResult( ( xReturned == ( portBASE_TYPE ) xStringLength ), __LINE__ );

			/* The whole string should now have been received.  Is it correct? */
			xReturned = strcmp( ( char * ) pcRxBuffer, ( char * ) pcTestMessage3 );
			prvCheckTestResult( ( xReturned == 0 ), __LINE__ );
		}




		/*************************************************************************
		 * Test 4.  Character queue Rx/Tx block times
		 *************************************************************************/


		/* Reading characters from an Rx queue has a block time.  This is the
		total time spent trying to read characters from the Rx queue if the
		queue is already empty.  If the task finds the queue empty then it is
		held in the	Blocked state until data becomes available, so no CPU time
		is wasted polling.  If the block time expires before all the characters
		have been read from the queue then the FreeRTOS_read() call returns the
		number of characters that were successfully read (as normal). */
		xReturned = FreeRTOS_ioctl( xTestUART, ioctlSET_RX_TIMEOUT, uartstVERY_SHORT_RX_BLOCK_TIME );
		prvCheckTestResult( xReturned, __LINE__ );

		for( xTestLoops = 0; xTestLoops < uartstNUM_TEST_TRANSACTIONS; xTestLoops++ )
		{
			/* Try reading a string again, still using the character by
			character queue, but this time using a very short block time so not
			all the	characters will make it from the queue. */
			xTimeBefore = xTaskGetTickCount();
			xReturned = FreeRTOS_read( xTestUART, pcRxBuffer, xStringLength );
			xTimeAfter = xTaskGetTickCount();

			prvCheckTestResult( ( ( xReturned != 0 ) && ( xReturned != ( portBASE_TYPE ) xStringLength ) ), __LINE__ );
			prvCheckTestResult( ( ( xTimeAfter - xTimeBefore ) < ( ( portTickType ) uartstVERY_SHORT_RX_BLOCK_TIME + ( portTickType ) 2 ) ), __LINE__ );
		}

		/* Clear any characters that remain UART buffers/FIFO before
		continuing. */
		while( FreeRTOS_read( xTestUART, &( pcRxBuffer[ 0 ] ), sizeof( uint8_t ) ) != 0 );
		while( FreeRTOS_read( xTestUART, &( pcRxBuffer[ 0 ] ), sizeof( uint8_t ) ) != 0 );
		while( FreeRTOS_read( xTestUART, &( pcRxBuffer[ 0 ] ), sizeof( uint8_t ) ) != 0 );
	}
}
Esempio n. 10
0
//------------------------------------------------------------------------------------
s08 FF_rewind(void)
{
	// Borra el archivo y lo lleva a su condicion inicial.
	// Inicializa la memoria. Como lleva bastante tiempo, tenemos problemas con el
	// watchdog. Por esto desde donde la invocamos debemos desactivarlo y esta
	// funcion SOLO debe usarse desde CMD.

u16 val = 0;
u16 tryes;
u16 xPos;

	wdt_reset();

	// Lo primero es obtener el semaforo del I2C
	FreeRTOS_ioctl(&pdI2C,ioctlOBTAIN_BUS_SEMPH, NULL);

	// inicializo la estructura lineal temporal del FCB.
	memset( FCB.ff_buffer,0, sizeof(FCB.ff_buffer) );

	// EE WRITE:
	// Luego indicamos el periferico i2c en el cual queremos leer
	val = EE_ADDR;
	FreeRTOS_ioctl(&pdI2C,ioctl_I2C_SET_DEVADDRESS, &val);
	// Luego indicamos la direccion a escribir del dispositivo: largo ( en la ee son 2 bytes )
	val = 2;
	FreeRTOS_ioctl(&pdI2C,ioctl_I2C_SET_BYTEADDRESSLENGTH, &val);
	// Ciclo de borrado
	for ( xPos = 0; xPos < FF_MAX_RCDS; xPos++) {
		// direccion interna en la EE.(comienzo del registro / frontera)
		val = FF_ADDR_START + xPos * FF_RECD_SIZE;
		FreeRTOS_ioctl(&pdI2C,ioctl_I2C_SET_BYTEADDRESS,&val);

		for ( tryes = 0; tryes < 3; tryes++ ) {
			// Borro: escribo un pagina entera, 64 bytes con los '\0'
			FreeRTOS_write(&pdI2C, &FCB.ff_buffer, FF_RECD_SIZE);
			taskYIELD();
			// Leo y verifico
			FreeRTOS_read(&pdI2C, &FCB.check_buffer, FF_RECD_SIZE);
			if ( memcmp (&FCB.check_buffer, &FCB.ff_buffer, FF_RECD_SIZE) == 0 )
				break;
			if  ( tryes == 3 ) {
				snprintf_P( debug_printfBuff,sizeof(debug_printfBuff),PSTR("FFrew ERR: %d,%d\r\n\0"),xPos, val);
				FreeRTOS_write( &pdUART1, debug_printfBuff, sizeof(debug_printfBuff) );
			}

		}
		// Imprimo realimentacion c/32 recs.
		if ( (xPos % 32) == 0 ) {
			FreeRTOS_write( &pdUART1, ".\0", sizeof(".\0") );
		}

		// Para no salir por wdg reset
		if ( (xPos % 64) == 0 ) {
			wdt_reset();
		}
	}

	FreeRTOS_write( &pdUART1, "\r\n\0", sizeof("\r\n\0") );
	FreeRTOS_ioctl(&pdI2C,ioctlRELEASE_BUS_SEMPH, NULL);
	// RESET
	u_reset();

}
Esempio n. 11
0
//------------------------------------------------------------------------------------
size_t FF_fread( void *pvBuffer, size_t xSize)
{
	// Lee un registro apuntado por RD.
	// Retorna la cantidad de bytes leidos.
	// Las condiciones de lectura son:
	// - la memoria debe tener al menos algun dato
	// - el puntero RD debe apuntar dentro del bloque 'leible'
	//
	// Lee un registro ( como string ) y lo copia al espacio de memoria apuntado
	// *pvBuffer. El puntero es void y entonces debemos pasar el tamaño de la estructura
	// a la que apunta.
	// En caso que tenga problemas para leer o de checksum, debo continuar e indicar
	// el error.

u16 val = 0;
size_t xReturn = 0U;
u08 rdCheckSum;

	// Lo primero es obtener el semaforo del I2C
//	a = xTaskGetTickCount();
	FreeRTOS_ioctl(&pdI2C,ioctlOBTAIN_BUS_SEMPH, NULL);
//	b = xTaskGetTickCount();
	FCB.ff_stat.errno = pdFF_ERRNO_NONE;

	// Si la memoria esta vacia salgo ( todos los registros libres )
	if ( FCB.ff_stat.rcdsFree == FF_MAX_RCDS ) {
		FCB.ff_stat.errno = pdFF_ERRNO_MEMEMPTY;
		goto quit;
	}

	// Si el registro no corresponde al bloque 'leible', salgo
	if ( ( FCB.ff_stat.HEAD > FCB.ff_stat.TAIL) && ( ( FCB.ff_stat.RD >= FCB.ff_stat.HEAD ) || ( FCB.ff_stat.RD < FCB.ff_stat.TAIL ) ) ) {
		FCB.ff_stat.errno = pdFF_ERRNO_MEMEMPTY;
		goto quit;
	}
	if ( ( FCB.ff_stat.HEAD < FCB.ff_stat.TAIL) && ( ( FCB.ff_stat.RD >= FCB.ff_stat.HEAD ) && ( FCB.ff_stat.RD < FCB.ff_stat.TAIL ) ) ) {
		FCB.ff_stat.errno = pdFF_ERRNO_MEMEMPTY;
		goto quit;
	}

	// Aqui es que estoy dentro de un bloque 'leible'

	// inicializo la estructura lineal temporal en el FCB.
	memset( FCB.ff_buffer,0, sizeof(FCB.ff_buffer) );
	// EE READ:
	// Indicamos el periferico i2c al cual quiero acceder
	val = EE_ADDR;
	FreeRTOS_ioctl(&pdI2C,ioctl_I2C_SET_DEVADDRESS, &val);
	// Luego indicamos la direccion desde donde leer del dispositivo: largo ( en la ee son 2 bytes )
	val = 2;
	FreeRTOS_ioctl(&pdI2C,ioctl_I2C_SET_BYTEADDRESSLENGTH, &val);
	// y direccion interna en la EE.(comienzo del registro / frontera)
	val = FF_ADDR_START + FCB.ff_stat.RD * FF_RECD_SIZE;
	FreeRTOS_ioctl(&pdI2C,ioctl_I2C_SET_BYTEADDRESS,&val);
	// Por ultimo leo la memoria: un pagina entera, (recd) 64 bytes.
//	c = xTaskGetTickCount();
	xReturn = FreeRTOS_read(&pdI2C, &FCB.ff_buffer, FF_RECD_SIZE);
//	d = xTaskGetTickCount();
	// Avanzo el puntero de RD en modo circular siempre !!
	FCB.ff_stat.RD = (++FCB.ff_stat.RD == FF_MAX_RCDS) ?  0 : FCB.ff_stat.RD;

	// Copio los datos a la estructura de salida.: aun no se si estan correctos
	memcpy( pvBuffer, &FCB.ff_buffer, xSize );

	// Errores de lectura ?
	// Solo indico los errores, pero igual devuelvo el recd. para no trancarme
	if (xReturn != FF_RECD_SIZE ) {
		FCB.ff_stat.errno = pdFF_ERRNO_MEMRD;
		xReturn = 0U;
		goto quit;
	}

	// Verifico los datos leidos ( checksum )
	// El checksum es solo del dataFrame por eso paso dicho size.
	rdCheckSum = pv_memChecksum(FCB.ff_buffer, xSize );
//	e = xTaskGetTickCount();
	if ( rdCheckSum != FCB.ff_buffer[xSize] ) {
		FCB.ff_stat.errno = pdFF_ERRNO_RDCKS;
		xReturn = 0U;
		goto quit;
	}

	// Vemos si la ultima posicion tiene el tag de ocupado.
	if ( ( FCB.ff_buffer[sizeof(FCB.ff_buffer) - 1] )  != FF_WRTAG ) {
		FCB.ff_stat.errno = pdFF_ERRNO_RDNOTAG;
		xReturn = 0U;
		goto quit;
	}

	// Datos leidos correctamente
	xReturn = xSize;

quit:
	// libero los semaforos
	FreeRTOS_ioctl(&pdI2C,ioctlRELEASE_BUS_SEMPH, NULL);

//	snprintf_P( debug_printfBuff,sizeof(debug_printfBuff),PSTR("DEBUG RD:[%06lu][%06lu][%06lu][%06lu][%06lu]\r\n\0"),a,b,c,d,e  );
//	FreeRTOS_write( &pdUART1, debug_printfBuff, sizeof(debug_printfBuff) );

	return(xReturn);
}
Esempio n. 12
0
//------------------------------------------------------------------------------------
size_t FF_fopen(void)
{
	/*  Debe correrse luego de iniciado el FRTOS ya que utiliza funciones de este !!!
	    Abre el archivo de memoria extEE.
	    Lo recorre buscando el ppio. y el final e inicializa el FCB
	 	Inicializa el sistema de la memoria ( punteros )
		Recorro la memoria buscando transiciones VACIO->DATO y DATO->VACIO.
		La transicion VACIO->DATO determina el puntero DELptr
		La transicion DATO->VACIO determina el puntero WRptr.
		Si no hay transiciones y todos son datos, la memoria esta llena.
		Si no hay transicions y todos son blancos, la memoria esta vacia.
		Si todo anda bien, retorna en ERRNO un NONE.
		En otro caso retorna el recdNbr del error y setea la variable ERRNO

		// Testing con buffer de 16 posiciones:
		// Memoria vacia: OK
		// Memoria llena: OK
		// Memoria con HEAD(10) > TAIL(4), Free(10) OK
		// Memoria con HEAD(3) < TAIL(8), Free(5) OK
		// Condicion de borde 1: HEAD(15), TAIL(0), Free(1) OK
		// Condicion de borde 2: HEAD(0), TAIL(1), Free(1) OK
		// Condicion de borde 3: HEAD(0), TAIL(15), Free(15) OK
		// Condicion de borde 4: HEAD(1), TAIL(0), Free(15) OK

	 */

u08 mark_Z, mark;
u16 xPos;
s08 transicion = FALSE;
u16 val = 0;
size_t xReturn = 0U;

	// Lo primero es obtener el semaforo del I2C
	FreeRTOS_ioctl(&pdI2C,ioctlOBTAIN_BUS_SEMPH, NULL);
	FCB.ff_stat.errno = pdFF_ERRNO_NONE;
	// Indicamos el periferico i2c al cual quiero acceder
	val = EE_ADDR;
	FreeRTOS_ioctl(&pdI2C,ioctl_I2C_SET_DEVADDRESS, &val);
	// Luego indicamos la direccion desde donde leer del dispositivo: largo ( en la ee son 2 bytes )
	val = 2;
	FreeRTOS_ioctl(&pdI2C,ioctl_I2C_SET_BYTEADDRESSLENGTH, &val);

	// El primer registro que leo es el ultimo del archivo
	// direccion de lectura
	xPos = (FF_MAX_RCDS -1);
	val = FF_ADDR_START +  xPos * FF_RECD_SIZE;
	FreeRTOS_ioctl(&pdI2C,ioctl_I2C_SET_BYTEADDRESS,&val);
	// leo una pagina entera, (recd) 64 bytes.
	memset( FCB.ff_buffer,0, sizeof(FCB.ff_buffer) );
	xReturn = FreeRTOS_read(&pdI2C, &FCB.ff_buffer, FF_RECD_SIZE);

#ifdef DEBUG_FF
	snprintf_P( debug_printfBuff,sizeof(debug_printfBuff),PSTR("FO: [%d][%d]\r\n\0"),FF_RECD_SIZE, xReturn);
	FreeRTOS_write( &pdUART1, debug_printfBuff, sizeof(debug_printfBuff) );
#endif

	if ( xReturn != FF_RECD_SIZE ) {
		xReturn = xPos;
		FCB.ff_stat.errno = pdFF_ERRNO_INIT;
		goto quit;
	}
	mark_Z = FCB.ff_buffer[sizeof(FCB.ff_buffer) - 1];

	// Recorro toda la memoria EE buscando transiciones.
	for ( xPos=0; xPos < FF_MAX_RCDS; xPos++) {

		// Para no salir por wdg reset
		if ( (xPos % 128) == 0 ) {
			wdt_reset();
		}

		val = FF_ADDR_START + xPos * FF_RECD_SIZE;
		FreeRTOS_ioctl(&pdI2C,ioctl_I2C_SET_BYTEADDRESS,&val);
		// leo una pagina entera, (recd) 64 bytes.
		memset( FCB.ff_buffer,0, sizeof(FCB.ff_buffer) );
		xReturn = FreeRTOS_read(&pdI2C, &FCB.ff_buffer, FF_RECD_SIZE);

#ifdef DEBUG_FF
//		snprintf_P( debug_printfBuff,sizeof(debug_printfBuff),PSTR("FO: [%d][%d][%d][%d]\r\n\0"),xPos, val,FF_RECD_SIZE, xReturn);
//		FreeRTOS_write( &pdUART1, debug_printfBuff, sizeof(debug_printfBuff) );
#endif
		if ( xReturn != FF_RECD_SIZE )  {
			FCB.ff_stat.errno = pdFF_ERRNO_INIT;
			goto quit;
		}

		mark = FCB.ff_buffer[sizeof(FCB.ff_buffer) - 1];

#ifdef DEBUG_FF
		if ( mark == FF_WRTAG ) {
			snprintf_P( debug_printfBuff,sizeof(debug_printfBuff),PSTR("FO: [%d][%d][%d][%d][0X%03x]\r\n\0"),xPos, val,FF_RECD_SIZE, xReturn, mark);
			FreeRTOS_write( &pdUART1, debug_printfBuff, sizeof(debug_printfBuff) );
		}
#endif

		// busco transiciones:
		if ( ( mark_Z == 0) && ( mark == FF_WRTAG ) ) {
			// Tengo una transicion VACIO->DATO.
			FCB.ff_stat.TAIL = xPos;
			transicion = TRUE;
		}

		if ( ( mark_Z == FF_WRTAG ) && ( mark == 0) ) {
			// Tengo una transicion DATO->VACIO.
			FCB.ff_stat.HEAD = xPos;
			transicion = TRUE;
		}

		mark_Z = mark;
	}

	// Recorri toda la memoria. Analizo las transiciones...
	if ( ! transicion ) {
		// Si no hubieron transiciones es que la memoria esta llena o vacia.
		if ( mark == 0 ) {
			// Memoria vacia.
			FCB.ff_stat.HEAD = 0;
			FCB.ff_stat.TAIL = 0;
			FCB.ff_stat.RD  = FCB.ff_stat.TAIL;
			FCB.ff_stat.rcdsFree = FF_MAX_RCDS;
		} else {
			// Memoria llena
			FCB.ff_stat.HEAD = 0;
			FCB.ff_stat.TAIL = 0;
			FCB.ff_stat.RD  = FCB.ff_stat.TAIL;
			FCB.ff_stat.rcdsFree = 0;
		}
	} else {
		// Memoria con datos. Calculo los registro ocupados.
		if ( FCB.ff_stat.HEAD > FCB.ff_stat.TAIL) {
			FCB.ff_stat.RD  = FCB.ff_stat.TAIL;
			FCB.ff_stat.rcdsFree = FF_MAX_RCDS - FCB.ff_stat.HEAD + FCB.ff_stat.TAIL;
		} else {
			FCB.ff_stat.RD  = FCB.ff_stat.TAIL;
			FCB.ff_stat.rcdsFree = FCB.ff_stat.TAIL - FCB.ff_stat.HEAD;
		}
	}

quit:

	FreeRTOS_ioctl(&pdI2C,ioctlRELEASE_BUS_SEMPH, NULL);

#ifdef DEBUG_FF
		snprintf_P( debug_printfBuff,sizeof(debug_printfBuff),PSTR("FO: [%d][%d]\r\n\0"),xPos, FCB.ff_stat.errno);
		FreeRTOS_write( &pdUART1, debug_printfBuff, sizeof(debug_printfBuff) );
#endif

	return(xPos);

}
Esempio n. 13
0
//------------------------------------------------------------------------------------
size_t FF_fwrite( const void *pvBuffer, size_t xSize)
{
	// El archivo es del tipo circular FirstIN-LastOUT.
	// Escribe un registro en la posicion apuntada por el HEAD.
	// El registro que se pasa en pvBuffer es del tipo 'frameData_t' de 38 bytes
	// pero en la memoria voy a escribir de a paginas de 64 bytes.
	// Retorna el nro.de bytes escritos y setea la variable 'errno' del FCB
	// En la posicion 63 grabo un tag con el valor 0xC5 para poder luego
	// determinar si el registro esta ocupado o vacio.

	// TESTING:
	// Memoria vacia: OK
	// Memoria llena: OK
	// Memoria con HEAD(10) > TAIL(4), Free(10) OK
	// Memoria con HEAD(3) < TAIL(8), Free(5) OK
	// Condicion de borde 1: HEAD(15), TAIL(0), Free(1) OK
	// Condicion de borde 2: HEAD(0), TAIL(1), Free(1) OK

u16 val = 0;
size_t xReturn = 0U;
u16 tryes;

	// Lo primero es obtener el semaforo del I2C
	FreeRTOS_ioctl(&pdI2C,ioctlOBTAIN_BUS_SEMPH, NULL);
	FCB.ff_stat.errno = pdFF_ERRNO_NONE;

	// Si la memoria esta llena no puedo escribir: salgo
	if ( FCB.ff_stat.rcdsFree == 0 ) {
		FCB.ff_stat.errno = pdFF_ERRNO_MEMFULL;
		goto quit;
	}

	// inicializo la estructura lineal temporal en el FCB para copiar ahi los datos y
	// calcular el checksum antes de grabarlo en memoria.
	memset( FCB.ff_buffer,0, sizeof(FCB.ff_buffer) );
	// copio los datos recibidos del frame al buffer ( 0..(xSize-1))
	memcpy ( FCB.ff_buffer, pvBuffer, xSize );
	// Calculo y grabo el checksum a continuacion del frame (en la pos.xSize)
	// El checksum es solo del dataFrame por eso paso dicho size.
	FCB.ff_buffer[xSize] = pv_memChecksum(FCB.ff_buffer, xSize );
	// Grabo el tag para indicar que el registro esta escrito.
	FCB.ff_buffer[sizeof(FCB.ff_buffer) - 1] = FF_WRTAG;

	// EE WRITE:
	// Luego indicamos el periferico i2c en el cual queremos leer
	val = EE_ADDR;
	FreeRTOS_ioctl(&pdI2C,ioctl_I2C_SET_DEVADDRESS, &val);
	// Luego indicamos la direccion a escribir del dispositivo: largo ( en la ee son 2 bytes )
	val = 2;
	FreeRTOS_ioctl(&pdI2C,ioctl_I2C_SET_BYTEADDRESSLENGTH, &val);
	// y direccion interna en la EE.(comienzo del registro / frontera)
	val = FF_ADDR_START + FCB.ff_stat.HEAD * FF_RECD_SIZE;
	FreeRTOS_ioctl(&pdI2C,ioctl_I2C_SET_BYTEADDRESS,&val);

	// Por ultimo escribo la memoria. Escribo un pagina entera, 64 bytes.
	// Reintento hasta 3 veces.
	for ( tryes = 0; tryes < 3; tryes++ ) {
		// Write
		xReturn = FreeRTOS_write(&pdI2C, &FCB.ff_buffer, FF_RECD_SIZE);
		taskYIELD();
		// Verify
		FreeRTOS_read(&pdI2C, &FCB.check_buffer, FF_RECD_SIZE);

		if ( memcmp (&FCB.check_buffer, &FCB.ff_buffer, FF_RECD_SIZE) == 0 )
			break;

		if  ( tryes == 3 ) {
			snprintf_P( debug_printfBuff,sizeof(debug_printfBuff),PSTR("FS WR ERR: [%d]\r\n\0"), val);
			FreeRTOS_write( &pdUART1, debug_printfBuff, sizeof(debug_printfBuff) );
			FCB.ff_stat.errno = pdFF_ERRNO_MEMWR;
			xReturn = 0U;
			goto quit;
		}
	}

	if (xReturn != FF_RECD_SIZE ) {
		// Errores de escritura ?
		FCB.ff_stat.errno = pdFF_ERRNO_MEMWR;
		xReturn = 0U;
		goto quit;
	} else {
		xReturn = xSize;
		// Avanzo el puntero de WR en modo circular
		FCB.ff_stat.HEAD = (++FCB.ff_stat.HEAD == FF_MAX_RCDS) ?  0 : FCB.ff_stat.HEAD;
		FCB.ff_stat.rcdsFree--;
	}

quit:
	// libero los semaforos
	FreeRTOS_ioctl(&pdI2C,ioctlRELEASE_BUS_SEMPH, NULL);
	return(xReturn);

}