/*
 * interrupt.c
 *
 *  Created on: Aug 29, 2019
 *      Author: abody
 */
#include "main.h"
#include "globals.h"
#include "usart_handler.h"
#include "strutil.h"

#ifndef DIAG_INTERRUPT_IN
#	define DIAG_INTERRUPT_IN()
#endif

#ifndef DIAG_INTERRUPT_OUT
#	define DIAG_INTERRUPT_OUT()
#endif

void HandleConsoleUsartTxDmaIrq(DMAINFO *info, USART_TypeDef *usart)	//	debug usart
{
	DIAG_INTERRUPT_IN();
	if(*info->isReg & info->tcMask) {	// DMA transfer complete
		*info->ifcReg = info->tcMask;
		LL_USART_EnableIT_TC(usart);
		LL_DMA_DisableStream(info->dma, info->stream);
	}
	DIAG_INTERRUPT_OUT();
}

void HandleConsoleUsartIrq(USART_TypeDef *usart)
{
	DIAG_INTERRUPT_IN();
	if(LL_USART_IsActiveFlag_TC(usart) && LL_USART_IsEnabledIT_TC(usart))	// transmission complete
		LL_USART_DisableIT_TC(usart);
	DIAG_INTERRUPT_OUT();
}

#define ADDINFO(b,s,u) \
	b += strcpy_ex(b,s); \
	b += uitodec(b,u);

void PrintStats(char *buffer, uint8_t id,  struct usart_stats *stats, USART_TypeDef *usart, DMAINFO *dmaInfo)
{
	char ids[] = " : ";
	char *bs = buffer;

	ids[0] = id + '0';
	buffer += strcpy_ex(buffer, ids);
	ADDINFO(buffer, " s: ", stats->sent);
	ADDINFO(buffer, " r: ", stats->rcvd);
	ADDINFO(buffer, " sk: ", stats->skiped);
	ADDINFO(buffer, " or: ", stats->overrun);
	ADDINFO(buffer, " he: ", stats->hdrError);
	buffer += strcpy_ex(buffer,",0x");
	buffer += uitohex(buffer, stats->lastErrHdr, 8);
	ADDINFO(buffer, " pe: ", stats->payloadErrror);
	buffer += strcpy_ex(buffer,",0x");
	buffer += uitohex(buffer, stats->pep1, 8);
	buffer += strcpy_ex(buffer,",0x");
	buffer += uitohex(buffer, stats->pep2, 8);
	ADDINFO(buffer, " de: ", stats->dmaError);
	ADDINFO(buffer, " pmh: ", stats->premature_hdr);
	ADDINFO(buffer, " pmp: ", stats->premature_payload);
	buffer += strcpy_ex(buffer, "\r\n");

	SetupTransmit(usart, dmaInfo->dma, dmaInfo->stream, bs, buffer - bs + 1);
}
