/*******************************************************************************
  MPLAB Harmony Application Source File
  
  Company:
    Microchip Technology Inc.
  
  File Name:
    app.c

  Summary:
    This file contains the source code for the MPLAB Harmony application.

  Description:
    This file contains the source code for the MPLAB Harmony application.  It 
    implements the logic of the application's state machine and it may call 
    API routines of other MPLAB Harmony modules in the system, such as drivers,
    system services, and middleware.  However, it does not call any of the
    system interfaces (such as the "Initialize" and "Tasks" functions) of any of
    the modules in the system or make any assumptions about when those functions
    are called.  That is the responsibility of the configuration-specific system
    files.
 *******************************************************************************/

// DOM-IGNORE-BEGIN
/*******************************************************************************
* Copyright (C) 2018 Microchip Technology Inc. and its subsidiaries.
*
* Subject to your compliance with these terms, you may use Microchip software
* and any derivatives exclusively with Microchip products. It is your
* responsibility to comply with third party license terms applicable to your
* use of third party software (including open source software) that may
* accompany Microchip software.
*
* THIS SOFTWARE IS SUPPLIED BY MICROCHIP "AS IS". NO WARRANTIES, WHETHER
* EXPRESS, IMPLIED OR STATUTORY, APPLY TO THIS SOFTWARE, INCLUDING ANY IMPLIED
* WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY, AND FITNESS FOR A
* PARTICULAR PURPOSE.
*
* IN NO EVENT WILL MICROCHIP BE LIABLE FOR ANY INDIRECT, SPECIAL, PUNITIVE,
* INCIDENTAL OR CONSEQUENTIAL LOSS, DAMAGE, COST OR EXPENSE OF ANY KIND
* WHATSOEVER RELATED TO THE SOFTWARE, HOWEVER CAUSED, EVEN IF MICROCHIP HAS
* BEEN ADVISED OF THE POSSIBILITY OR THE DAMAGES ARE FORESEEABLE. TO THE
* FULLEST EXTENT ALLOWED BY LAW, MICROCHIP'S TOTAL LIABILITY ON ALL CLAIMS IN
* ANY WAY RELATED TO THIS SOFTWARE WILL NOT EXCEED THE AMOUNT OF FEES, IF ANY,
* THAT YOU HAVE PAID DIRECTLY TO MICROCHIP FOR THIS SOFTWARE.
 *******************************************************************************/
// DOM-IGNORE-END


// *****************************************************************************
// *****************************************************************************
// Section: Included Files 
// *****************************************************************************
// *****************************************************************************

#include "app1.h"


// *****************************************************************************
// *****************************************************************************
// Section: Global Data Definitions
// *****************************************************************************
// *****************************************************************************

uint8_t CACHE_ALIGN switchPromptUSB[] = "\r\nPUSH BUTTON PRESSED";

uint8_t CACHE_ALIGN cdcReadBuffer[APP_READ_BUFFER_SIZE];
uint8_t CACHE_ALIGN cdcWriteBuffer[APP_READ_BUFFER_SIZE];


// *****************************************************************************
/* Application Data

  Summary:
    Holds application data

  Description:
    This structure holds the application's data.

  Remarks:
    This structure should be initialized by the APP_Initialize function.
    
    Application strings and buffers are be defined outside this structure.
*/

APP1_DATA app1Data;


// *****************************************************************************
// *****************************************************************************
// Section: Application Callback Functions
// *****************************************************************************
// *****************************************************************************



/*******************************************************
 * USB CDC Device Events - Application Event Handler
 *******************************************************/

USB_DEVICE_CDC_EVENT_RESPONSE APP_USBDeviceCDCEventHandler
(
    USB_DEVICE_CDC_INDEX index,
    USB_DEVICE_CDC_EVENT event,
    void * pData,
    uintptr_t userData
)
{
    APP1_DATA * appDataObject;
    USB_CDC_CONTROL_LINE_STATE * controlLineStateData;
    USB_DEVICE_CDC_EVENT_DATA_READ_COMPLETE * eventDataRead;
    
    appDataObject = (APP1_DATA *)userData;

    switch(event)
    {
        case USB_DEVICE_CDC_EVENT_GET_LINE_CODING:

            /* This means the host wants to know the current line
             * coding. This is a control transfer request. Use the
             * USB_DEVICE_ControlSend() function to send the data to
             * host.  */

            USB_DEVICE_ControlSend(appDataObject->deviceHandle,
                    &appDataObject->getLineCodingData, sizeof(USB_CDC_LINE_CODING));

            break;

        case USB_DEVICE_CDC_EVENT_SET_LINE_CODING:

            /* This means the host wants to set the line coding.
             * This is a control transfer request. Use the
             * USB_DEVICE_ControlReceive() function to receive the
             * data from the host */

            USB_DEVICE_ControlReceive(appDataObject->deviceHandle,
                    &appDataObject->setLineCodingData, sizeof(USB_CDC_LINE_CODING));

            break;

        case USB_DEVICE_CDC_EVENT_SET_CONTROL_LINE_STATE:

            /* This means the host is setting the control line state.
             * Read the control line state. We will accept this request
             * for now. */

            controlLineStateData = (USB_CDC_CONTROL_LINE_STATE *)pData;
            appDataObject->controlLineStateData.dtr = controlLineStateData->dtr;
            appDataObject->controlLineStateData.carrier = controlLineStateData->carrier;

            USB_DEVICE_ControlStatus(appDataObject->deviceHandle, USB_DEVICE_CONTROL_STATUS_OK);

            break;

        case USB_DEVICE_CDC_EVENT_SEND_BREAK:

            /* This means that the host is requesting that a break of the
             * specified duration be sent. Read the break duration */

            appDataObject->breakData = ((USB_DEVICE_CDC_EVENT_DATA_SEND_BREAK *)pData)->breakDuration;
            
            /* Complete the control transfer by sending a ZLP  */
            USB_DEVICE_ControlStatus(appDataObject->deviceHandle, USB_DEVICE_CONTROL_STATUS_OK);
            
            break;

        case USB_DEVICE_CDC_EVENT_READ_COMPLETE:

            /* This means that the host has sent some data*/
            eventDataRead = (USB_DEVICE_CDC_EVENT_DATA_READ_COMPLETE *)pData;
            
            if(eventDataRead->status != USB_DEVICE_CDC_RESULT_ERROR)
            {
                appDataObject->isReadComplete = true;
                
                appDataObject->numBytesRead = eventDataRead->length; 
            }
            break;

        case USB_DEVICE_CDC_EVENT_CONTROL_TRANSFER_DATA_RECEIVED:

            /* The data stage of the last control transfer is
             * complete. For now we accept all the data */

            USB_DEVICE_ControlStatus(appDataObject->deviceHandle, USB_DEVICE_CONTROL_STATUS_OK);
            break;

        case USB_DEVICE_CDC_EVENT_CONTROL_TRANSFER_DATA_SENT:

            /* This means the GET LINE CODING function data is valid. We don't
             * do much with this data in this demo. */
            break;

        case USB_DEVICE_CDC_EVENT_WRITE_COMPLETE:

            /* This means that the data write got completed. We can schedule
             * the next read. */

            appDataObject->isWriteComplete = true;
            break;

        default:
            break;
    }

    return USB_DEVICE_CDC_EVENT_RESPONSE_NONE;
}

/***********************************************
 * Application USB Device Layer Event Handler.
 ***********************************************/
void APP_USBDeviceEventHandler 
(
    USB_DEVICE_EVENT event, 
    void * eventData, 
    uintptr_t context 
)
{
    USB_DEVICE_EVENT_DATA_CONFIGURED *configuredEventData;

    switch(event)
    {
        case USB_DEVICE_EVENT_SOF:

            /* This event is used for switch debounce. This flag is reset
             * by the switch process routine. */
            app1Data.sofEventHasOccurred = true;
            
            break;

        case USB_DEVICE_EVENT_RESET:

            app1Data.isConfigured = false;

            break;

        case USB_DEVICE_EVENT_CONFIGURED:

            /* Check the configuration. We only support configuration 1 */
            configuredEventData = (USB_DEVICE_EVENT_DATA_CONFIGURED*)eventData;
            
            if ( configuredEventData->configurationValue == 1)
            {
                /* Register the CDC Device application event handler here.
                 * Note how the app1Data object pointer is passed as the
                 * user data */

                USB_DEVICE_CDC_EventHandlerSet(USB_DEVICE_CDC_INDEX_0, APP_USBDeviceCDCEventHandler, (uintptr_t)&app1Data);

                /* Mark that the device is now configured */
                app1Data.isConfigured = true;
            }
            
            break;

        case USB_DEVICE_EVENT_POWER_DETECTED:

            /* VBUS was detected. We can attach the device */
            USB_DEVICE_Attach(app1Data.deviceHandle);
            
            break;

        case USB_DEVICE_EVENT_POWER_REMOVED:
            
            /* VBUS is not available. We can detach the device */
            USB_DEVICE_Detach(app1Data.deviceHandle);
            
            app1Data.isConfigured = false;
            
            //LED_Off();
            
            break;

        case USB_DEVICE_EVENT_SUSPENDED:

            break;

        case USB_DEVICE_EVENT_RESUMED:
        case USB_DEVICE_EVENT_ERROR:
        default:
            
            break;
    }
}

// *****************************************************************************
// *****************************************************************************
// Section: Application Local Functions
// *****************************************************************************
// *****************************************************************************

/*****************************************************
 * This function is called in every step of the
 * application state machine.
 *****************************************************/

bool APP_StateReset(void)
{
    /* This function returns true if the device
     * was reset  */

    bool retVal;

    if(app1Data.isConfigured == false)
    {
        app1Data.state = APP_STATE_WAIT_FOR_CONFIGURATION;
        app1Data.readTransferHandle = USB_DEVICE_CDC_TRANSFER_HANDLE_INVALID;
        app1Data.writeTransferHandle = USB_DEVICE_CDC_TRANSFER_HANDLE_INVALID;
        app1Data.isReadComplete = true;
        app1Data.isWriteComplete = true;
        retVal = true;
    }
    else
    {
        retVal = false;
    }

    return(retVal);
}

// *****************************************************************************
// *****************************************************************************
// Section: Application Initialization and State Machine Functions
// *****************************************************************************
// *****************************************************************************

/*******************************************************************************
  Function:
    void APP_Initialize(void)

  Remarks:
    See prototype in app.h.
 */

void APP1_Initialize(void)
{
    /* Place the App state machine in its initial state. */
    app1Data.state = APP_STATE_INIT;
    
    /* Device Layer Handle  */
    app1Data.deviceHandle = USB_DEVICE_HANDLE_INVALID ;

    /* Device configured status */
    app1Data.isConfigured = false;

    /* Initial get line coding state */
    app1Data.getLineCodingData.dwDTERate = 57600;
    app1Data.getLineCodingData.bParityType = 0;
    app1Data.getLineCodingData.bCharFormat= 0; 
    app1Data.getLineCodingData.bDataBits = 8;

    /* Read Transfer Handle */
    app1Data.readTransferHandle = USB_DEVICE_CDC_TRANSFER_HANDLE_INVALID;

    /* Write Transfer Handle */
    app1Data.writeTransferHandle = USB_DEVICE_CDC_TRANSFER_HANDLE_INVALID;

    /* Initialize the read complete flag */
    app1Data.isReadComplete = true;

    /*Initialize the write complete flag*/
    app1Data.isWriteComplete = true;

    /* Initialize Ignore switch flag */
    app1Data.ignoreSwitchPress = false;

    /* Reset the switch debounce counter */
    app1Data.switchDebounceTimer = 0;

    /* Reset other flags */
    app1Data.sofEventHasOccurred = false;
    
    /* To know status of Switch */
    app1Data.isSwitchPressed = false;

    /* Set up the read buffer */
    app1Data.cdcReadBuffer = &cdcReadBuffer[0];

    /* Set up the read buffer */
    app1Data.cdcWriteBuffer = &cdcWriteBuffer[0];       
}


/******************************************************************************
  Function:
    void APP_Tasks(void)

  Remarks:
    See prototype in app.h.
 */

void APP1_Tasks(void)
{
    /* Update the application state machine based
     * on the current state */
    
    switch(app1Data.state)
    {
        case APP_STATE_INIT:

            /* Open the device layer */
            app1Data.deviceHandle = USB_DEVICE_Open( USB_DEVICE_INDEX_0, DRV_IO_INTENT_READWRITE );

            if(app1Data.deviceHandle != USB_DEVICE_HANDLE_INVALID)
            {
                /* Register a callback with device layer to get event notification (for end point 0) */
                USB_DEVICE_EventHandlerSet(app1Data.deviceHandle, APP_USBDeviceEventHandler, 0);

                app1Data.state = APP_STATE_WAIT_FOR_CONFIGURATION;
            }
            else
            {
                /* The Device Layer is not ready to be opened. We should try
                 * again later. */
            }

            break;

        case APP_STATE_WAIT_FOR_CONFIGURATION:

            /* Check if the device was configured */
            if(app1Data.isConfigured)
            {
                /* If the device is configured then lets start reading */
                app1Data.state = APP_STATE_SCHEDULE_READ;

                app1Data.isWriteComplete = true;
                app1Data.readTransferHandle =  USB_DEVICE_CDC_TRANSFER_HANDLE_INVALID;

                USB_DEVICE_CDC_Read (USB_DEVICE_CDC_INDEX_0,
                        &app1Data.readTransferHandle, app1Data.cdcReadBuffer,
                        APP_READ_BUFFER_SIZE);
            }
            
            break;

        case APP_STATE_SCHEDULE_READ:

            if(app1Data.isConfigured)
            {
                /* This means this device is still configured */

                app1Data.state = APP_STATE_SCHEDULE_WRITE;
            }
            else
            {
                APP_StateReset();
                app1Data.state = APP_STATE_WAIT_FOR_CONFIGURATION;
                        break;
            }

        case APP_STATE_WAIT_FOR_READ_COMPLETE:

            if(APP_StateReset())
            {
                break;
            }

            /* Check if a character was received or a switch was pressed.
             * The isReadComplete flag gets updated in the CDC event handler. */

            if(app1Data.isReadComplete)
            {
                app1Data.state = APP_STATE_SCHEDULE_WRITE;
            }

            break;


        case APP_STATE_SCHEDULE_WRITE:

            app1Data.state = APP_STATE_WAIT_FOR_CONFIGURATION;
            
            break;

        case APP_STATE_WAIT_FOR_WRITE_COMPLETE:

            if(APP_StateReset())
            {
                break;
            }

            /* Check if a character was sent. The isWriteComplete
             * flag gets updated in the CDC event handler */

            app1Data.state = APP_STATE_WAIT_FOR_CONFIGURATION;

            break;

        case APP_STATE_ERROR:
        default:
            
            break;
    }
}

bool USBCDC_getData(uint8_t **buf, uint32_t *cnt)
{
        *buf = NULL;
        *cnt = 0;
        if(app1Data.isReadComplete == true){
                *buf = cdcReadBuffer;
		        *cnt = app1Data.numBytesRead;
        return true;
        }else
                return false;
}

//?????????????????????????
//????????????
bool USBCDC_finishGetData(void)
{
    uint8_t *buf = cdcReadBuffer;
    app1Data.isReadComplete = false;
    USB_DEVICE_CDC_Read(USB_DEVICE_CDC_INDEX_0,
                        &app1Data.readTransferHandle,
                        buf, APP_READ_BUFFER_SIZE);
    return true;
}

bool USBCDC_getPutBuf(uint8_t **buf, uint16_t *bufSize)
{
        if(app1Data.isReadComplete == true){
                cdcWriteBuffer[0]='\0';
                *buf = cdcWriteBuffer;
                *bufSize = 0;
                return true;
        } else {
            *buf = cdcWriteBuffer;
            *bufSize = sizeof(cdcWriteBuffer);
            return false;
        }
}

bool USBCDC_putData(uint8_t *buf, uint32_t cnt)
{
        if(app1Data.isWriteComplete == true){
            app1Data.writeTransferHandle = USB_DEVICE_CDC_TRANSFER_HANDLE_INVALID;
            app1Data.isWriteComplete = false;
            USB_DEVICE_CDC_Write(USB_DEVICE_CDC_INDEX_0,
                                 &app1Data.writeTransferHandle, buf, cnt,
                                 USB_DEVICE_CDC_TRANSFER_FLAGS_DATA_COMPLETE);
                return true;
        }
        return false;
}

/*******************************************************************************
 End of File
 */

