/*
 * Copyright (c) 2015, Texas Instruments Incorporated
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * *  Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * *  Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * *  Neither the name of Texas Instruments Incorporated nor the names of
 *    its contributors may be used to endorse or promote products derived
 *    from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
 * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

/*
 *  ======== usbserialdevice.c ========
 */

#include <string.h>
#include <stdbool.h>

/* XDCtools Header files */
#include <xdc/std.h>
#include <xdc/runtime/Error.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/SPI.h>

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

/* USB Reference Module Header file */
#include "USBCDCD.h"

#define TASKSTACKSIZE   1024

const unsigned char text[] = "TI-RTOS controls USB.\r\n";

Task_Struct task0Struct, task1Struct;
Char task0Stack[TASKSTACKSIZE], task1Stack[TASKSTACKSIZE];

/*
 *  ======== transmitFxn ========
 *  Task to transmit serial data.
 *
 *  This task periodically sends data to the USB host once it's connected.
 */
int8_t error = 0;
Void TaskFxn_Flash(UArg arg0, UArg arg1)
{
    SPI_Params spiParams;
    SPI_Handle spi = NULL;

    /* Create I2C for usage */
    SPI_Params_init(&spiParams);
    spiParams.transferMode = SPI_MODE_BLOCKING;
    spiParams.mode = SPI_MASTER;
    spiParams.bitRate = 12000000;
    spiParams.dataSize = 8;
    spiParams.frameFormat = SPI_POL0_PHA0;      // or SPI_POL1_PHA1
    spiParams.transferTimeout = (uint32_t) 100;

    spi = SPI_open(MSP_EXP430F5529LP_SPIB0, &spiParams);
    while (spi == NULL)
    {
        error = -1;
        Task_sleep(BIOS_WAIT_FOREVER);
    }

    uint8_t txBuf[] = { 0x90, 0x00, 0x00, 0x00 };
    uint8_t tx_count = sizeof(txBuf);

    uint8_t rxBuf[] = { 0x00, 0x00 };
    uint8_t rx_count = sizeof(rxBuf);

    SPI_Transaction transaction1;
    transaction1.txBuf = txBuf;
    transaction1.rxBuf = NULL;
    transaction1.count = (size_t) tx_count;

    SPI_Transaction transaction2;
    transaction2.txBuf = NULL;
    transaction2.rxBuf = rxBuf;
    transaction2.count = (size_t) rx_count;

    if (SPI_transfer(spi, &transaction1) == false)
    {
        error = -2;
        Task_sleep(BIOS_WAIT_FOREVER);
    }

    if (SPI_transfer(spi, &transaction2) == false)
    {
        error = -3;
        Task_sleep(BIOS_WAIT_FOREVER);
    }

    while (true)
    {
        Task_sleep(BIOS_WAIT_FOREVER);
    }
}

Void TaskFxn_USB(UArg arg0, UArg arg1)
{
    unsigned int received = 0;
    unsigned char data[32] = "";

    while (true)
    {

        /* Block while the device is NOT connected to the USB */
        USBCDCD_waitForConnect(BIOS_WAIT_FOREVER);

        received = USBCDCD_receiveData(data, 31, BIOS_WAIT_FOREVER);
        if (received == 0)
        {
            continue;
        }

        GPIO_toggle(Board_LED1);

        USBCDCD_receiveData(data, received, BIOS_WAIT_FOREVER);
    }
}

/*
 *  ======== main ========
 */
int main(void)
{
    // todo: I have changed this 4MHz XT2 to 24MHz XT2.

    /* Construct BIOS objects */
    Task_Params taskParams;

    /* Call board init functions */
    Board_initGeneral();
    Board_initGPIO();
    Board_initSPI();
    Board_initUSB(Board_USBDEVICE);

    USBCDCD_init();

    /* Construct tx/rx Task threads */
    Task_Params_init(&taskParams);
    taskParams.stackSize = TASKSTACKSIZE;
    taskParams.stack = &task0Stack;
    taskParams.priority = 2;
    Task_construct(&task0Struct, (Task_FuncPtr) TaskFxn_Flash, &taskParams,
    NULL);

    taskParams.stack = &task1Stack;
    Task_construct(&task1Struct, (Task_FuncPtr) TaskFxn_USB, &taskParams, NULL);

    /* Turn on user LED */
    GPIO_write(Board_LED0, Board_LED_ON);

    System_printf("Starting the USB Serial Device 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);
}
