
/*
 *  ======== uarttask.c ========
 */

/* XDCtools Header files */
#include <xdc/std.h>
#include <xdc/runtime/System.h>

/* BIOS Header files */
#include <ti/sysbios/BIOS.h>
#include <ti/sysbios/knl/Task.h>

/* TI-RTOS Header files */
#include <ti/drivers/GPIO.h>
#include <ti/drivers/UART.h>

/* Example/Board Header files */
#include "Board.h"

#include <stdint.h>
#include <stdio.h>   // for sprintf()
#include <strings.h> // for strcmp()

#define MAX_UART_STRING_LENGTH	256
#define E_UART_ERROR						-1006
#define E_OUTPUT_STRING_TOO_LONG			-1007
#define E_INPUT_STRING_TOO_LONG				-1008
#define E_UART_TIMEOUT						 1009

/*
 *  ======== uartFxn ========
 *  Task for this function is created statically. See the project's .cfg file.
 *
 */
Void uartFxn(UArg arg0, UArg arg1)
{
    UART_Handle uartPC, uartCB;	// to PC and to collector board
    UART_Params uartParams;
    char inputstring[MAX_UART_STRING_LENGTH], returnstring[MAX_UART_STRING_LENGTH];
    int bytes;
    int iii;
    int err,theErr;

    /* 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_NEWLINE;   // string is read until it reaches a newline
    uartParams.readEcho = UART_ECHO_OFF;
    uartParams.baudRate = 9600;
    uartPC = UART_open(Board_UART0, &uartParams);
    uartParams.baudRate = 38400;  // to collector board
    uartCB = UART_open(Board_UART1, &uartParams);

    if ((uartCB == NULL)) {
        System_printf("Error opening the controller board UART\n");
        System_flush();
    }

    if ((uartPC == NULL)) {
        System_abort("Error opening the PC UART--aborting.\n");
        System_flush();
    }

    System_printf("UART Initialized!\n");
    System_flush();

    /* Loop forever */
    while (1)
    {
    	theErr=0;
    	err=0;

    	/* read string */
    	bytes = UART_read(uartPC, inputstring, MAX_UART_STRING_LENGTH);  // string is read until it reaches a newline (see UART params)
    	if (bytes<0)
    		theErr = E_UART_ERROR;
    	else if (bytes==MAX_UART_STRING_LENGTH) {
    		theErr = E_INPUT_STRING_TOO_LONG;
    	}
    	else if (bytes>0)
		{
//    		System_printf("string(%s)\n",inputstring);
//    		System_flush();
		} // if bytes>0
    	else
    	{
    		System_printf("no bytes, timeout : ");
    		System_flush();
    		theErr = E_UART_TIMEOUT;
    	}

    	// if not a timeout, send response
    	if (theErr!=E_UART_TIMEOUT) {
			sprintf(returnstring, "count %d,END",iii);
    		err = UART_write(uartPC,returnstring,strlen(returnstring));
			System_printf("bytes written: %d [%s]\n",err,returnstring);
    	}
		System_flush();

		iii++;

    } // while (1)
}


