/********************************************************************
 FileName:      main.c
 Dependencies:  See INCLUDES section
 Processor:     PIC18, PIC24, dsPIC, and PIC32 USB Microcontrollers
 Hardware:      This demo is natively intended to be used on Microchip USB demo
                boards supported by the MCHPFSUSB stack.  See release notes for
                support matrix.  This demo can be modified for use on other 
                hardware platforms.
 Complier:      Microchip C18 (for PIC18), XC16 (for PIC24/dsPIC), XC32 (for PIC32)
 Company:       Microchip Technology, Inc.

 Software License Agreement:

 The software supplied herewith by Microchip Technology Incorporated
 (the "Company") for its PIC(R) Microcontroller is intended and
 supplied to you, the Company's customer, for use solely and
 exclusively on Microchip PIC Microcontroller products. The
 software is owned by the Company and/or its supplier, and is
 protected under applicable copyright laws. All rights are reserved.
 Any use in violation of the foregoing restrictions may subject the
 user to criminal sanctions under applicable laws, as well as to
 civil liability for the breach of the terms and conditions of this
 license.

 THIS SOFTWARE IS PROVIDED IN AN "AS IS" CONDITION. NO WARRANTIES,
 WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING, BUT NOT LIMITED
 TO, IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
 PARTICULAR PURPOSE APPLY TO THIS SOFTWARE. THE COMPANY SHALL NOT,
 IN ANY CIRCUMSTANCES, BE LIABLE FOR SPECIAL, INCIDENTAL OR
 CONSEQUENTIAL DAMAGES, FOR ANY REASON WHATSOEVER.

********************************************************************/

/** INCLUDES *******************************************************/
#include "./USB/usb.h"
#include "./USB/usb_function_cdc.h"

#include "HardwareProfile.h"

/** CONFIGURATION **************************************************/

#pragma config PLLSEL   = PLL3X     // 3X PLL multiplier selected
#pragma config CFGPLLEN = OFF       // PLL turned on during execution
#pragma config CPUDIV   = NOCLKDIV  // 1:1 mode (for 48MHz CPU)
#pragma config LS48MHZ  = SYS48X8   // Clock div / 8 in Low Speed USB mode
#pragma config FOSC     = INTOSCIO  // HFINTOSC selected at powerup, no clock out
#pragma config PCLKEN   = OFF       // Primary oscillator driver
#pragma config FCMEN    = OFF       // Fail safe clock monitor
#pragma config IESO     = OFF       // Internal/external switchover (two speed startup)
#pragma config nPWRTEN  = OFF       // Power up timer
#pragma config BOREN    = SBORDIS   // BOR enabled
#pragma config nLPBOR   = ON        // Low Power BOR
#pragma config WDTEN    = SWON      // Watchdog Timer controlled by SWDTEN
#pragma config WDTPS    = 32768     // WDT postscalar
#pragma config PBADEN   = OFF       // Port B Digital/Analog Powerup Behavior
#pragma config SDOMX    = RC7       // SDO function location
#pragma config LVP      = OFF       // Low voltage programming
#pragma config MCLRE    = ON        // MCLR function enabled (RE3 disabled)
#pragma config STVREN   = ON        // Stack overflow reset
#pragma config XINST    = OFF       // Extended instruction set

/** I N C L U D E S **********************************************************/

#include "GenericTypeDefs.h"
#include "Compiler.h"
#include "usb_config.h"
#include "USB/usb_device.h"
#include "USB/usb.h"

#include "HardwareProfile.h"

/** V A R I A B L E S ********************************************************/
#if defined(__18CXX)
#pragma udata
#endif
char USB_Out_Buffer[CDC_DATA_OUT_EP_SIZE];
char RS232_Out_Data[CDC_DATA_IN_EP_SIZE];


unsigned char   NextUSBOut;
unsigned char   NextUSBOut;

//char RS232_In_Data;
unsigned char   LastRS232Out;  // Number of characters in the buffer
unsigned char   RS232cp;       // current position within the buffer
unsigned char   RS232_Out_Data_Rdy = 0;

USB_HANDLE      lastTransmission;

/** VARIABLES AND DEFINITIONS FOR RN4020 PICTAIL APP ****************/

#define FIRMWARE_VERSION_MAJOR 0x02
#define FIRMWARE_VERSION_MINOR 0x00

#define MAX_CMD_SIZE 20
#define memcpy_cmd_prompt(a) memcpy((void*)a, (void*)&USB_Out_Buffer_CMD[9], 3)

unsigned char   val8 = 0;
unsigned char   control_console_escape = 0;
unsigned char   control_console_set = 0;
unsigned char   control_console_escape_guard = 0;
char            RS232_Cmd_Data[MAX_CMD_SIZE];
volatile unsigned long int sof_milli_second = 0;
volatile unsigned long int sof_milli_second_test = 0;

const char      USB_Out_Buffer_CMD[] = {'<', 'P', 'I', 'C', '-', 'C', 'M', 'D', '>', '\r', '\n', '>'};
const char      USB_Out_Buffer_END[] = {'\r', '\n', '<', 'P', 'I', 'C', '-', 'E', 'N', 'D', '>', '\r', '\n'};
const char      help_text[] =
{
    '\r','\n','>',
    'I','#','X',',','Y','Y','-','S','e','t','s','/','C','l','e','a','r','s',' ','I','O','\r','\n',
    '>','I','%','X','-','R','e','a','d','s',' ','I','O','\r','\n',
    '>','I','@','X',',','Y','Y','-','S','e','t','s',' ','I','O',' ','d','i','r','\r','\n',
    '>'
};

#ifdef TEST_MODE
const char  buffer_command_server_services[] = {'S', 'S', ',', 'F', '0', '1', 'C', '0', '0', '0', '0', '\r'};
const char  buffer_command_client_services[] = {'S', 'C', ',', 'C', '0', '0', '0', '0', '0', '0', '0', '\r'};
const char  buffer_command_features[] = {'S', 'R', ',', '2', '2', '0', '0', '0', '0', '0', '0','\r'};
const char  buffer_command_factory[] = {'S', 'F', ',', '1', '\r'};
const char  buffer_command_reset[] = {'R', ',', '1', '\r'};
const char  buffer_command_clearpdl[] = {'U', '\r'};
const char  buffer_command_adv[] = {'A', '\r'};
const char  buffer_command_endadv[] = {'Y', '\r'};
char        buffer_command_hrate[] = {'S', 'U', 'W', ',', '2', 'a', '3', '7', ',', '1', 'F', '4', '4', '0', '0', 'B', 'B', '0', '0', 'E', 'E', '0', '0', '\r'};
char        buffer_command_sensor_location[] = {'S', 'U', 'W', ',', '2', 'a', '3', '8', ',', '0', '1', '\r'};
char        buffer_command_temperature[] = {'S', 'U', 'W', ',', '2', 'a', '1', 'C', ',', '0', '1', '4', 'B', '0', '0', '0', '0', '0', '0', '\r'};
char        buffer_command_battery[] = {'S', 'U', 'W', ',', '2', 'a', '1', '9', ',', '5', 'C', '\r'};

unsigned char heart_rate_value = 0x44;
unsigned char egy_exp_value = 0x82;
unsigned char rr_int_value = 0xA2;
unsigned char battery_value = 0x64;
unsigned char location_value = 0x01;
unsigned char temperature_value = 0x4B;

unsigned int test_mode_flag = 0;

#define BUFFER_LEN_MAX 64
char buffer_rx[BUFFER_LEN_MAX];
#endif

/** P R I V A T E  P R O T O T Y P E S ***************************************/
static void InitializeSystem(void);
void ProcessIO(void);
void USBDeviceTasks(void);
void YourHighPriorityISRCode();
void YourLowPriorityISRCode();
void USBCBSendResume(void);
void BlinkUSBStatus(void);
void UserInit(void);
void InitializeUSART(void);
void putcUSART(char c);
unsigned char getcUSART1 ();
unsigned char get_hex_byte(char * str, unsigned char *) ;
unsigned char get_hex(char * str, unsigned short int *) ;
unsigned char get_hex_dword(char * str, unsigned long int *) ;
unsigned char get_hex_24bit(char * str, unsigned long int *) ;
void format_hex_byte(char * str, unsigned char) ;
void format_hex_byte2(char * str, unsigned char) ;
void format_hex(char * str, unsigned short int) ;
void format_hex_dword(char * str, unsigned long int) ;
void format_hex_24bit(char * str, unsigned long int) ;

/** VECTOR REMAPPING ***********************************************/
#if defined(__18CXX)
	//On PIC18 devices, addresses 0x00, 0x08, and 0x18 are used for
	//the reset, high priority interrupt, and low priority interrupt
	//vectors.  However, the Microchip HID bootloader occupies the
	//0x00-0xFFF program memory region.  Therefore, the bootloader code remaps 
	//these vectors to new locations as indicated below.  This remapping is 
	//only necessary if you wish to be able to (optionally) program the hex file 
	//generated from this project with the USB bootloader.  
	#define REMAPPED_RESET_VECTOR_ADDRESS			0x1000
	#define REMAPPED_HIGH_INTERRUPT_VECTOR_ADDRESS	0x1008
	#define REMAPPED_LOW_INTERRUPT_VECTOR_ADDRESS	0x1018
	#define APP_VERSION_ADDRESS                     0x1016 //Fixed location, so the App FW image version can be read by the bootloader.
	#define APP_SIGNATURE_ADDRESS                   0x1006 //Signature location that must be kept at blaknk value (0xFFFF) in this project (has special purpose for bootloader).

    //--------------------------------------------------------------------------
    //Application firmware image version values, as reported to the bootloader
    //firmware.  These are useful so the bootloader can potentially know if the
    //user is trying to program an older firmware image onto a device that
    //has already been programmed with a with a newer firmware image.
    //Format is APP_FIRMWARE_VERSION_MAJOR.APP_FIRMWARE_VERSION_MINOR.
    //The valid minor version is from 00 to 99.  Example:
    //if APP_FIRMWARE_VERSION_MAJOR == 1, APP_FIRMWARE_VERSION_MINOR == 1,
    //then the version is "1.01"
    #define APP_FIRMWARE_VERSION_MAJOR  1   //valid values 0-255
    #define APP_FIRMWARE_VERSION_MINOR  0   //valid values 0-99
    //--------------------------------------------------------------------------
	
	#pragma romdata AppVersionAndSignatureSection = APP_VERSION_ADDRESS
	ROM unsigned char AppVersion[2] = {APP_FIRMWARE_VERSION_MINOR, APP_FIRMWARE_VERSION_MAJOR};
	#pragma romdata AppSignatureSection = APP_SIGNATURE_ADDRESS
	ROM unsigned short int SignaturePlaceholder = 0xFFFF;
	
	#pragma code HIGH_INTERRUPT_VECTOR = 0x08
	void High_ISR (void)
	{
	     _asm goto REMAPPED_HIGH_INTERRUPT_VECTOR_ADDRESS _endasm
	}
	#pragma code LOW_INTERRUPT_VECTOR = 0x18
	void Low_ISR (void)
	{
	     _asm goto REMAPPED_LOW_INTERRUPT_VECTOR_ADDRESS _endasm
	}
	extern void _startup (void);        // See c018i.c in your C18 compiler dir
	#pragma code REMAPPED_RESET_VECTOR = REMAPPED_RESET_VECTOR_ADDRESS
	void _reset (void)
	{
	    _asm goto _startup _endasm
	}
	#pragma code REMAPPED_HIGH_INTERRUPT_VECTOR = REMAPPED_HIGH_INTERRUPT_VECTOR_ADDRESS
	void Remapped_High_ISR (void)
	{
	     _asm goto YourHighPriorityISRCode _endasm
	}
	#pragma code REMAPPED_LOW_INTERRUPT_VECTOR = REMAPPED_LOW_INTERRUPT_VECTOR_ADDRESS
	void Remapped_Low_ISR (void)
	{
	     _asm goto YourLowPriorityISRCode _endasm
	}
	#pragma code
	
	
	//These are your actual interrupt handling routines.
	#pragma interrupt YourHighPriorityISRCode
	void YourHighPriorityISRCode()
	{
		//Check which interrupt flag caused the interrupt.
		//Service the interrupt
		//Clear the interrupt flag
		//Etc.
        #if defined(USB_INTERRUPT)
	        USBDeviceTasks();
        #endif
	
	}	//This return will be a "retfie fast", since this is in a #pragma interrupt section 
	#pragma interruptlow YourLowPriorityISRCode
	void YourLowPriorityISRCode()
	{
		//Check which interrupt flag caused the interrupt.
		//Service the interrupt
		//Clear the interrupt flag
		//Etc.
	
	}	//This return will be a "retfie", since this is in a #pragma interruptlow section 

#endif



/** DECLARATIONS ***************************************************/
#if defined(__18CXX)
    #pragma code
#endif

/******************************************************************************
 * Function:        void main(void)
 *
 * PreCondition:    None
 *
 * Input:           None
 *
 * Output:          None
 *
 * Side Effects:    None
 *
 * Overview:        Main program entry point.
 *
 * Note:            None
 *****************************************************************************/
#if defined(__18CXX)
void main(void)
#else
int main(void)
#endif
{   
    InitializeSystem();

    #if defined(USB_INTERRUPT)
        USBDeviceAttach();
    #endif

    while(1)
    {
        // Application-specific tasks.
        // Application related code may be added here, or in the ProcessIO() function.
        ProcessIO();        
    }//end while
}//end main


/********************************************************************
 * Function:        static void InitializeSystem(void)
 *
 * PreCondition:    None
 *
 * Input:           None
 *
 * Output:          None
 *
 * Side Effects:    None
 *
 * Overview:        InitializeSystem is a centralize initialization
 *                  routine. All required USB initialization routines
 *                  are called from here.
 *
 *                  User application initialization routine should
 *                  also be called from here.                  
 *
 * Note:            None
 *******************************************************************/
static void InitializeSystem(void)
{
    #if (defined(__18CXX) & !defined(PIC18F87J50_PIM) & !defined(PIC18F97J94_FAMILY))
        ADCON1 |= 0x0F;                 // Default all pins to digital
    #endif

    #if defined(RN4020)
        //Configure oscillator settings for clock settings compatible with USB
        //operation.  Note: Proper settings depends on USB speed (full or low).
        #if(USB_SPEED_OPTION == USB_FULL_SPEED)
            OSCTUNE = 0x80; //3X PLL ratio mode selected
            OSCCON = 0x70;  //Switch to 16MHz HFINTOSC
            OSCCON2 = 0x10; //Enable PLL, SOSC, PRI OSC drivers turned off
            while(OSCCON2bits.PLLRDY != 1);   //Wait for PLL lock
            *((unsigned char*)0xFB5) = 0x90;  //Enable active clock tuning for USB operation
        #endif
        //Configure all I/O pins for digital mode (except RA0/AN0 which has POT on demo board)
        ANSELA = 0x01;
        ANSELB = 0x00;
        ANSELC = 0x00;
//        ANSELD = 0x00;
//        ANSELE = 0x00;
    #endif

//	The USB specifications require that USB peripheral devices must never source
//	current onto the Vbus pin.  Additionally, USB peripherals should not source
//	current on D+ or D- when the host/hub is not actively powering the Vbus line.
//	When designing a self powered (as opposed to bus powered) USB peripheral
//	device, the firmware should make sure not to turn on the USB module and D+
//	or D- pull up resistor unless Vbus is actively powered.  Therefore, the
//	firmware needs some means to detect when Vbus is being powered by the host.
//	A 5V tolerant I/O pin can be connected to Vbus (through a resistor), and
// 	can be used to detect when Vbus is high (host actively powering), or low
//	(host is shut down or otherwise not supplying power).  The USB firmware
// 	can then periodically poll this I/O pin to know when it is okay to turn on
//	the USB module/D+/D- pull up resistor.  When designing a purely bus powered
//	peripheral device, it is not possible to source current on D+ or D- when the
//	host is not actively providing power on Vbus. Therefore, implementing this
//	bus sense feature is optional.  This firmware can be made to use this bus
//	sense feature by making sure "USE_USB_BUS_SENSE_IO" has been defined in the
//	HardwareProfile.h file.    
    #if defined(USE_USB_BUS_SENSE_IO)
    tris_usb_bus_sense = INPUT_PIN; // See HardwareProfile.h
    #endif
    
//	If the host PC sends a GetStatus (device) request, the firmware must respond
//	and let the host know if the USB peripheral device is currently bus powered
//	or self powered.  See chapter 9 in the official USB specifications for details
//	regarding this request.  If the peripheral device is capable of being both
//	self and bus powered, it should not return a hard coded value for this request.
//	Instead, firmware should check if it is currently self or bus powered, and
//	respond accordingly.  If the hardware has been configured like demonstrated
//	on the PICDEM FS USB Demo Board, an I/O pin can be polled to determine the
//	currently selected power source.  On the PICDEM FS USB Demo Board, "RA2" 
//	is used for	this purpose.  If using this feature, make sure "USE_SELF_POWER_SENSE_IO"
//	has been defined in HardwareProfile - (platform).h, and that an appropriate I/O pin 
//  has been mapped	to it.
    #if defined(USE_SELF_POWER_SENSE_IO)
    tris_self_power = INPUT_PIN;	// See HardwareProfile.h
    #endif
    
    UserInit();

    USBDeviceInit();	//usb_device.c.  Initializes USB module SFRs and firmware
    					//variables to known states.
}//end InitializeSystem



/******************************************************************************
 * Function:        void UserInit(void)
 *
 * PreCondition:    None
 *
 * Input:           None
 *
 * Output:          None
 *
 * Side Effects:    None
 *
 * Overview:        This routine should take care of all of the demo code
 *                  initialization that is required.
 *
 * Note:            
 *
 *****************************************************************************/
void UserInit(void)
{
    unsigned char i;
    InitializeUSART();

    // 	 Initialize the arrays
    for (i=0; i<sizeof(USB_Out_Buffer); i++)
    {
        USB_Out_Buffer[i] = 0;
    }

    NextUSBOut = 0;
    LastRS232Out = 0;
    lastTransmission = 0;

    mInitAllLEDs();

    SWAKE_OUTPUT = 0;
    SWAKE_TRISTx = OUTPUT_PIN;
    SWAKE_OUTPUT = 1;

    CMD_OUTPUT = 0;
    CMD_TRISTx = OUTPUT_PIN;
}//end UserInit

/******************************************************************************
 * Function:        void InitializeUSART(void)
 *
 * PreCondition:    None
 *
 * Input:           None
 *
 * Output:          None
 *
 * Side Effects:    None
 *
 * Overview:        This routine initializes the UART to 19200
 *
 * Note:            
 *
 *****************************************************************************/
void InitializeUSART(void)
{
    #if defined(__18CXX) || defined(__XC8)
        unsigned char c;

        UART_TRISRx=1;				// RX
        UART_TRISTx=0;				// TX
        TXSTA = 0x24;       	// TX enable BRGH=1
        RCSTA = 0x90;       	// Single Character RX
        SPBRG = 0x71;
        SPBRGH = 0x02;      	// 0x0271 for 48MHz -> 19200 baud
        BAUDCON = 0x08;     	// BRG16 = 1
        c = RCREG;				// read 
    #endif

}//end InitializeUSART

#if defined(__18CXX) || defined(__XC8)
    #define mDataRdyUSART() PIR1bits.RCIF
    #define mTxRdyUSART()   TXSTAbits.TRMT
#endif

/******************************************************************************
 * Function:        void putcUSART(char c)
 *
 * PreCondition:    None
 *
 * Input:           char c - character to print to the UART
 *
 * Output:          None
 *
 * Side Effects:    None
 *
 * Overview:        Print the input character to the UART
 *
 * Note:            
 *
 *****************************************************************************/
void putcUSART(char c)  
{
    #if defined(__18CXX) || defined(__XC8)
	    TXREG = c;
    #endif
}


/******************************************************************************
 * Function:        void mySetLineCodingHandler(void)
 *
 * PreCondition:    USB_CDC_SET_LINE_CODING_HANDLER is defined
 *
 * Input:           None
 *
 * Output:          None
 *
 * Side Effects:    None
 *
 * Overview:        This function gets called when a SetLineCoding command
 *                  is sent on the bus.  This function will evaluate the request
 *                  and determine if the application should update the baudrate
 *                  or not.
 *
 * Note:            
 *
 *****************************************************************************/
#if defined(USB_CDC_SET_LINE_CODING_HANDLER)
void mySetLineCodingHandler(void)
{
    //If the request is not in a valid range
    if(cdc_notice.GetLineCoding.dwDTERate.Val > 115200)
    {
        //NOTE: There are two ways that an unsupported baud rate could be
        //handled.  The first is just to ignore the request and don't change
        //the values.  That is what is currently implemented in this function.
        //The second possible method is to stall the STATUS stage of the request.
        //STALLing the STATUS stage will cause an exception to be thrown in the 
        //requesting application.  Some programs, like HyperTerminal, handle the
        //exception properly and give a pop-up box indicating that the request
        //settings are not valid.  Any application that does not handle the
        //exception correctly will likely crash when this requiest fails.  For
        //the sake of example the code required to STALL the status stage of the
        //request is provided below.  It has been left out so that this demo
        //does not cause applications without the required exception handling
        //to crash.
        //---------------------------------------
        //USBStallEndpoint(0,1);
    }
    else
    {
        //Update the baudrate info in the CDC driver
        CDCSetBaudRate(cdc_notice.GetLineCoding.dwDTERate.Val);
        
        //Update the baudrate of the UART
        #if defined(__18CXX) || defined(__XC8)
        {
            DWORD_VAL dwBaud;
            dwBaud.Val = (DWORD)(GetSystemClock()/4)/line_coding.dwDTERate.Val-1;
            SPBRG = dwBaud.v[0];
            SPBRGH = dwBaud.v[1];
        }    
        #endif
    }
}
#endif

/******************************************************************************
 * Function:        void putcUSART(char c)
 *
 * PreCondition:    None
 *
 * Input:           None
 *
 * Output:          unsigned char c - character to received on the UART
 *
 * Side Effects:    None
 *
 * Overview:        Print the input character to the UART
 *
 * Note:            
 *
 *****************************************************************************/
unsigned char getcUSART1 ()
{
    char  c;

    #if defined(__18CXX) || defined(__XC8)

    if (RCSTAbits.OERR)  // in case of overrun error
    {                    // we should never see an overrun error, but if we do,
        RCSTAbits.CREN = 0;  // reset the port
        c = RCREG;
        RCSTAbits.CREN = 1;  // and keep going.
    }
    else
    {
        c = RCREG;
    }
// not necessary.  EUSART auto clears the flag when RCREG is cleared
//	PIR1bits.RCIF = 0;    // clear Flag

    #endif
    return c;
}


/** RN4020 PICTAIL: PIC18 COMMAND SHELL ***********************************************/

void send_command(char* src)
{
    char* psrc = src;
    while(*psrc != '\r')
    {
        if(mTxRdyUSART())
            putcUSART(*psrc++);
    }
    putcUSART('\r');
}


void get_response(char* dst)
{
    char* pdst = dst;

    while(1){
        if(mDataRdyUSART())
        {
            *pdst = getcUSART1();          
            if(*pdst == '\r')
                break;
            if(*pdst != '\n')
                pdst++;
        }
    }
}
 

/** RN4020 PICTAIL: AUTO-DEMO MODE ***********************************************/
#ifdef TEST_MODE
void test_mode_start(void)
{
    heart_rate_value = 0x0044;
    sof_milli_second_test = 0;
    send_command((char*)buffer_command_factory);
    get_response(buffer_rx);
    send_command((char*)buffer_command_server_services);
    get_response(buffer_rx);
    send_command((char*)buffer_command_client_services);
    get_response(buffer_rx);
    send_command((char*)buffer_command_features);
    get_response(buffer_rx);
    send_command((char*)buffer_command_sensor_location);
    get_response(buffer_rx);
    send_command((char*)buffer_command_reset);
    get_response(buffer_rx);
    test_mode_flag = 1;
}

void test_mode_end(void)
{
    test_mode_flag = 0;
    send_command((char*)buffer_command_factory);
    get_response(buffer_rx);    
    send_command((char*)buffer_command_reset);
    get_response(buffer_rx);
    
    //Read for CMD at RN4020 startup
    get_response(buffer_rx);

    heart_rate_value = 0x0044;
    sof_milli_second_test = 0;
    
}

void test_mode_process(void)
{
    unsigned char temp;
    if(sof_milli_second_test >= 1000)   //Update data every 1 sec
    {
        if(test_mode_flag == 1)
        {

            // Format heart rate measurement data
            if(heart_rate_value < 200)
            heart_rate_value++;
            else
            heart_rate_value = 40;
            egy_exp_value++;
            if(egy_exp_value < 60)
            egy_exp_value = 60;
            rr_int_value++;
            if(rr_int_value < 60)
            rr_int_value = 60;
            format_hex_byte2(&buffer_command_hrate[11], heart_rate_value);
            format_hex_byte2(&buffer_command_hrate[15], egy_exp_value);
            format_hex_byte2(&buffer_command_hrate[19], rr_int_value);
            buffer_command_hrate[23] = '\r';
            send_command(buffer_command_hrate);
            get_response(buffer_rx);

            // Format heart rate sensor location data
            format_hex_byte2(&buffer_command_sensor_location[9], location_value);
            buffer_command_sensor_location[11] = '\r';
            send_command(buffer_command_sensor_location);
            get_response(buffer_rx);
            location_value = location_value + 1;
            if(location_value > 6)
                location_value = 1;

            // Format battery measurement data
            format_hex_byte2(&buffer_command_battery[9], battery_value);
            buffer_command_battery[11] = '\r';
            send_command(buffer_command_battery);
            get_response(buffer_rx);
            battery_value = battery_value-1;
            if(battery_value < 1)
                battery_value = 100;

            // Format temperature data
            format_hex_byte2(&buffer_command_temperature[11], temperature_value);
            send_command(buffer_command_temperature);
            get_response(buffer_rx);
            temperature_value = temperature_value - 1;
            if(temperature_value < 50)
                temperature_value = 100;
        }
        sof_milli_second_test = 0;
    }
}
#endif

/** RN4020 PICTAIL: PIC18 COMMAND SHELL PARSER ***********************************************/
char set_to_upper(char lower)
{
    if((lower >= 'a') && (lower <= 'z'))
        return ('A'+lower-'a');
    else
        return lower;
}

void command_error(void)
{
    memcpy_cmd_prompt(&USB_Out_Buffer[0]);
    USB_Out_Buffer[3]='E';
    USB_Out_Buffer[4]='R';
    USB_Out_Buffer[5]='R';
    memcpy_cmd_prompt(&USB_Out_Buffer[6]);
    NextUSBOut = 9;
}

void command_ok(void)
{
    memcpy_cmd_prompt(&USB_Out_Buffer[0]);
    USB_Out_Buffer[3]='O';
    USB_Out_Buffer[4]='K';
    memcpy_cmd_prompt(&USB_Out_Buffer[5]);
    NextUSBOut = 8;
}

BOOL command_parse(void)
{
    BOOL res = FALSE;
    if(RS232_Out_Data[0] != '\r')
    {
        RS232_Cmd_Data[val8++] = RS232_Out_Data[0];
        if(val8 > MAX_CMD_SIZE) val8 = 0;
    }
    else
    {
        val8 = 0;
        switch(set_to_upper(RS232_Cmd_Data[0]))
        {
            case 'I':
                {
                    if((RS232_Cmd_Data[3] == ',') || (RS232_Cmd_Data[1] == '%'))
                    {
                        get_hex_byte(&RS232_Cmd_Data[4], &val8);
                        switch(RS232_Cmd_Data[1])
                        {
                            case '@':
                                if(set_to_upper(RS232_Cmd_Data[2]) == 'A')
                                    TRISA = val8;
                                else if(set_to_upper(RS232_Cmd_Data[2]) == 'B')
                                    TRISB = val8;
                                else if(set_to_upper(RS232_Cmd_Data[2]) == 'C')
                                    TRISC = val8;
                                else
                                    goto error_label;
                                command_ok();
                                res = TRUE;
                                break;

                            case '#':
                                if(set_to_upper(RS232_Cmd_Data[2]) == 'A')
                                    LATA = val8;
                                else if(set_to_upper(RS232_Cmd_Data[2]) == 'B')
                                    LATB = val8;
                                else if(set_to_upper(RS232_Cmd_Data[2]) == 'C')
                                    LATC = val8;
                                else
                                    goto error_label;
                                command_ok();
                                res = TRUE;
                                break;

                            case '%':
                                if(set_to_upper(RS232_Cmd_Data[2]) == 'A')
                                    val8 = PORTA;
                                else if(set_to_upper(RS232_Cmd_Data[2]) == 'B')
                                    val8 = PORTB;
                                else if(set_to_upper(RS232_Cmd_Data[2]) == 'C')
                                    val8 = PORTC;
                                else
                                    goto error_label;
                                memcpy_cmd_prompt(&USB_Out_Buffer[0]);
                                format_hex_byte(&USB_Out_Buffer[3], val8);
                                memcpy_cmd_prompt(&USB_Out_Buffer[6]);
                                NextUSBOut = 9;
                                res = TRUE;
                                break;

                            default:
                            error_label:
                                command_error();
                                res = TRUE;
                                break;
                        }
                    }
                    else
                    {
                        command_error();
                        res = TRUE;
                    }

                }
                break;

            case 'V':
                memcpy_cmd_prompt(&USB_Out_Buffer[0]);
                format_hex_byte(&USB_Out_Buffer[3], FIRMWARE_VERSION_MAJOR);
                USB_Out_Buffer[5] = '.';
                format_hex_byte(&USB_Out_Buffer[6], FIRMWARE_VERSION_MINOR);
                memcpy_cmd_prompt(&USB_Out_Buffer[8]);
                NextUSBOut = 11;
                res = TRUE;
                break;

            case 'H':
                memcpy((void*)USB_Out_Buffer, (void*)&help_text[0], 64);
                NextUSBOut = 63;
                res = TRUE;
                break;
 #ifdef TEST_MODE
            case 'T':
                if(RS232_Cmd_Data[1] == ',')
                {
                    if(set_to_upper(RS232_Cmd_Data[2]) == 'S')
                    {
                        test_mode_start();
                        command_ok();
                        res = TRUE;
                    }
                    else if(set_to_upper(RS232_Cmd_Data[2]) == 'E')
                    {
                        test_mode_end();
                        command_ok();
                        res = TRUE;
                    }
                    else
                    {
                        command_error();
                        res = TRUE;
                    }
                }                   

                else
                {
                    command_error();
                    res = TRUE;
                }
                break;
#endif
                    
            default:
                command_error();
                res = TRUE;
                break;
        }
        memset(&RS232_Cmd_Data[0], (int)'0', MAX_CMD_SIZE);
        val8 = 0;
    }

    return res;

}

void command_escape(void)
{
    control_console_escape++;
    if(control_console_escape == 3)
    {
        control_console_escape_guard = 0;
        control_console_escape = 0;
        if(control_console_set == 0)
        {
            control_console_set = 1;
            memcpy((void*)&USB_Out_Buffer[0], (void*)&USB_Out_Buffer_CMD[0], sizeof(USB_Out_Buffer_CMD));
            NextUSBOut = sizeof(USB_Out_Buffer_CMD);
            //CMD_OUTPUT = 1;
        }
        else if(control_console_set == 1)
        {
#ifdef TEST_MODE
            if(test_mode_flag == 1)
                test_mode_end();
#endif
            control_console_set = 0;
            memcpy((void*)&USB_Out_Buffer[0], (void*)&USB_Out_Buffer_END[0], sizeof(USB_Out_Buffer_END));
            NextUSBOut = sizeof(USB_Out_Buffer_END);
            //CMD_OUTPUT = 0;
        }
    }
}

void command_escape_guard_reset(void)
{
    sof_milli_second = 0;

}

void command_escape_guard(void)
{
    if(sof_milli_second >= 1000)
    {
        sof_milli_second = 0;
        control_console_escape_guard = 1;
    }
}

void command_escape_release(void)
{
    int i;
    control_console_escape_guard = 0;
    command_escape_guard_reset();
    control_console_escape = 0;
}

BOOL command_escape_guard_check(void)
{
    if(control_console_escape_guard == 1)
        return TRUE;
    else
        return FALSE;
}

BOOL command_mode_check(void)
{
    if(control_console_set == 1)
        return TRUE;
    else
        return FALSE;
}

void command_echo(void)
{
    USB_Out_Buffer[0] = RS232_Out_Data[0];
    if(RS232_Out_Data[0] != '\r')
        NextUSBOut = 1;
    else
    {
        memcpy_cmd_prompt(&USB_Out_Buffer[0]);
        NextUSBOut = 3;
    }
}

/********************************************************************
 * Function:        void ProcessIO(void)
 *
 * PreCondition:    None
 *
 * Input:           None
 *
 * Output:          None
 *
 * Side Effects:    None
 *
 * Overview:        This function is a place holder for other user
 *                  routines. It is a mixture of both USB and
 *                  non-USB tasks.
 *
 * Note:            None
 *******************************************************************/


void ProcessIO(void)
{   
    //Blink the LEDs according to the USB device status
#ifndef RN4020
    BlinkUSBStatus();
#endif

    // User Application USB tasks
    if((USBDeviceState < CONFIGURED_STATE)||(USBSuspendControl==1))
    {
        return;
    }

    if (RS232_Out_Data_Rdy == 0)  // only check for new USB buffer if the old RS232 buffer is
    {						  // empty.  This will cause additional USB packets to be NAK'd
        LastRS232Out = getsUSBUSART(RS232_Out_Data,64); //until the buffer is free.
        if(LastRS232Out > 0)
        {
            command_escape_guard_reset();
            RS232_Out_Data_Rdy = 1;  // signal buffer full
            RS232cp = 0;  // Reset the current position
        }
    }

    command_escape_guard();


    //Check if one or more bytes are waiting in the physical UART transmit
    //queue.  If so, send it out the UART TX pin.
    if(RS232_Out_Data_Rdy && mTxRdyUSART())
    {
        #if defined(USB_CDC_SUPPORT_HARDWARE_FLOW_CONTROL)
        //Make sure the receiving UART device is ready to receive data before
        //actually sending it.
        if(UART_CTS == USB_CDC_CTS_ACTIVE_LEVEL)
        {

            if((RS232_Out_Data[RS232cp] == '$') && command_escape_guard_check())
            {
                if(!command_mode_check())
                    putcUSART(RS232_Out_Data[RS232cp]);

                command_escape();                
            }
            else
            {               
                if(!command_mode_check())
                {
                    command_escape_release();
                    putcUSART(RS232_Out_Data[RS232cp]);
                }
                else
                {
                    if(!command_parse())
                    {
                        command_echo();
                    }
                }
            }
            ++RS232cp;
            if (RS232cp == LastRS232Out)
                    RS232_Out_Data_Rdy = 0;
        }
        #else
            //Hardware flow control not being used.  Just send the data.
            putcUSART(RS232_Out_Data[RS232cp]);
            ++RS232cp;
            if (RS232cp == LastRS232Out)
                    RS232_Out_Data_Rdy = 0;
        #endif
    }

    //Check if we received a character over the physical UART, and we need
    //to buffer it up for eventual transmission to the USB host.
    if(mDataRdyUSART() && (NextUSBOut < (CDC_DATA_OUT_EP_SIZE - 1)) && (!command_mode_check()))
    {
        USB_Out_Buffer[NextUSBOut] = getcUSART1();
        ++NextUSBOut;
        USB_Out_Buffer[NextUSBOut] = 0;
    }

    #if defined(USB_CDC_SUPPORT_HARDWARE_FLOW_CONTROL)
    //Drive RTS pin, to let UART device attached know if it is allowed to
    //send more data or not.  If the receive buffer is almost full, we
    //deassert RTS.
    if(NextUSBOut <= (CDC_DATA_OUT_EP_SIZE - 5u))
    {
        UART_RTS = USB_CDC_RTS_ACTIVE_LEVEL;
    }
    else
    {
        UART_RTS = (USB_CDC_RTS_ACTIVE_LEVEL ^ 1);
    }
    #endif	

    //Check if any bytes are waiting in the queue to send to the USB host.
    //If any bytes are waiting, and the endpoint is available, prepare to
    //send the USB packet to the host.
    if((USBUSARTIsTxTrfReady()) && (NextUSBOut > 0))
    {
        putUSBUSART(&USB_Out_Buffer[0], NextUSBOut);
        NextUSBOut = 0;
        command_escape_guard_reset();
    }
		
    CDCTxService();
#ifdef TEST_MODE
    test_mode_process();
#endif
}//end ProcessIO

// ******************************************************************************************************
// ************** USB Callback Functions ****************************************************************
// ******************************************************************************************************
// The USB firmware stack will call the callback functions USBCBxxx() in response to certain USB related
// events.  For example, if the host PC is powering down, it will stop sending out Start of Frame (SOF)
// packets to your device.  In response to this, all USB devices are supposed to decrease their power
// consumption from the USB Vbus to <2.5mA* each.  The USB module detects this condition (which according
// to the USB specifications is 3+ms of no bus activity/SOF packets) and then calls the USBCBSuspend()
// function.  You should modify these callback functions to take appropriate actions for each of these
// conditions.  For example, in the USBCBSuspend(), you may wish to add code that will decrease power
// consumption from Vbus to <2.5mA (such as by clock switching, turning off LEDs, putting the
// microcontroller to sleep, etc.).  Then, in the USBCBWakeFromSuspend() function, you may then wish to
// add code that undoes the power saving things done in the USBCBSuspend() function.

// The USBCBSendResume() function is special, in that the USB stack will not automatically call this
// function.  This function is meant to be called from the application firmware instead.  See the
// additional comments near the function.

// Note *: The "usb_20.pdf" specs indicate 500uA or 2.5mA, depending upon device classification. However,
// the USB-IF has officially issued an ECN (engineering change notice) changing this to 2.5mA for all 
// devices.  Make sure to re-download the latest specifications to get all of the newest ECNs.

/******************************************************************************
 * Function:        void USBCBSuspend(void)
 *
 * PreCondition:    None
 *
 * Input:           None
 *
 * Output:          None
 *
 * Side Effects:    None
 *
 * Overview:        Call back that is invoked when a USB suspend is detected
 *
 * Note:            None
 *****************************************************************************/
void USBCBSuspend(void)
{
	//Example power saving code.  Insert appropriate code here for the desired
	//application behavior.  If the microcontroller will be put to sleep, a
	//process similar to that shown below may be used:
	
	//ConfigureIOPinsForLowPower();
	//SaveStateOfAllInterruptEnableBits();
	//DisableAllInterruptEnableBits();
	//EnableOnlyTheInterruptsWhichWillBeUsedToWakeTheMicro();	//should enable at least USBActivityIF as a wake source
	//Sleep();
	//RestoreStateOfAllPreviouslySavedInterruptEnableBits();	//Preferrably, this should be done in the USBCBWakeFromSuspend() function instead.
	//RestoreIOPinsToNormal();									//Preferrably, this should be done in the USBCBWakeFromSuspend() function instead.

	//IMPORTANT NOTE: Do not clear the USBActivityIF (ACTVIF) bit here.  This bit is 
	//cleared inside the usb_device.c file.  Clearing USBActivityIF here will cause 
	//things to not work as intended.	
	

 
}



/******************************************************************************
 * Function:        void USBCBWakeFromSuspend(void)
 *
 * PreCondition:    None
 *
 * Input:           None
 *
 * Output:          None
 *
 * Side Effects:    None
 *
 * Overview:        The host may put USB peripheral devices in low power
 *					suspend mode (by "sending" 3+ms of idle).  Once in suspend
 *					mode, the host may wake the device back up by sending non-
 *					idle state signalling.
 *					
 *					This call back is invoked when a wakeup from USB suspend 
 *					is detected.
 *
 * Note:            None
 *****************************************************************************/
void USBCBWakeFromSuspend(void)
{
	// If clock switching or other power savings measures were taken when
	// executing the USBCBSuspend() function, now would be a good time to
	// switch back to normal full power run mode conditions.  The host allows
	// 10+ milliseconds of wakeup time, after which the device must be 
	// fully back to normal, and capable of receiving and processing USB
	// packets.  In order to do this, the USB module must receive proper
	// clocking (IE: 48MHz clock must be available to SIE for full speed USB
	// operation).  
	// Make sure the selected oscillator settings are consistent with USB 
    // operation before returning from this function.
}

/********************************************************************
 * Function:        void USBCB_SOF_Handler(void)
 *
 * PreCondition:    None
 *
 * Input:           None
 *
 * Output:          None
 *
 * Side Effects:    None
 *
 * Overview:        The USB host sends out a SOF packet to full-speed
 *                  devices every 1 ms. This interrupt may be useful
 *                  for isochronous pipes. End designers should
 *                  implement callback routine as necessary.
 *
 * Note:            None
 *******************************************************************/
void USBCB_SOF_Handler(void)
{
    // No need to clear UIRbits.SOFIF to 0 here.
    // Callback caller is already doing that.
    sof_milli_second = sof_milli_second + 1;
#ifdef TEST_MODE
    sof_milli_second_test = sof_milli_second_test + 1;
#endif
}

/*******************************************************************
 * Function:        void USBCBErrorHandler(void)
 *
 * PreCondition:    None
 *
 * Input:           None
 *
 * Output:          None
 *
 * Side Effects:    None
 *
 * Overview:        The purpose of this callback is mainly for
 *                  debugging during development. Check UEIR to see
 *                  which error causes the interrupt.
 *
 * Note:            None
 *******************************************************************/
void USBCBErrorHandler(void)
{
    // No need to clear UEIR to 0 here.
    // Callback caller is already doing that.

	// Typically, user firmware does not need to do anything special
	// if a USB error occurs.  For example, if the host sends an OUT
	// packet to your device, but the packet gets corrupted (ex:
	// because of a bad connection, or the user unplugs the
	// USB cable during the transmission) this will typically set
	// one or more USB error interrupt flags.  Nothing specific
	// needs to be done however, since the SIE will automatically
	// send a "NAK" packet to the host.  In response to this, the
	// host will normally retry to send the packet again, and no
	// data loss occurs.  The system will typically recover
	// automatically, without the need for application firmware
	// intervention.
	
	// Nevertheless, this callback function is provided, such as
	// for debugging purposes.
}


/*******************************************************************
 * Function:        void USBCBCheckOtherReq(void)
 *
 * PreCondition:    None
 *
 * Input:           None
 *
 * Output:          None
 *
 * Side Effects:    None
 *
 * Overview:        When SETUP packets arrive from the host, some
 * 					firmware must process the request and respond
 *					appropriately to fulfill the request.  Some of
 *					the SETUP packets will be for standard
 *					USB "chapter 9" (as in, fulfilling chapter 9 of
 *					the official USB specifications) requests, while
 *					others may be specific to the USB device class
 *					that is being implemented.  For example, a HID
 *					class device needs to be able to respond to
 *					"GET REPORT" type of requests.  This
 *					is not a standard USB chapter 9 request, and 
 *					therefore not handled by usb_device.c.  Instead
 *					this request should be handled by class specific 
 *					firmware, such as that contained in usb_function_hid.c.
 *
 * Note:            None
 *******************************************************************/
void USBCBCheckOtherReq(void)
{
    USBCheckCDCRequest();
}//end


/*******************************************************************
 * Function:        void USBCBStdSetDscHandler(void)
 *
 * PreCondition:    None
 *
 * Input:           None
 *
 * Output:          None
 *
 * Side Effects:    None
 *
 * Overview:        The USBCBStdSetDscHandler() callback function is
 *					called when a SETUP, bRequest: SET_DESCRIPTOR request
 *					arrives.  Typically SET_DESCRIPTOR requests are
 *					not used in most applications, and it is
 *					optional to support this type of request.
 *
 * Note:            None
 *******************************************************************/
void USBCBStdSetDscHandler(void)
{
    // Must claim session ownership if supporting this request
}//end


/*******************************************************************
 * Function:        void USBCBInitEP(void)
 *
 * PreCondition:    None
 *
 * Input:           None
 *
 * Output:          None
 *
 * Side Effects:    None
 *
 * Overview:        This function is called when the device becomes
 *                  initialized, which occurs after the host sends a
 * 					SET_CONFIGURATION (wValue not = 0) request.  This 
 *					callback function should initialize the endpoints 
 *					for the device's usage according to the current 
 *					configuration.
 *
 * Note:            None
 *******************************************************************/
void USBCBInitEP(void)
{
    //Enable the CDC data endpoints
    CDCInitEP();
}

/********************************************************************
 * Function:        void USBCBSendResume(void)
 *
 * PreCondition:    None
 *
 * Input:           None
 *
 * Output:          None
 *
 * Side Effects:    None
 *
 * Overview:        The USB specifications allow some types of USB
 * 					peripheral devices to wake up a host PC (such
 *					as if it is in a low power suspend to RAM state).
 *					This can be a very useful feature in some
 *					USB applications, such as an Infrared remote
 *					control	receiver.  If a user presses the "power"
 *					button on a remote control, it is nice that the
 *					IR receiver can detect this signalling, and then
 *					send a USB "command" to the PC to wake up.
 *					
 *					The USBCBSendResume() "callback" function is used
 *					to send this special USB signalling which wakes 
 *					up the PC.  This function may be called by
 *					application firmware to wake up the PC.  This
 *					function will only be able to wake up the host if
 *                  all of the below are true:
 *					
 *					1.  The USB driver used on the host PC supports
 *						the remote wakeup capability.
 *					2.  The USB configuration descriptor indicates
 *						the device is remote wakeup capable in the
 *						bmAttributes field.
 *					3.  The USB host PC is currently sleeping,
 *						and has previously sent your device a SET 
 *						FEATURE setup packet which "armed" the
 *						remote wakeup capability.   
 *
 *                  If the host has not armed the device to perform remote wakeup,
 *                  then this function will return without actually performing a
 *                  remote wakeup sequence.  This is the required behavior, 
 *                  as a USB device that has not been armed to perform remote 
 *                  wakeup must not drive remote wakeup signalling onto the bus;
 *                  doing so will cause USB compliance testing failure.
 *                  
 *					This callback should send a RESUME signal that
 *                  has the period of 1-15ms.
 *
 * Note:            This function does nothing and returns quickly, if the USB
 *                  bus and host are not in a suspended condition, or are 
 *                  otherwise not in a remote wakeup ready state.  Therefore, it
 *                  is safe to optionally call this function regularly, ex: 
 *                  anytime application stimulus occurs, as the function will
 *                  have no effect, until the bus really is in a state ready
 *                  to accept remote wakeup. 
 *
 *                  When this function executes, it may perform clock switching,
 *                  depending upon the application specific code in 
 *                  USBCBWakeFromSuspend().  This is needed, since the USB
 *                  bus will no longer be suspended by the time this function
 *                  returns.  Therefore, the USB module will need to be ready
 *                  to receive traffic from the host.
 *
 *                  The modifiable section in this routine may be changed
 *                  to meet the application needs. Current implementation
 *                  temporary blocks other functions from executing for a
 *                  period of ~3-15 ms depending on the core frequency.
 *
 *                  According to USB 2.0 specification section 7.1.7.7,
 *                  "The remote wakeup device must hold the resume signaling
 *                  for at least 1 ms but for no more than 15 ms."
 *                  The idea here is to use a delay counter loop, using a
 *                  common value that would work over a wide range of core
 *                  frequencies.
 *                  That value selected is 1800. See table below:
 *                  ==========================================================
 *                  Core Freq(MHz)      MIP         RESUME Signal Period (ms)
 *                  ==========================================================
 *                      48              12          1.05
 *                       4              1           12.6
 *                  ==========================================================
 *                  * These timing could be incorrect when using code
 *                    optimization or extended instruction mode,
 *                    or when having other interrupts enabled.
 *                    Make sure to verify using the MPLAB SIM's Stopwatch
 *                    and verify the actual signal on an oscilloscope.
 *******************************************************************/
void USBCBSendResume(void)
{
    static WORD delay_count;
    
    //First verify that the host has armed us to perform remote wakeup.
    //It does this by sending a SET_FEATURE request to enable remote wakeup,
    //usually just before the host goes to standby mode (note: it will only
    //send this SET_FEATURE request if the configuration descriptor declares
    //the device as remote wakeup capable, AND, if the feature is enabled
    //on the host (ex: on Windows based hosts, in the device manager 
    //properties page for the USB device, power management tab, the 
    //"Allow this device to bring the computer out of standby." checkbox 
    //should be checked).
    if(USBGetRemoteWakeupStatus() == TRUE) 
    {
        //Verify that the USB bus is in fact suspended, before we send
        //remote wakeup signalling.
        if(USBIsBusSuspended() == TRUE)
        {
            USBMaskInterrupts();
            
            //Clock switch to settings consistent with normal USB operation.
            USBCBWakeFromSuspend();
            USBSuspendControl = 0; 
            USBBusIsSuspended = FALSE;  //So we don't execute this code again, 
                                        //until a new suspend condition is detected.

            //Section 7.1.7.7 of the USB 2.0 specifications indicates a USB
            //device must continuously see 5ms+ of idle on the bus, before it sends
            //remote wakeup signalling.  One way to be certain that this parameter
            //gets met, is to add a 2ms+ blocking delay here (2ms plus at 
            //least 3ms from bus idle to USBIsBusSuspended() == TRUE, yeilds
            //5ms+ total delay since start of idle).
            delay_count = 3600U;        
            do
            {
                delay_count--;
            }while(delay_count);
            
            //Now drive the resume K-state signalling onto the USB bus.
            USBResumeControl = 1;       // Start RESUME signaling
            delay_count = 1800U;        // Set RESUME line for 1-13 ms
            do
            {
                delay_count--;
            }while(delay_count);
            USBResumeControl = 0;       //Finished driving resume signalling

            USBUnmaskInterrupts();
        }
    }
}


/*******************************************************************
 * Function:        void USBCBEP0DataReceived(void)
 *
 * PreCondition:    ENABLE_EP0_DATA_RECEIVED_CALLBACK must be
 *                  defined already (in usb_config.h)
 *
 * Input:           None
 *
 * Output:          None
 *
 * Side Effects:    None
 *
 * Overview:        This function is called whenever a EP0 data
 *                  packet is received.  This gives the user (and
 *                  thus the various class examples a way to get
 *                  data that is received via the control endpoint.
 *                  This function needs to be used in conjunction
 *                  with the USBCBCheckOtherReq() function since 
 *                  the USBCBCheckOtherReq() function is the apps
 *                  method for getting the initial control transfer
 *                  before the data arrives.
 *
 * Note:            None
 *******************************************************************/
#if defined(ENABLE_EP0_DATA_RECEIVED_CALLBACK)
void USBCBEP0DataReceived(void)
{
}
#endif

/*******************************************************************
 * Function:        BOOL USER_USB_CALLBACK_EVENT_HANDLER(
 *                        USB_EVENT event, void *pdata, WORD size)
 *
 * PreCondition:    None
 *
 * Input:           USB_EVENT event - the type of event
 *                  void *pdata - pointer to the event data
 *                  WORD size - size of the event data
 *
 * Output:          None
 *
 * Side Effects:    None
 *
 * Overview:        This function is called from the USB stack to
 *                  notify a user application that a USB event
 *                  occured.  This callback is in interrupt context
 *                  when the USB_INTERRUPT option is selected.
 *
 * Note:            None
 *******************************************************************/
BOOL USER_USB_CALLBACK_EVENT_HANDLER(int event, void *pdata, WORD size)
{
    switch(event)
    {
        case EVENT_TRANSFER:
            //Add application specific callback task or callback function here if desired.
            break;
        case EVENT_SOF:
            USBCB_SOF_Handler();
            break;
        case EVENT_SUSPEND:
            USBCBSuspend();
            break;
        case EVENT_RESUME:
            USBCBWakeFromSuspend();
            break;
        case EVENT_CONFIGURED: 
            USBCBInitEP();
            break;
        case EVENT_SET_DESCRIPTOR:
            USBCBStdSetDscHandler();
            break;
        case EVENT_EP0_REQUEST:
            USBCBCheckOtherReq();
            break;
        case EVENT_BUS_ERROR:
            USBCBErrorHandler();
            break;
        case EVENT_TRANSFER_TERMINATED:
            //Add application specific callback task or callback function here if desired.
            //The EVENT_TRANSFER_TERMINATED event occurs when the host performs a CLEAR
            //FEATURE (endpoint halt) request on an application endpoint which was 
            //previously armed (UOWN was = 1).  Here would be a good place to:
            //1.  Determine which endpoint the transaction that just got terminated was 
            //      on, by checking the handle value in the *pdata.
            //2.  Re-arm the endpoint if desired (typically would be the case for OUT 
            //      endpoints).
            break;
        default:
            break;
    }      
    return TRUE; 
}


/** RN4020 PICTAIL: UTILITY FUNCTIONS ***********************************************/
unsigned char get_hex_byte(char * str, unsigned char * val)
{
	unsigned char x,y,z;
	z=0;

	for (x=0;x<2;x++)
	{
		y = str[x];//toupper(str[x]);
		z = z << 4;
		if ( (y >= '0') && (y <= '9') )
			z+= y -48;
		else
			if ( (y >= 'A') && (y <= 'F') )
				z+= y -55;
			else
				return 0;
        }

	*val=z;
	return 1;

}

unsigned char get_hex(char * str, unsigned short int * val)
{
	unsigned char x,y;
	unsigned short int z=0;

	for (x=0;x<3;x+=2)
	{
		if ( ! get_hex_byte(&str[x],&y)  )
			return 0;
		z= (z << 8) + y;
	}

	*val=z;
	return 1;

}

unsigned char get_hex_24bit(char * str, unsigned long int * val)
{
	unsigned char x,y;
	unsigned long int z=0;

	for (x=0;x<5;x+=2)
	{
		if ( ! get_hex_byte(&str[x],&y)  )
			return 0;
		z= (z << 8) + y;
	}

	*val=z;
	return 1;

}

unsigned char get_hex_dword(char * str, unsigned long int * val)
{
	unsigned char x,y;
	unsigned long int z=0;

	for (x=0;x<7;x+=2)
	{
		if ( ! get_hex_byte(&str[x],&y)  )
			return 0;
		z= (z << 8) + y;
	}

	*val=z;
	return 1;

}

void format_hex_byte(char * str, unsigned char val)
{
    unsigned char x,y;

    for (x=0;x<2;x++)
    {
        y = val & 0xf;
        if ( y > 9 )
            str[1-x] = y + 55;
        else
            str[1-x] = y + 48;

        val = val >> 4;
    }
    str[2]=0;
}

void format_hex_byte2(char * str, unsigned char val)
{
    unsigned char x,y;

    for (x=0;x<2;x++)
    {
        y = val & 0xf;
        if ( y > 9 )
            str[1-x] = y + 55;
        else
            str[1-x] = y + 48;

        val = val >> 4;
    }
}

void format_hex(char * str, unsigned short int val)
{
    unsigned char x,y;

    for (x=0;x<4;x++)
    {
        y = val & 0xf;
        if ( y > 9 )
            str[3-x] =y +55;
        else
            str[3-x] =y +48;

        val = val >> 4;
    }
    str[4]=0;
}

void format_hex_24bit(char * str, unsigned long int val)
{
    unsigned char x,y;

    for (x=0;x<6;x++)
    {
        y = val & 0xf;
        if ( y > 9 )
            str[5-x] =y +55;
        else
            str[5-x] =y +48;

        val = val >> 4;
    }
    str[6]=0;
}

void format_hex_dword(char * str, unsigned long int val)
{
    unsigned char x,y;

    for (x=0;x<8;x++)
    {
        y = val & 0xf;
        if ( y > 9 )
            str[7-x] =y +55;
        else
            str[7-x] =y +48;

        val = val >> 4;
    }
    str[8]=0;
}

/** EOF main.c *************************************************/
