/** @file usart.c
 * Module handling Universal Synchronous/Asynchronous Receiver/Transmitter
 *
 * The module provides functions to configure the usarts and read/write from/to
 * it
 */

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

#include "usart.h"
#include "nvic.h"
#include "usart_regs.h"
#include "reg.h"

#include "rcc.h"
#include "dma.h"

#include "stddef.h"


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

struct CircularBuffer {
	volatile uint8_t* buffer; //the buffer to use as a circular buffer
	uint16_t size;            //the size of the buffer
	uint16_t begin;           //pointer to the current begin of the buffer
	bool dmaLooped;           //whether the DMA looped or not (buffer overflow)
};

struct FragmentedBuffer {
	uint8_t** buffers;        //list of buffers to write to
	uint16_t buffer_size;     //size of a single buffer
	uint16_t byte_index;      //index of the current byte in the current buffer
	uint8_t buffer_nb;        //total number of buffers
	uint8_t free_buffer_nb;   //number of buffers not currently used
	uint8_t buffer_index;     //index of the current buffer
	uint8_t dma_buffer_index; //index of the DMA's current buffer
};

static void configure_usart(volatile struct USART* regs,
		enum UsartConfig config);
static void configure_baudrate(volatile struct USART* regs, uint32_t clock,
		uint32_t baudrate);
static uint32_t write_byte(volatile struct USART* regs, uint8_t byte);
static uint32_t write_to_buffer(volatile struct USART* regs,
		volatile struct FragmentedBuffer *buffer, enum DmaChannel channel,
		uint8_t byte);
static uint32_t read_from_buffer(volatile struct CircularBuffer* buffer,
		enum DmaChannel channel, uint8_t* byte);

static void usart1_tx_callback(enum DmaIRQSource src);
static void usart1_rx_callback(enum DmaIRQSource src);


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

static volatile struct USART* const usart1 = (struct USART*)USART1_BASE_ADDRESS;
static volatile struct USART* const usart2 = (struct USART*)USART2_BASE_ADDRESS;
static volatile struct USART* const usart3 = (struct USART*)USART3_BASE_ADDRESS;

static volatile struct CircularBuffer usart1_rx_buffer;
static volatile struct FragmentedBuffer usart1_tx_buffer;


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

void usart_configure(enum UsartPeriph periph, enum UsartConfig config,
		uint32_t baudrate)
{
	struct RccClocks clocks;
	rcc_get_clocks(&clocks);

	switch (periph) {
		case USART_PERIPH_1:
			rcc_enable(RCC_AHB_NONE, RCC_APB1_NONE, RCC_APB2_USART);
			configure_baudrate(usart1, clocks.apb2_freq, baudrate);
			configure_usart(usart1, config);
			usart1_tx_buffer.buffers = NULL;
			break;
		case USART_PERIPH_2:
			rcc_enable(RCC_AHB_NONE, RCC_APB1_USART2, RCC_APB2_NONE);
			configure_baudrate(usart2, clocks.apb1_freq, baudrate);
			configure_usart(usart2, config);
			break;
		case USART_PERIPH_3:
			rcc_enable(RCC_AHB_NONE, RCC_APB1_USART3, RCC_APB2_NONE);
			configure_baudrate(usart3, clocks.apb1_freq, baudrate);
			configure_usart(usart3, config);
			break;
		default:
			break;
	}
}

uint32_t usart_write_byte(enum UsartPeriph periph, uint8_t byte)
{
	volatile struct USART* regs;
	volatile struct FragmentedBuffer* buffer;
	enum DmaChannel dma_channel;

	switch (periph) {
		case USART_PERIPH_1:
			regs = usart1;
			buffer = &usart1_tx_buffer;
			dma_channel = DMA_CHANNEL_4;
			break;
		case USART_PERIPH_2:
		case USART_PERIPH_3:
		default:
			return 1;
			break;
	}

	if (buffer->buffers) {
		return write_to_buffer(regs, buffer, dma_channel, byte);
	} else {
		while (regs->SR.TXE == 0) {}
		reg_write(regs->DR, USART_DR_DR, byte);
		return 0;
	}
}

uint32_t usart_read_byte(enum UsartPeriph periph, uint8_t* byte)
{
	volatile struct USART* regs;
	volatile struct CircularBuffer* buffer;
	enum DmaChannel dma_channel;

	switch (periph) {
		case USART_PERIPH_1:
			regs = usart1;
			buffer = &usart1_rx_buffer;
			dma_channel = DMA_CHANNEL_5;
			break;
		case USART_PERIPH_2:
		case USART_PERIPH_3:
		default:
			return 1;
			break;
	}

	if (buffer->buffer) {
		return read_from_buffer(buffer, dma_channel, byte);
	} else {
		if (regs->SR.RXNE) {
			*byte = regs->DR.DR;
			return 0;
		} else {
			return 1;
		}
	}
}

void usart_set_tx_buffer(enum UsartPeriph periph, uint8_t** buffers,
		uint16_t buffer_size, uint8_t buffer_nb)
{
	volatile struct FragmentedBuffer* buffer = NULL;
	switch (periph) {
		case USART_PERIPH_1:
			buffer = &usart1_tx_buffer;
			break;
		case USART_PERIPH_2:
			break;
		case USART_PERIPH_3:
			break;
	}

#warning "check for null ptr"

	buffer->buffers = buffers;
	buffer->buffer_size = buffer_size;
	buffer->byte_index = 0;
	buffer->buffer_nb = buffer_nb;
	buffer->free_buffer_nb = buffer_nb - 1;
	buffer->buffer_index = 0;
	buffer->dma_buffer_index = 0;
}

void usart_set_rx_buffer(enum UsartPeriph periph, uint8_t* buffer,
		uint16_t size)
{
	switch (periph) {
		case USART_PERIPH_1:
			dma_configure(DMA_PERIPH_1, DMA_CHANNEL_5,
					DMA_CONFIG_IRQ_COMPLETE | DMA_CONFIG_FROM_PERIPH
					| DMA_CONFIG_CIRCULAR | DMA_CONFIG_INC_MEM
					| DMA_CONFIG_PSIZE_8BITS | DMA_CONFIG_MSIZE_8BITS
					| DMA_CONFIG_PRIO_LOW, (void*)&usart1->DR, buffer,
					size, usart1_rx_callback);
			usart1_rx_buffer.buffer = buffer;
			usart1_rx_buffer.size = size;
			usart1_rx_buffer.begin = 0;
			usart1_rx_buffer.dmaLooped = false;
			reg_set(usart1->CR3, USART_CR3_DMAR);
			break;
		case USART_PERIPH_2:
			break;
		case USART_PERIPH_3:
			break;
	}
}

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

/**
 * Apply the given configuration to the given registers. Generic version of
 * usart_configure()
 */
static void configure_usart(volatile struct USART* regs,
		enum UsartConfig config)
{
	//configure parity
	switch (config)
	{
		case USART_CONFIG_7E1:
		case USART_CONFIG_8E1:
		case USART_CONFIG_7E2:
		case USART_CONFIG_8E2:
			reg_set(regs->CR1, USART_CR1_PCE);
			reg_reset(regs->CR1, USART_CR1_PS);
			break;
		case USART_CONFIG_7O1:
		case USART_CONFIG_7O2:
		case USART_CONFIG_8O1:
		case USART_CONFIG_8O2:
			reg_set(regs->CR1, USART_CR1_PCE);
			reg_set(regs->CR1, USART_CR1_PS);
			break;
		case USART_CONFIG_8N1:
		case USART_CONFIG_8N2:
			reg_reset(regs->CR1, USART_CR1_PCE);
			break;
		default:
			break;
	}

	//configure bit number
	switch (config)
	{
		case USART_CONFIG_7E1:
		case USART_CONFIG_7E2:
		case USART_CONFIG_7O1:
		case USART_CONFIG_7O2:
		case USART_CONFIG_8N1:
		case USART_CONFIG_8N2:
			reg_reset(regs->CR1, USART_CR1_M);
			break;
		case USART_CONFIG_8E2:
		case USART_CONFIG_8E1:
		case USART_CONFIG_8O1:
		case USART_CONFIG_8O2:
			reg_set(regs->CR1, USART_CR1_M);
			break;
		default:
			break;
	}

	//configure stop bits
	switch (config)
	{
		case USART_CONFIG_7E1:
		case USART_CONFIG_7O1:
		case USART_CONFIG_8N1:
		case USART_CONFIG_8E1:
		case USART_CONFIG_8O1:
			reg_reset(regs->CR2, USART_CR2_STOP);
			break;
		case USART_CONFIG_7E2:
		case USART_CONFIG_7O2:
		case USART_CONFIG_8N2:
		case USART_CONFIG_8E2:
		case USART_CONFIG_8O2:
			reg_reset(regs->CR2, USART_CR2_STOP);
			reg_write(regs->CR2, USART_CR2_STOP, 2);
			break;
		default:
			break;
	}

	//enable Rx/Tx
	reg_set(regs->CR1, USART_CR1_TE);
	reg_set(regs->CR1, USART_CR1_RE);
	reg_set(regs->CR1, USART_CR1_UE);
}

/**
 * Configure the given registers with the given baudrate. Baudrate is dependant
 * on the peripheric's clock and may not be exact due to precision errors (see
 * table 192 in documentation)
 */
static void configure_baudrate(volatile struct USART* regs, uint32_t clock,
		uint32_t baudrate)
{
	uint32_t mantissa = clock / (baudrate * 16);
	uint32_t factor = clock / baudrate;
	volatile uint32_t divider = factor - (mantissa * 16);

	reg_reset(regs->BRR, USART_BRR_DIV_Mantissa);
	reg_write(regs->BRR, USART_BRR_DIV_Mantissa, mantissa & 0xFFF);
	reg_reset(regs->BRR, USART_BRR_DIV_Fraction);
	reg_write(regs->BRR, USART_BRR_DIV_Fraction, divider & 0xF);
}

/**
 * Non-blocking write to the given USART. Will return 0 if the write was
 * successfull, 1 otherwise. If the write is successfull, the tranfer complete
 * IRQ is enabled and the DMA disabled
 */
static uint32_t write_byte(volatile struct USART* regs, uint8_t byte)
{
	//write if TX register empty
	if (regs->SR.TXE) {
		reg_write(regs->DR, USART_DR_DR, byte);
		//enable IRQ, disable DMA
		reg_reset(regs->CR3, USART_CR3_DMAT);
		reg_set(regs->CR1, USART_CR1_TXEIE);
		nvic_enable(NVIC_IRQ_USART1);
		return 0;
	} else {
		return 1;
	}
}

/**
 * Writes the given byte to the given UART, using a FragmentedBuffer and a DMA
 * to bufferize the write if the peripheral is already busy.
 */
static uint32_t write_to_buffer(volatile struct USART *regs,
		volatile struct FragmentedBuffer *buffer, enum DmaChannel channel,
		uint8_t byte)
{
	//if the tx register is empty, there is no need to go through the dma
	if (!write_byte(regs, byte)) {
		return 0;
	}

	dma_enter_critical(DMA_PERIPH_1, channel);

	//if the current buffer is full, we need to switch it with an empty one
	if (buffer->byte_index >= buffer->buffer_size) {

		//if all buffer full, simply wait for the DMA to empty one
		dma_exit_critical(DMA_PERIPH_1, channel);
		while (buffer->free_buffer_nb == 0) {}
		dma_enter_critical(DMA_PERIPH_1, channel);

		++buffer->buffer_index;
		if (buffer->buffer_index >= buffer->buffer_nb) {
			buffer->buffer_index = 0;
		}
		--buffer->free_buffer_nb;

		buffer->byte_index = 0;
	} else {
		dma_enter_critical(DMA_PERIPH_1, channel);
	}

	//write the byte
	buffer->buffers[buffer->buffer_index][buffer->byte_index] = byte;
	++buffer->byte_index;

	dma_exit_critical(DMA_PERIPH_1, channel);
	return 0;
}

/**
 * Reads the oldest byte from the given CircularBuffer if any. Returns 0 if the
 * read was successfull, 1 otherwise
 */
static uint32_t read_from_buffer(volatile struct CircularBuffer* buffer,
		enum DmaChannel channel, uint8_t* byte)
{
	//retreive the current end of the buffer based on the DMA's progress
	uint16_t end = buffer->size - dma_get_remaining(DMA_PERIPH_1, channel);

	//check for bytes to read and overflow
	if ((end > buffer->begin) && buffer->dmaLooped) {
		//TODO overflow
		buffer->begin = end;
	} else if ((buffer->begin == end) && !buffer->dmaLooped) {
		//TODO no data
		return 1;
	}

	//read the oldest byte and advance the buffer
	*byte = buffer->buffer[buffer->begin];
	++buffer->begin;
	if (buffer->begin >= buffer->size) {
		buffer->begin = 0;
		buffer->dmaLooped = false;
	}

	return 0;
}

//--callbacks-------------------------------------------------------------------

/**
 * Callback called on DMA TX tranfert's completion. Checks for any remaining
 * data to send. If any, starts a new transfer, else stop the DMA
 */
static void usart1_tx_callback(enum DmaIRQSource src)
{
	(void)src; //only transfer complete expected
	volatile struct FragmentedBuffer* buffer = &usart1_tx_buffer;

	//increment DMA's buffer since the last once has already been sent
	++buffer->dma_buffer_index;
	if (buffer->dma_buffer_index >= buffer->buffer_nb) {
		buffer->dma_buffer_index = 0;
	}
	++buffer->free_buffer_nb;

	//no more data to send, stop here
	if (buffer->dma_buffer_index == buffer->buffer_index
			&& buffer->byte_index == 0) {
		return;
	}

	//else start a new transfer
	dma_configure(DMA_PERIPH_1, DMA_CHANNEL_4,
			DMA_CONFIG_IRQ_COMPLETE | DMA_CONFIG_FROM_MEM
			| DMA_CONFIG_INC_MEM | DMA_CONFIG_PSIZE_8BITS
			| DMA_CONFIG_MSIZE_8BITS | DMA_CONFIG_PRIO_LOW,
			(void*)&usart1->DR,
			(void*)buffer->buffers[buffer->dma_buffer_index],
			buffer->byte_index,
			usart1_tx_callback);

	//if the newly transfering buffer was being written to, switch the current
	//buffer. Since we just ended a transfer, the next buffer should be empty
	if (buffer->dma_buffer_index == buffer->buffer_index)
	{
		++buffer->buffer_index;
		if (buffer->buffer_index >= buffer->buffer_nb) {
			buffer->buffer_index = 0;
		}
		buffer->byte_index = 0;
	}
}

/**
 * Callback called on DMA RX tranfert's completion. Sets a flag needed to
 * properly handle the circular buffer
 */
static void usart1_rx_callback(enum DmaIRQSource src)
{
	(void)src; //only transfer complete expected
	usart1_rx_buffer.dmaLooped = true;
}


//--ISRs------------------------------------------------------------------------

void hdr_usart1(void)
{
	nvic_clear_pending(NVIC_IRQ_USART1);
	nvic_disable(NVIC_IRQ_USART1);
	reg_reset(usart1->CR1, USART_CR1_TXEIE);
	reg_set(usart1->CR3, USART_CR3_DMAT);

	volatile struct FragmentedBuffer* buffer = &usart1_tx_buffer;

	//no more data to send, stop here
	if (buffer->dma_buffer_index == buffer->buffer_index
			&& buffer->byte_index == 0) {
		return;
	}

	dma_configure(DMA_PERIPH_1, DMA_CHANNEL_4,
			DMA_CONFIG_IRQ_COMPLETE | DMA_CONFIG_FROM_MEM
			| DMA_CONFIG_INC_MEM | DMA_CONFIG_PSIZE_8BITS
			| DMA_CONFIG_MSIZE_8BITS | DMA_CONFIG_PRIO_LOW,
			(void*)&usart1->DR,
			(void*)buffer->buffers[buffer->dma_buffer_index],
			buffer->byte_index,
			usart1_tx_callback);

	if (buffer->dma_buffer_index == buffer->buffer_index)
	{
		++buffer->buffer_index;
		if (buffer->buffer_index >= buffer->buffer_nb) {
			buffer->buffer_index = 0;
		}
		buffer->byte_index = 0;
	}
}

