/*
 * p_usart.c
 *
 * Created: 8/19/2020 5:18:25 PM
 *  Author: Penguin
 */ 

#include "p_usart.h"
#include <stdarg.h>
#include <string.h>
#ifdef DEBUG
#define MAX_P_PRINTF_BUFFER 256
uint8_t p_printf_buffer[MAX_P_PRINTF_BUFFER] = {'\0'};
static void p_usart_debug_init(void);
static void p_usart_debug_rx_cb(struct usart_module* const inst);
static volatile uint8_t debug_rc = '\0';
#endif

static void p_usart_debug_enable(void);

void p_usart_init(void)
{
	#ifdef DEBUG
	p_usart_debug_init();
	#endif
}

void p_usart_debug_enable(void)
{
	usart_enable_callback(&p_debug_inst, USART_CALLBACK_BUFFER_RECEIVED);
	usart_read_job(&p_debug_inst, &debug_rc);
}

void p_usart_debug_init(void)
{
	static struct usart_config p_debug_conf;
	usart_get_config_defaults(&p_debug_conf);
	p_debug_conf.pinmux_pad0 = P_DEBUG_USART_PINMUX_PAD0;
	p_debug_conf.pinmux_pad1 = P_DEBUG_USART_PINMUX_PAD1;
	p_debug_conf.pinmux_pad2 = P_DEBUG_USART_PINMUX_PAD2;
	p_debug_conf.pinmux_pad3 = P_DEBUG_USART_PINMUX_PAD3;
	p_debug_conf.mux_setting = P_DEBUG_USART_MUX_SETTING;
	p_debug_conf.baudrate =	P_DEBUG_USART_BAUDRATE;
	
	usart_init(&p_debug_inst, P_DEBUG_USART_MODULE, &p_debug_conf);
	usart_enable(&p_debug_inst);
	
	usart_register_callback(&p_debug_inst, p_usart_debug_rx_cb, USART_CALLBACK_BUFFER_RECEIVED);
	printf("USART Debugging initialized\n");
}
void p_usart_debug_rx_cb(struct usart_module* const inst)
{
	printf("%c", debug_rc);
	usart_read_job(&p_debug_inst, &debug_rc);
}

#ifdef DEBUG
void p_printf(struct usart_module* instance, const char* str, ...)
{
	uint16_t size_str = strlen(str);
	if(size_str >= MAX_P_PRINTF_BUFFER)
	{
		delay_ms(2000);
		return;
	}
	memset(p_printf_buffer, '\0', size_str + 1);
	va_list args;
	va_start(args, str);
	vsprintf((char*)p_printf_buffer,str, args);
	
	va_end(args);
	usart_write_buffer_wait(instance, (uint8_t*)p_printf_buffer, strlen((const char*)p_printf_buffer));
}
#endif