/*
 * UartBase.cpp
 *
 *  Created on: Feb 4, 2020
 *      Author: abody
 */

#include <f4ll_cpp/uartbase.h>

namespace f4ll_cpp {

UartBase::UartBase(USART_TypeDef *uart, DMA_TypeDef *dma, uint32_t stream_rx, uint32_t stream_tx)
	: m_uart(uart)
	, m_rxDma(dma, stream_rx)
	, m_txDma(dma, stream_tx)
{
	*m_rxDma.GetIfcReg() =
			m_rxDma.GetTcMask() | m_rxDma.GetHtMask() |
			m_rxDma.GetTeMask() | m_rxDma.GetFeMask() | m_rxDma.GetDmeMask();
	*m_txDma.GetIfcReg() =
			m_txDma.GetTcMask() | m_txDma.GetHtMask() |
			m_txDma.GetTeMask() | m_txDma.GetFeMask() | m_txDma.GetDmeMask();

	LL_DMA_EnableIT_TC(dma, stream_rx);
	LL_DMA_EnableIT_TE(dma, stream_rx);
	LL_DMA_EnableIT_TC(dma, stream_tx);
	LL_DMA_EnableIT_TE(dma, stream_tx);
}

void UartBase::SetupReceive(void *buffer, uint16_t length)
{
	LL_DMA_ConfigAddresses(m_rxDma.GetDma(), m_rxDma.GetStream(), LL_USART_DMA_GetRegAddr(m_uart),
		(uint32_t)buffer, LL_DMA_DIRECTION_PERIPH_TO_MEMORY);
	LL_DMA_SetDataLength(m_rxDma.GetDma(), m_rxDma.GetStream(), length);	// payload already have extra room for hash
	LL_USART_EnableDMAReq_RX(m_uart);
	LL_USART_ClearFlag_ORE(m_uart);
	LL_DMA_EnableStream(m_rxDma.GetDma(), m_rxDma.GetStream());
}


void UartBase::SetupTransmit(void *buffer, uint16_t length)
{
	LL_DMA_ConfigAddresses(m_txDma.GetDma(), m_txDma.GetStream(), (uint32_t)buffer, LL_USART_DMA_GetRegAddr(m_uart), LL_DMA_DIRECTION_MEMORY_TO_PERIPH);
	LL_DMA_SetDataLength(m_txDma.GetDma(), m_txDma.GetStream(), length);
	LL_USART_EnableDMAReq_TX(m_uart);
	LL_DMA_EnableStream(m_txDma.GetDma(), m_txDma.GetStream());
}

}	//	f4ll_cpp
