/* usb test for communications between host and device
designed by takefuji on Dec.27, 2007 */

#include <avr/io.h>
#include <avr/wdt.h>
#include <avr/eeprom.h>
#include <avr/interrupt.h>
#include <avr/pgmspace.h>
#include <util/delay.h>
#include "usbdrv.h"
#include "oddebug.h"
#define FOSC F_CPU
#define BAUD 9600
#define UBRR FOSC/16/BAUD-1
#define UART_BUFMAX 50
unsigned char rxbuf[UART_BUFMAX];
unsigned char txbuf[UART_BUFMAX];
unsigned char rxpointer;
unsigned char txpointer;

ISR(USART_RX_vect)
{unsigned char c=UDR0;
rxbuf[rxpointer]=c;
rxpointer++;
}

void send_1byte(unsigned char c)
{
loop_until_bit_is_set(UCSR0A, UDRE0); 
UDR0=c;
}


uchar usbFunctionSetup(uchar data[8])
{
static uchar replybuf[50];	
usbMsgPtr = replybuf;
unsigned char c=data[1];
int i;

if(c=='R'){
	for(i=0;i<rxpointer;i++){
	replybuf[i]=rxbuf[i];}
	i=rxpointer; 
	rxpointer=0;
	return i;}
else if(c=='S'){ for(i=0;i<txpointer;i++)
		{send_1byte(txbuf[i]);}
		txpointer=0;
		return 0;}
else{txbuf[txpointer]=c;txpointer++;}
return 0;
}


int main(void)
{
UBRR0H=UBRR>>8;
UBRR0L=UBRR;
UCSR0A=0<<U2X0;
UCSR0B = (1<<RXEN0)|(1<<TXEN0)|(1<<RXCIE0); 
UCSR0C = (0<<UMSEL00)|(3<<UCSZ00)|(1<<USBS0)|(0<<UPM00); 
rxpointer=0;txpointer=0;

    usbInit();
    sei();
    for(;;){    /* main event loop */
        usbPoll();
        }
    return 0;
}

