/*
 * ll_consolehandler.cpp
 *
 *  Created on: Nov 7, 2019
 *      Author: abody
 */

#include <f4ll/console_handler.h>
#include <f4ll/str_util.h>

namespace f4ll {

console_handler::console_handler(USART_TypeDef *usart, DMA_TypeDef *dma, uint32_t streamRx, uint32_t streamTx)
    : usart_core(usart, dma, streamRx, streamTx)
{
}

void console_handler::receiver_idle(void) {}

void console_handler::transmission_complete(void) {}

void console_handler::framing_error(void) {}

void console_handler::overrun(void) {}

void console_handler::rx_dma_transfer_complete(void) {}

void console_handler::rx_dma_half_transfer(void) {}

void console_handler::rx_dma_error(dma_helper::dma_error_type reason)
{
    (void)reason;
}

void console_handler::tx_dma_transfer_complete(void)
{
    LL_USART_EnableIT_TC(m_usart);
    LL_DMA_DisableStream(m_tx_dma.get_dma(), m_tx_dma.get_stream());
}

void console_handler::tx_dma_half_transfer(void) {}

void console_handler::tx_dma_error(dma_helper::dma_error_type reason)
{
    (void)reason;
}

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

void console_handler::PrintStats(uint8_t id, PacketUsart &usart)
{
    char ids[] = " : ";
    char *buffer = m_buffer;
    PacketUsart::Stats const &stats(usart.GetStats());

    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);
    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, " rde: ", stats.rxDmaError);
    ADDINFO(buffer, " tde: ", stats.txDmaError);
    ADDINFO(buffer, " pmh: ", stats.premature_hdr);
    ADDINFO(buffer, " pmp: ", stats.premature_payload);
    buffer += strcpy_ex(buffer, "\r\n");

    setup_transmit(m_buffer, buffer - m_buffer + 1);
}

} /* namespace f4ll */
