#include "usart.h"
/*
 * usart.c
 *
 * Created: 10.4.2012 13:36:11
 *  Author: Kain
 *
 *  2 stop bity, licha parita, 1200
 */
volatile uint8_t USART_rxbuffer[USART_RXBUFLEN];
volatile uint8_t USART_novaDataVBufferu = 0;
volatile uint8_t USART_syncReceived = 0;
volatile uint8_t USART_rxcounter = 0;

void USART_init(void)
{
  // Setup the UART baud rate
  UBRRH = (BAUD_RATE_UBRR >> 8);
  UBRRL = (0xff&BAUD_RATE_UBRR);

  // Enable the UART receiver and transceiver
  UCSRB = _BV(RXEN) | _BV(TXEN);
  // Set the frame format : 8 bits data, 2 bit stop, odd parity
  UCSRC = ((1<<URSEL)|_BV(UCSZ1) | _BV(UCSZ0) | (1<<UPM1) | (1<<UPM0) | (1<<USBS));

  // RX interrupt
  UCSRB |= (1<<RXCIE);
}

/* V obsluze preruseni ukladame bajt po bajtu do zasobniku.
 * adresa, data, CRC7 = 3B
 */
ISR(USART_RXC_vect)  {
	char c;
	/************************************************************************
	 * Chybove stavy USART portu - jedna se pouze o osetreni "chyb" které
	 * prichazi na port ve forme ruseni kdyz prijimaci modul zrovna nic neprijima
	 * a pouze zesiluje ruseni ve vzduchu.
	 */
	if(UCSRA & 1<<DOR) {
		// Data overrun, vycistit UDR a shift reg
		c = UDR;
		c = UDR;
		USART_rxcounter = 0;
		USART_syncReceived = 0;
		return;
	}
	if(UCSRA & 1<<PE) {
		// Parity error
		USART_rxcounter = 0;
		USART_syncReceived = 0;
		return;
	}
	if(UCSRA & 1<<FE) {
		// Frame error - stop bit je 0, ma byt 1
		USART_rxcounter = 0;
		USART_syncReceived = 0;
		return;
	}
	/************************************************************************/
	c = UDR;    // Prijaty bajt
	if(c == RF_SYNCMARK) {
		// Jedna se o synchronizacni znacku - muzeme povolit prijem dalsich bytu
		USART_rxcounter = 0;
		USART_syncReceived = 1;
	}
	if(USART_syncReceived == 0) {
		// Sync ramec jeste nebyl prijat, takze prichozi data jeste nejsou validni
		return;
	}

	USART_rxbuffer[USART_rxcounter] = c;    // Ulozeni bajtu do bufferu

	if(USART_rxcounter < USART_RXBUFLEN-1) {
	    USART_rxcounter ++;
	} else {
		// Dosli jsme na konec RX bufferu = mame prijaty komplet ramec vcetne CRC
		USART_rxcounter = 0;
		USART_novaDataVBufferu = 1;
		USART_syncReceived = 0;
	}
}
