 
//----- Include Files ---------------------------------------------------------
#include <avr/io.h>		// include I/O definitions (port names, pin names, etc)
#include <avr/interrupt.h>	// include interrupt support
#include <stdlib.h>

#include "avrlib/conf/global.h"		// include our global settings
#include "avrlib/uart2.h"		// include dual-uart function library
#include "avrlib/rprintf.h"	// include printf function library
#include "avrlib/timer.h"		// include timer function library (timing, PWM, etc)
#include "avrlib/gps.h"		// include gps data support
#include "avrlib/nmea.h"		// include NMEA gps packet handling
#include "avrlib/a2d.h"		

#include <util/delay.h> //cekaci smycka v ms



// uartRxOverflow je globalni promena definovana v uart.c/uart2.c
extern unsigned short uartRxOverflow[2];



/// definice HW

#define LED1On()	PORTA|=128;
#define LED2On()	PORTA|=64;
#define LED3On()	PORTA|=32;
#define LED4On()	PORTA|=16;

#define LED1Off()	PORTA&=~128;
#define LED2Off()	PORTA&=~64;
#define LED3Off()	PORTA&=~32;
#define LED4Off()	PORTA&=~16;

#define GPS_reset()	PORTD&=~1;
#define GPS_release()	PORTD|=1;

#define MT_Status()	(PINC&1)


void gpsNmeaInit(void)
{
	// nastaveni rychlosti pro UART1 NMEA
	uartSetBaudRate(1,4800);

	// inicializace GPS knihovny
	gpsInit();
	// inicializace GPS paketoveho dekoderu
	nmeaInit();

}

void gpsNmeaLoop(void) {
		// prijem paketu GPS do bufferu
		while( nmeaProcess(uartGetRxBuffer(1)) );

		//pokud prijimame TOF, blikame LED2
		if ((long int)(gpsGetInfo()->PosLLA.TimeOfFix.f)%2<1) {
			LED2On();
		} else {
			LED2Off();
		}
}


//pocatecni nastaveni portu

void initPorts() {
	PORTA = 0x00;
	DDRA = 0xFF;

	PORTB = 0x3F;
	DDRB = 0xC0;

	PORTC = 0x00;
	DDRC = 0x02;

	PORTD = 0x03;
	DDRD = 0x02;

	PORTE = 0x00;
	DDRE = 0x00;

	PORTF = 0x00;
	DDRC = 0x00;

	GPS_reset();
	for (unsigned int i=0;i<50000;i++) asm("nop");
	GPS_release();

}


void MTPrepareAT(void) {
	//mazani bufferu prijatych dat
	while (uart0GetByte()>=0) ;
}

// prikaz AT pro overeni GSM casti zdali zije
void MTSendATCommand(void) {
	rprintf("AT\r\n");
}

unsigned char MTgetResponse(void) {
	unsigned char timeout = 255;
	do {
		delay_ms(10);
	} while (timeout-- && uart0GetByte()==-1);
	return (timeout>0);
}

//inicializace mobilu po zapnuti
void MTinitAll(void) {
	MTPrepareAT();
	rprintf("AT+CMGF=1\r\n"); //nastaví text na sms místo PDU
	_delay_ms(300);
}
//start poslani sms, zada cislo
void MTinitSMSSending(void) {
	MTPrepareAT();
	rprintf("AT+CMGS=\"+420608479629\"\r\n");
	delay_ms(1500);	
}

//zakonci sms zpravu a odesle
void MTfinishSMSSending(void) {
	MTPrepareAT();
	rprintf("\r\nKonec dat\x1A");
	delay_ms(1000);
}

// test komunikace s GSM zdali zapnut
int MTtestCommunication(void) {
	MTPrepareAT();
	MTSendATCommand();
	unsigned char result = MTgetResponse(); //prirazeni odpovedel, neodpovedel
	delay_ms(300);
	return result;
}

//zapnuti GSM casti
#define MT_wakeOn()			PORTD&=~2;
#define MT_wakeOff()		PORTD|=2;




// tvorba popisku osy
void rprintfResNo(unsigned char no) {
		rprintfFloat(3, '+', (aresult[no]-512)/19.0);
		rprintf(" (");
		rprintfFloat(3,  '+', (amin[no]-512)/19.0);
		rprintf("..");
		rprintfFloat(3, '+', (amax[no]-512)/19.0);
		rprintf(")");
}

//slozeni sms z os a dalsich informaci
void describeSituation() {
		rprintf("Poplach dopravni nehoda!");
		rprintf("\rX:");
		rprintfResNo(1);
		rprintf("\rY:");
		rprintfResNo(0);
		rprintf("\rZ:");;
		rprintfResNo(2);
		rprintf("\r\n");
		
		rprintfProgStrM("Zemepisna sirka:   ");		rprintfFloat(8, '+', 180*(gpsGetInfo()->PosLLA.lat.f/PI));	
		rprintfProgStrM(", Zemepisna delka:   ");	rprintfFloat(8, '+', 180*(gpsGetInfo()->PosLLA.lon.f/PI));
		rprintfProgStrM(",");
		rprintf("\r");		
		rprintfProgStrM("Cas UTC:   "); 	rprintfFloat(9, ' ', gpsGetInfo()->PosLLA.TimeOfFix.f);
				
}


int main(void)
{
initPorts();


	
	// inicializace UART
	uartInit();
	//nastaveni rychlosti pro UART0 GSM
	uartSetBaudRate(0,38400);
	// nastaveni rprintfInit, aby odeslala vzdy na UART0
	rprintfInit(uart0SendByte);
	// inicializace casovacu
	timerInit();

	LED4On();

	unsigned char pocetznaku;

	do {
		pocetznaku = 0;

		MTPrepareAT();
		MTSendATCommand();
		
		delay_ms(500);
		
		int x;
		while ((x=uart0GetByte())>0) {
			LED3On();
			_delay_ms(30);
			LED3Off();
			_delay_ms(30);
			pocetznaku ++;
		}
		LED3Off();

		if (pocetznaku<3) {
			//pokus o zapnuti mobilu
			MT_wakeOn();
			LED1On();
			_delay_ms(2200);
			MT_wakeOff();
			LED1Off();
			_delay_ms(4000);
		}
	} while (pocetznaku<3 && !MT_Status());

	LED1On();

	
	// inicalizace prevodniku
	
	a2dInit();
	a2dConvert10bit(0);

	// inicializace GPS
	gpsNmeaInit();

	LED4Off();

	//hlavni smycka vyhodnocovani

	while (1) {
		
		if (aresult[1]>512) LED3On() else LED3Off();
		
		if (bylNaraz) {
			//if (bylNaraz==1) rprintf("NARAZ (%d)\r\n",bylNaraz); //pro kontrolu terminalem
			bylNaraz++;
			if (bylNaraz==51) {
				//5 sec sber dat hotov
				//vyslani 			
				MTinitAll();
				MTinitSMSSending();
				describeSituation(); //vytvori sms
				MTfinishSMSSending();
				bylNaraz = 0; //znovuobnoveni pokud trva tak posila
			}
			LED4On();
		} else {
			LED4Off();
		}

		
		gpsNmeaLoop();
	
		_delay_ms(100);
		
	}

	
	return 0;
}

