#include "elog.h"
#include <stdio.h>
#include "main.h"
#include "task_main.h"

extern SemaphoreHandle_t elog_async;
extern SemaphoreHandle_t elog_dma_lock;
void elog_port_output(const char *log, size_t size);

void HAL_UART_TxCpltCallback(UART_HandleTypeDef *huart)
{
  BaseType_t task_woken = pdFALSE;

  if (huart->Instance == huart1.Instance) {
    xSemaphoreGiveFromISR(elog_dma_lock, &task_woken);
  }

  portYIELD_FROM_ISR(task_woken);
}

void task_elog_entry(void const * argument)
{
#ifdef ELOG_ASYNC_LINE_OUTPUT
  static char __attribute__((section(".ram_ahb"))) poll_get_buf[ELOG_LINE_BUF_SIZE - 4];
#else
  static char __attribute__((section(".ram_ahb"))) poll_get_buf[ELOG_ASYNC_OUTPUT_BUF_SIZE - 4];
#endif

  printf("\033[2J"); //清屏
  fflush(stdout);

  elog_init();
  elog_set_fmt(ELOG_LVL_ASSERT, ELOG_FMT_LVL | ELOG_FMT_TAG | ELOG_FMT_TIME);
  elog_set_fmt(ELOG_LVL_ERROR, ELOG_FMT_LVL | ELOG_FMT_TAG | ELOG_FMT_TIME);
  elog_set_fmt(ELOG_LVL_WARN, ELOG_FMT_LVL | ELOG_FMT_TAG | ELOG_FMT_TIME);
  elog_set_fmt(ELOG_LVL_INFO, ELOG_FMT_LVL | ELOG_FMT_TAG | ELOG_FMT_TIME);
  elog_set_fmt(ELOG_LVL_DEBUG, ELOG_FMT_LVL | ELOG_FMT_TAG | ELOG_FMT_TIME);
  elog_set_fmt(ELOG_LVL_VERBOSE, ELOG_FMT_LVL | ELOG_FMT_TAG | ELOG_FMT_TIME);
  elog_start();

  task_main_create(NULL); //进入用户主任务

  while (1) {
    /* waiting log */
    xSemaphoreTake(elog_async, portMAX_DELAY);
    /* polling gets and outputs the log */
    while (1) {
#ifdef ELOG_ASYNC_LINE_OUTPUT
    size_t get_log_size = elog_async_get_line_log(poll_get_buf, sizeof(poll_get_buf));
#else
    size_t get_log_size = elog_async_get_log(poll_get_buf, sizeof(poll_get_buf));
#endif
      if (get_log_size) {
        elog_port_output(poll_get_buf, get_log_size);
      } else {
        break;
      }
    }
  }
}
