#include <em_device.h>
#include "uart.h"
#define BUFFER_SIZE 80

char buffer[BUFFER_SIZE];
uint8_t readIndex;
int8_t lineCnt;

void UART0_WriteChar(uint8_t c) 				// outputs character c
{
	while (!(USART0->IF & USART_IF_TXBL)){}		// wait for TDRE bit to set	
	USART0->TXDATA = c;							// transmit byte c
}	

void UART1_WriteChar(uint8_t c) 				// outputs character c
{
	while (!(USART1->IF & USART_IF_TXBL)){}		// wait for TDRE bit to set	
	USART1->TXDATA = c;							// transmit byte c
}	

void Write_AMW037(const char* s)
{
	uint8_t i = 0;
	while (s[i] != 0)							// send every string char
		UART1_WriteChar(s[i++]);
}	

void WriteCR_AMW037(const char* s)
{
	uint8_t i = 0;
	while (s[i] != 0)							// send every string char
		UART1_WriteChar(s[i++]);
	UART1_WriteChar(13);						// send CR + LF
	UART1_WriteChar(10);	
}

void CMD_AMW037(const char* s, uint8_t l)		// send command to AMW037
{
	uint8_t i = 0;
	readIndex = 1;								// reset response buffer index
	lineCnt = l;								// read that many response lines
	while (s[i] != 0)							// send every string char
		UART1_WriteChar(s[i++]);
	UART1_WriteChar(13);						// send CR + LF
	UART1_WriteChar(10);	
	SCB->SCR = SCB_SCR_SLEEPONEXIT_Msk;			// prepare to read module response	
	__WFI();									// wait for module response
}

uint32_t a2i(char* s, uint8_t off, uint8_t len)	// get numeric value of substring of s
{												//    starting at offset off
	uint32_t val = 0;							//    and of length len
	for ( ; len>0; len--)
		val = val*10 + (s[off++] - '0');
	return val;
}

void USART0_RX_IRQHandler(void)
{
	USART1->TXDATA = USART0->RXDATA;
}

void USART1_RX_IRQHandler(void)
{
	char c = USART1->RXDATA;					// get received char
	USART0->TXDATA = c;							// echo it to the terminal
	if (c == 10)								// last line character
	{
		readIndex = 1;
		lineCnt--;
	}
	else if (c == '>')							// end of command response 
	{
		readIndex = 0;
		SCB->SCR = 0;							// cancel sleep-on-exit
	}
	else if (lineCnt >= 0)						// ignore remaining response lines
	{
		buffer[readIndex] = c;
		if (readIndex < BUFFER_SIZE)
			readIndex++;
		else
			lineCnt = -1;
	}
}
