/** @brief Implementation of error code display via UART and LED.
 *
 * @copyright 2020 Remsdaq Ltd.
 *
 * @file c4_error_codes.c
 *
 * @date: 5 Jun 2020
 * @author: Dan Smithers <dwhs@remsdaq.com>
 *
 */

#include "c4_error_codes.h"
#include "c4_privilege_modes.h"
//#include "fsl_debug_console.h"
#include <stdio.h>
#include <stdint.h>

static void C4_flashError(const uint32_t err[6]);

static const uint16_t g_ditLength = 1000U * 60/50/2/5; // milli-seconds

#define DIT (1)
#define DI (DIT)
#define DAH (3)
#define CODE_SPACE (1)
#define CHAR_SPACE (3 - CODE_SPACE)
#define WORD_SPACE (7 - CHAR_SPACE - CODE_SPACE)


static const uint32_t FlashCode[C4_ERR_MAX][6] = {
#define CALLISTO_ERR(name, text, ...)  __VA_ARGS__ ,
        ERROR_LIST
#undef CALLISTO_ERR
};

const char err_strings[C4_ERR_MAX][72] = {
#define CALLISTO_ERR(name, text, ...) "C4_ERR_"#name" : "#text,
        ERROR_LIST
#undef CALLISTO_ERR
};

extern void BL_SysTick_DelayTicks(uint32_t n);

void C4_displayError(const char *text, exit_code_t errVal, bool fatal)
{
    printf("%s: %s\n", err_strings[errVal], text);

    do {
        C4_flashError(FlashCode[errVal]);
        BL_SysTick_DelayTicks(3 * DIT * g_ditLength);
    } while ((true == fatal) && (C4_ERR_OK != errVal));
}

void C4_flashError(const uint32_t code[6])
{
    for (unsigned int i = 1; i < 6; ++i)
    {
        FlashLed(code[0], code[i]*g_ditLength, CODE_SPACE*g_ditLength);
    }

    BL_SysTick_DelayTicks(CHAR_SPACE);
 }

