/*
   Copyright (c) 2012 - David Pello

   Permission is hereby granted, free of charge, to any person obtaining a copy
   of this software and associated documentation files (the "Software"), to deal
   in the Software without restriction, including without limitation the rights
   to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
   copies of the Software, and to permit persons to whom the Software is
   furnished to do so, subject to the following conditions:

   The above copyright notice and this permission notice shall be included in
   all copies or substantial portions of the Software.

   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
   IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
   AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
   OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
   THE SOFTWARE.

 */

#include <inttypes.h>
#include <stdlib.h>
#include <msp430g2553.h>

#include "utils.h"
#include "uart.h"
#include "rtty.h"
#include "adc.h"
#include "i2c_sw.h"
#include "bmp085.h"
#include "parse_nmea.h"
#include "gprs.h"

#define BUFFER_SIZE 80

char nmeatemp[BUFFER_SIZE];
int tempcounter = 0;
char nmea[BUFFER_SIZE] = "XXXXX";
int adc_value;
float external_temperature, internal_temperature;
long bmp085_pressure, bmp085_temperature;
int gps_error;
int cycles_counter;
nmea_data_t nmea_data;

#define NUM_CYCLES 30
#define ID "\nHAB-SOM1\n"

int main(void) {

	WDTCTL = WDTPW + WDTHOLD;	/* Stop WDT */

	BCSCTL1 = CALBC1_1MHZ;          /* Set range */
	DCOCTL = CALDCO_1MHZ;
	BCSCTL2 = 0;                    /* MCLK=DCOCLK, No div, SMCLK=DCOCLK, No div, Internal resistor. */

	/* init memory for nmea data */
	nmea_data = (nmea_data_t)malloc(sizeof(struct nmea_data_struct));

	/* led direction */
	P1DIR |= BIT0;
	blink_led();

	/* GPRS "on" signal */
	P2DIR |= BIT3;


	/* initialize usart in serial mode */
	serial_init();

	_delay_ms(2000);
	//gprs_test_call(GPRS_NUMBER);
	//gprs_send_sms(GPRS_NUMBER, "GPRS System OK");

	WRITE_SR(GIE);	//Enable global interrupts

	/* set pins for rtty */
	rtty_init();

	/* calibrate pressure sensor */
	bmp085_calibration();

	/* start */
	cycles_counter = 0;

	for(;;)
	{

		/* get temperature */
		adc_value=adc_read(INCH_5); /* Read from adc channel 4 */
		/* convert to temperature.
		   We got a 3.3 VCC, so (3.3/1024) * adc_value = volts.
		   LM35 output is 10mV/ºC so volts/0.01 = ºC
		 */
		external_temperature = (3.3*(float)adc_value*100)/1024.0;

		bmp085_pressure = bmp085_read_pressure();
		bmp085_temperature = bmp085_read_temperature();

		_delay_ms(3000);
		rtty_txstring(ID);

		/* parse gps data */
		gps_error = parse_nmea(nmea_data, nmea);

		if (!gps_error) {
			rtty_txstring(nmea_data->latitude);
			rtty_txbyte(' ');
			rtty_txstring(nmea_data->ns);
			rtty_txbyte(',');
			rtty_txstring(nmea_data->longitude);
			rtty_txbyte(' ');
			rtty_txstring(nmea_data->ew);
			rtty_txbyte(',');
			rtty_txstring(nmea_data->altitude);

			rtty_txstring("\n");
		}
		else
		{
			//rtty_txstring("GPS Data invalid\n");
			rtty_txstring(nmea);
			rtty_txstring("\n");
		}	
		/* external temperature */
		rtty_send_temperature(external_temperature);
		rtty_txstring("\n");

		/* barometric pressure */
		rtty_send_pressure(bmp085_pressure);
                rtty_txstring("\n");
		/* internal temperature */
		rtty_send_temperature((float)bmp085_temperature/10.0);


		/* each NUM_CYCLES send an SMS with the GPS coordinates */
		if (cycles_counter == 0)
		{
			if (!gps_error)
				gprs_send_gps(nmea_data, GPRS_NUMBER);
			else
				gprs_send_sms(GPRS_NUMBER, "No GPS Data");
		}

		cycles_counter++;
		
		if (cycles_counter == NUM_CYCLES)
			cycles_counter = 0;


		blink_led();	

	}

	return 0;

}



/* Serial interrupt
 * Receive NMEA data from GPS into buffer until EOL. 
 * Then check if data is a GGA sentence to store the buffer or discard it
 */

__attribute__ ((interrupt(USCIAB0RX_VECTOR))) void usart0_rx(void)
{

	if (UCA0RXBUF != 0x0d && UCA0RXBUF != 0x0a) /* not EOL */
	{
		nmeatemp[tempcounter] = UCA0RXBUF;
		tempcounter++;
		if (tempcounter>BUFFER_SIZE-1) 
			tempcounter=0;
	}
	else if (UCA0RXBUF == 0x0d) /* EOL is \r\n, so we can discard one of them */
	{
		if (nmeatemp[3] == 'G' && nmeatemp[4] == 'G' && nmeatemp[5] == 'A') /* GGA, Position data */
			while (tempcounter--)
			{
				nmea[tempcounter] = nmeatemp[tempcounter];
			}
		tempcounter=0;
	}

	//serial_putch(UCA0RXBUF);
	//
	/* clear interrupt */
	UC0IFG &= ~UCA0RXIFG;
}



