#include <em_device.h>									// header for all micro registers
#include "hardware.h"									// custom headers
#include "uart.h"
#include "hdc1050.h"

extern char buffer[];									// AMW037 response buffer
extern char temp[];
extern char humi[];
const char req1[] = "GET /update?api_key=5CB4E53RRDCJ17Q5";
const char req2[] = " HTTP/1.1\r\nHost: api.thingspeak.com\r\nConnection: close\r\n\r\n";
char streamNum;
uint8_t connect;

void sendRequest(char);

int main()
{
	char close[] = "close N";
	CMU_setup();										// configure clock										// configure GPIO ports											
	I2C0_setup();
	USART_setup();
	LETIMER_setup();

	do
	{
		CMD_AMW037("get wl n s", 1);					// wait for connection with AP
		Delay_ms(1000);
	} while (buffer[1] != '2');							// and getting IP address

	RTC_setup();
	while(1)											// main application loop
	{
		__WFI();										// wait for connect time	
		if (!connect) continue;
		HDC1050_requestConversion();					// request new conversion		
		Delay_ms(50);									// wait for conversion end
		HDC1050_getTempHumi();							// read temperature from sensor		

		CMD_AMW037("tcpc", 1); 							// establish server connection
		if (buffer[1] == '0')							// connect if returned value is 0
		{
			CMD_AMW037("list", 2);						// get request stream number
			streamNum = buffer[3];
			sendRequest(streamNum);						// send request to server
			Delay_ms(500);
			close[6] = streamNum;
			CMD_AMW037(close, 1);
		}
		connect = 0;
	}
}

void sendRequest(char s)
{
	char write_request[] = "write X NNN";				// write request
	char tdata[] = "&field1=";							// temperature data
	char hdata[] = "&field2=";							// humidity data
	uint16_t data_length;								// request data length
	
	data_length = sizeof(req1)-1 + sizeof(tdata)-1 + sizeof(hdata)-1 + sizeof(req2)-1 + 4;
	write_request[6] = s;	
	write_request[8] = (data_length / 100) + '0';
	write_request[9] = (data_length % 100) / 10 + '0';
	write_request[10] = (data_length % 10) + '0';

	WriteCR_AMW037(write_request);						// send request command
	Write_AMW037(req1);									// send request data
	Write_AMW037(tdata);
	Write_AMW037(temp);	
	Write_AMW037(hdata);
	Write_AMW037(humi);
	Write_AMW037(req2);	
}

void RTC_IRQHandler(void)
{
	RTC->IFC = RTC_IFC_COMP0;							// clear RTC IF
	connect = 1;
}
