/*
 * UC864G.c
 *
 * Created: 15.5.2012 18:04:48
 *  Author: Tomas
 */ 


#include "avr\io.h" 		// definiční soubor pro mikrokontrolér
#include "avr\interrupt.h"	// přerušení mikrokontroléru
#include "util\delay.h"
#include <string.h>

typedef struct
{
  unsigned int bit0:1;
  unsigned int bit1:1;
  unsigned int bit2:1;
  unsigned int bit3:1;
  unsigned int bit4:1;
  unsigned int bit5:1;
  unsigned int bit6:1;
  unsigned int bit7:1;
} _io_reg; 

#define REG_BIT(rg,bt) ((volatile _io_reg*)&rg)->bit##bt

#define SW1 REG_BIT(PIND, 4)
#define SW2 REG_BIT(PIND, 3)
#define SW3 REG_BIT(PIND, 2)
#define MCU_ON REG_BIT(PIND, 7)4
#define LED_REDr REG_BIT(PIND, 6)
#define LED_YELr REG_BIT(PIND, 5)

#define LED_RED REG_BIT(PORTD, 6)
#define LED_YEL REG_BIT(PORTD, 5)

#define InputBuffSize 300

void sendc(char byte);
void sends(char *msg, int N);

char InputBuff[InputBuffSize] = {0};	//vstupni buffer UART
int IBI = 0;		//index ukazujici na pozici v bufferu
short AtReady = 1;	

ISR(PCINT2_vect)
{
	if (SW1 == 0)
	{
		_delay_ms(10);
		if (SW1 == 0)
		{
			sends("ATD4603\r", 0);
		}
	}
	if (SW2 == 0)
	{
		_delay_ms(10);
		if (SW2 == 0)
		{
			sends("AT+CHUP\r", 0);
		}
	}
}

SIGNAL(SIG_USART_RECV)
{
	char rx_data = UDR0;
	if (IBI >= InputBuffSize) reti();	//konec pokud je plny buffer
	InputBuff[IBI++] = rx_data;
	if (InputBuff[IBI-4]=='O' && InputBuff[IBI-3]=='K' && InputBuff[IBI-2]=='\r' && InputBuff[IBI-1]=='\n')	//hleda "OK\r\n"
	{
		IBI=0;
		if (InputBuff[20] == '1') LED_YEL = 1;	//kontrola registrace modulu
	}
}


int main(void)
{
	DDRD =  0b01100010;
	PORTD = 0b10011100;

	PCICR = 0b00000100;	
	PCMSK2 = 0b10011100;

	UBRR0H = 0;	//115,2 kbit/s 8N1
	UBRR0L = 12;
	UCSR0A = 0b00000010;
	UCSR0C = 0b00000110;
	UCSR0B = 0b10011000;
	
	sei();		//povolit preruseni

	_delay_ms(250);

	sends("AT#GPIO=5,0,2\r", 0);	//nastavy LED RFTXMON
	_delay_ms(500);
	sends("AT+FCLASS=8\r", 0);		//hlasovy rezim hovoru
	_delay_ms(500);
	sends("AT+CLVL=10\r",0);		//vystupni hlasitost
	_delay_ms(500);
	sends("AT+CREG?\r",0);			//kontrola registrace site

    while(1)
    {

    }
}

void sendc(char byte)		//odesle char
{
	while(!( UCSR0A & (1<<UDRE0))) {}
	UDR0 = byte;
}

void sends(char *msg, int N)	//odesle string
{
	if (N==0) N = strlen(msg);
	for(int i=0; i<N;i++) sendc(msg[i]);
}
