/** @file debug.c
 * Module handling various debug functions
 *
 * The module provides a range of functions and tools to make debug more
 * convenient
 */

//--includes--------------------------------------------------------------------

#include "debug.h"
#include "dma_mbuf.h"
#include "format.h"

#if DEBUG_TRACE || DEBUG_WARN || DEBUG_ERROR


//--local definitions-----------------------------------------------------------

static uint32_t write_debug(uint8_t c, void* arg);

#define DEBUG_BAUDRATE 115200
#define BUFFER_SIZE 162  //(80 char line + \n) * 2


//--local variables-------------------------------------------------------------

static struct DmaMultiBuffer mbuf;
static uint8_t tx_buffer[BUFFER_SIZE];


//--public functions------------------------------------------------------------

void _debug_init(enum UsartPeriph usart, enum GpioPort tx_port,
		enum GpioPin tx_pin)
{
	gpio_configure(tx_port, tx_pin, GPIO_MODE_OUTPUT_FAST,
			GPIO_CONFIG_OUT_ALT_PUSH_PULL);
	usart_configure(usart, USART_CONFIG_8N1, DEBUG_BAUDRATE);
	dma_mbuf_configure(&mbuf,usart_configure_tx_dma(usart),
			DMA_CONFIG_PRIO_LOW, tx_buffer, BUFFER_SIZE);

	debug_trace("");
	debug_trace("------------------------------------------------------------------------------");
	debug_trace("starting debug software");
	debug_trace("compiled on " __DATE__ " at " __TIME__);
	debug_trace("------------------------------------------------------------------------------");
}

void _debug_print(const char* restrict header,
		const char* restrict format, ...)
{
	va_list va;
	va_start(va, format);
	format_vfctprintf(write_debug, nullptr, header, va);
	format_vfctprintf(write_debug, nullptr, format, va);
	va_end(va);
	write_debug('\n', nullptr);

	//ensure everything is written when done
	while (dma_mbuf_switch(&mbuf)) {}
}


//--local functions-------------------------------------------------------------

/**
 * Callback to use with format_vfctprintf() to print caracters to the debug port
 */
static uint32_t write_debug(uint8_t c, void* arg)
{
	(void)arg; //unused, required because of FormatCallback

	while (dma_mbuf_write_byte(&mbuf, c))
	{
		//buffer is full, wait until transfer started
		while (dma_mbuf_switch(&mbuf)) {}
	}

	return 0;
}

#endif //DEBUG_TRACE || DEBUG_WARN || DEBUG_ERROR

