/* XDCtools Header files */
#include <xdc/std.h>
#include <xdc/runtime/System.h>
#include <xdc/runtime/System.h>
#include <xdc/runtime/Error.h>
/* BIOS Header files */
#include <ti/sysbios/BIOS.h>
#include <ti/sysbios/knl/Task.h>
#include <ti/sysbios/hal/Timer.h>
#include <ti/sysbios/knl/Semaphore.h>
#include <ti/sysbios/knl/Swi.h>
#include <ti/sysbios/knl/Queue.h>
#include <ti/sysbios/hal/Hwi.h>
/* TI-RTOS Header files */
#include <ti/drivers/GPIO.h>
#include <ti/drivers/UART.h>
#include <ti/drivers/uart/UARTTiva.h>
/* Board Header file */
#include "Board.h"
#include "inc/hw_ints.h"

#define TASKSTACKSIZE   512

void uart0Func(UArg arg0, UArg arg1) {

    System_printf("UART is set\n");

    char input;
    UART_Handle uart;
    UART_Params uartParams;
    const char echoPrompt[] = "\fEchoing characters:\r\n";

    /* Create a UART with data processing off. */
    UART_Params_init(&uartParams);
    uartParams.writeDataMode = UART_DATA_BINARY;
    uartParams.readDataMode = UART_DATA_BINARY;
    uartParams.readReturnMode = UART_RETURN_FULL;
    uartParams.readEcho = UART_ECHO_OFF;
    uartParams.baudRate = 115200;
    uart = UART_open(Board_UART0, &uartParams);

    if (uart == NULL) System_abort("Error opening the UART\n");
    else System_printf("UART is set\n");

    UART_write(uart, echoPrompt, sizeof(echoPrompt));

    /* Loop forever echoing */
    while (1) {
        UART_read(uart, &input, 1);
        UART_write(uart, &input, 1);
    }
}

void initHwiInt() {

    /* Turn on user LED */
    GPIO_write(Board_LED0, Board_LED_ON);
    Hwi_Params hwiParams;
    Hwi_Handle HwiUART;

    Hwi_Params_init(&hwiParams);
    hwiParams.eventId = INT_UART0_TM4C129;
    hwiParams.enableInt = true;
    HwiUART = Hwi_create(INT_UART0_TM4C129, (Hwi_FuncPtr)uart0Func, &hwiParams, NULL);
    if (HwiUART == NULL) System_printf("Hwi create failed\n");
    else System_printf("Hwi is set\n");
    Hwi_enableInterrupt(INT_UART0_TM4C129);
}


/* main */
int main(void) {

    /* Call board init functions */
    Board_initGeneral();
    Board_initGPIO();
    Board_initUART();

    initHwiInt();

    System_printf("Starting the example\nSystem provider is set to SysMin. "
                  "Halt the target to view any SysMin contents in ROV.\n");
    /* SysMin will only print to the console when you call flush or exit */
    System_flush();

    /* Start BIOS */
    BIOS_start();

    return (0);
}
