/* -------------------------------------------------------------------------- 
 * Copyright (c) 2013-2016 ARM Limited. All rights reserved.
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Licensed under the Apache License, Version 2.0 (the License); you may
 * not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an AS IS BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 *      Name:    main.c
 *      Purpose: RTX for Kneron
 *
 *---------------------------------------------------------------------------*/

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "kdrv_cmsis_core.h"
#include "project.h"

#include "kdrv_system.h"
#include "kdrv_uart.h"

#define MSG_SIZE 4096

uint8_t msg_rbuf[MSG_SIZE + 4];
uint8_t msg_tbuf[MSG_SIZE + 4];

static kdrv_uart_handle_t handle0;
void kmdw_console_init(kdrv_uart_dev_id_t uart_dev, uint32_t baudrate)
{
    kdrv_status_t sts = kdrv_uart_open(&handle0, uart_dev, UART_MODE_SYNC_RX | UART_MODE_SYNC_TX, NULL);
    if (sts != KDRV_STATUS_OK)
    {
        //err_msg("Open failed\n");
        return;
    }

    kdrv_uart_config_t cfg;
    cfg.baudrate = baudrate;
    cfg.data_bits = 8;
    cfg.frame_length = 0;
    cfg.stop_bits = 1;
    cfg.parity_mode = PARITY_NONE;
    cfg.fifo_en = false;

    if(kdrv_uart_configure(handle0, UART_CTRL_CONFIG, (void *)&cfg))
    {
        //err_msg("UART%d config failed\n",uart_dev);
    }
}

void myConsoleTest(void)
{
    char cmd;
    char *str = (char *)msg_rbuf;
    int8_t str_len=0;
    
    strcpy(str, "\nPlease enter command 1~5:");
    str_len = strlen(str);
    kdrv_uart_write(UART0_DEV, (uint8_t *)str, str_len);

    kdrv_uart_get_char(UART0_DEV,(char *)&cmd);
    switch(cmd)
    {
        case '1':
            strcpy(str, "1\nHELLO WORLD!");
        break;
        case '2':
            strcpy(str, "2\nGOOD MORNING!");
        break;
        case '3':
            strcpy(str, "3\nGOOD AFTERNOON!");
        break;
        case '4':
            strcpy(str, "4\nGOOD NIGHT!");
        break;
        case '5':
            strcpy(str, "5\nGOOD BYE!");
        break;
    }
    str_len = strlen(str);
    kdrv_uart_write(MSG_PORT, (uint8_t *)str, str_len);
}


/**
 * @brief main, main dispatch function
 */
int main(void) 
{
    SystemCoreClockUpdate();            // System Initialization
    kdrv_system_init();
    kdrv_system_init_ncpu();
    kdrv_uart_initialize();
    kdrv_uart_console_init(MSG_PORT, MSG_PORT_BAUDRATE, NULL);

    while(1)
    {
        myConsoleTest();
    }
}


