/**
 * \file
 *
 * \brief Empty user application template
 *
 */

/**
 * \mainpage User Application template doxygen documentation
 *
 * \par Empty user application template
 *
 * Bare minimum empty user application template
 *
 * \par Content
 *
 * -# Include the ASF header files (through asf.h)
 * -# Minimal main function that starts with a call to board_init()
 * -# "Insert application code here" comment
 *
 */

/*
 * Include header files for all drivers that have been imported from
 * Atmel Software Framework (ASF).
 */
#include <asf.h>
#include <delay.h>
#include <avr32/io.h>
#include <string.h>
#include "init_1.h"
#include "drawqr.h"
#include "qr.h"
#include "pm.h"
#include "usart.h"
#include "intc.h"


void main_init (void);

int usart_get_line(char* p, int maxLen);

volatile struct avr32_usart_t *usart = &AVR32_USART1;

int usart_get_line(char* p, int maxLen)
{
	int c;
	int Len = 0;
	int rv;
	while(Len+2 < maxLen)
	{
		rv = usart_read_char(&AVR32_USART1, &c);
		if(rv == USART_RX_EMPTY)
		 continue;
		if(rv == USART_RX_ERROR)
		{
		 continue;
		}
		if(c == 0x0D) break;
		p[Len] = c;
		Len++;
	}
	p[Len] = 0;
	return(Len);
}

void main_init (void)
{
	board_init();
	AVR32_GPIO.port[0].gpers = 1 << PIN_PWR;
	AVR32_GPIO.port[0].oders = 1 << PIN_PWR;
	CLR_PIN(PIN_PWR);
	delay1(100);
	lcdInit();
	SET_PIN(PIN_PWR);
	delay1(100);
	lcdOn();
	delay1(100);	
}

int main (void)
{
	pm_switch_to_osc0(&AVR32_PM, BOARD_OSC0_HZ, BOARD_OSC0_STARTUP_US);
	
	// sysclk_init();
	sysclk_enable_peripheral_clock(usart);
	
	static const gpio_map_t USART_GPIO_MAP =
	{
		{AVR32_USART1_RXD_0_0_PIN, AVR32_USART1_RXD_0_0_FUNCTION}
	};
	
	static const usart_options_t opt = 
	{
	.baudrate = 57600,
	.charlength = 8,
	.paritytype = USART_NO_PARITY,
	.stopbits = USART_1_STOPBIT,
	.channelmode = USART_NORMAL_CHMODE
	};
	
	AVR32_GPIO.port[0].gpers = 1 << 24;
	AVR32_GPIO.port[0].oderc = 1 << 24;
	gpio_enable_module(USART_GPIO_MAP, sizeof(USART_GPIO_MAP) / sizeof(USART_GPIO_MAP[0]));
	
	usart_init_rs232(usart, &opt, BOARD_OSC0_HZ);

    strcpy(QRCODE_TEXT, "Tomas Lakomy");
	main_init();	
    clearScreen();
    qr();
	for(;;)
	{
	  usart_get_line(QRCODE_TEXT, sizeof(QRCODE_TEXT));
	  clearScreen();
      qr();		
    }
}

