/*******************************************************************************
  MPLAB Harmony Application Source File

  Company:
    Microchip Technology Inc.

  File Name:
    app_drv_memory.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.
 *******************************************************************************/

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

#include "app_drv_memory.h"
#include "app_drv_usart1.h"
#include "driver/memory/drv_memory.h"
#include <stdio.h>
#include <string.h>

// *****************************************************************************
// *****************************************************************************
// Section: Global Data Definitions
// *****************************************************************************
// *****************************************************************************
#define NVM_BLOCK_START                 0
#define NVM_BUFFER_SIZE                 256
#define NVM_GEOMETRY_TABLE_READ_ENTRY   (0)
#define NVM_GEOMETRY_TABLE_WRITE_ENTRY  (1)
#define NVM_GEOMETRY_TABLE_ERASE_ENTRY  (2)
SYS_MEDIA_GEOMETRY *MemoryGeometry = NULL;
int MemoryReadBlocks;
int MemoryWriteBlocks;
int MemoryEraseBlocks;

DRV_HANDLE MemoryHandle;
DRV_MEMORY_COMMAND_HANDLE MemoryReadHandle;
DRV_MEMORY_COMMAND_HANDLE MemoryWriteHandle;
volatile int MemoryWriteComplete = false;
volatile int MemoryReadComplete = false;
char MemoryWriteBuf[NVM_BUFFER_SIZE];
char MemoryReadBuf[NVM_BUFFER_SIZE];
int MemoryResetCount = 1;

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

  Summary:
    Holds application data

  Description:
    This structure holds the application's data.

  Remarks:
    This structure should be initialized by the APP_DRV_MEMORY_Initialize function.

    Application strings and buffers are be defined outside this structure.
*/

APP_DRV_MEMORY_DATA app_drv_memoryData;

// *****************************************************************************
// *****************************************************************************
// Section: Application Callback Functions
// *****************************************************************************
// *****************************************************************************
void MemoryTransferHandler( SYS_MEDIA_BLOCK_EVENT event, SYS_MEDIA_BLOCK_COMMAND_HANDLE commandHandle, uintptr_t context )
{
    switch( event )
    {
    case SYS_MEDIA_EVENT_BLOCK_COMMAND_COMPLETE:
        if     (commandHandle == MemoryReadHandle)
        { MemoryReadComplete = true; }
        else if(commandHandle == MemoryWriteHandle)
        { MemoryWriteComplete = true; }
        break;

    case SYS_MEDIA_EVENT_BLOCK_COMMAND_ERROR:
        app_drv_memoryData.state = APP_DRV_MEMORY_STATE_ERROR;
        break;
    }
}

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


/* TODO:  Add any necessary local functions.
*/


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

/*******************************************************************************
  Function:
    void APP_DRV_MEMORY_Initialize ( void )

  Remarks:
    See prototype in app_drv_memory.h.
 */

void APP_DRV_MEMORY_Initialize ( void )
{
    /* Place the App state machine in its initial state. */
    app_drv_memoryData.state = APP_DRV_MEMORY_STATE_INIT;



    /* TODO: Initialize your application's state machine and other
     * parameters.
     */
}


/******************************************************************************
  Function:
    void APP_DRV_MEMORY_Tasks ( void )

  Remarks:
    See prototype in app_drv_memory.h.
 */

void APP_DRV_MEMORY_Tasks ( void )
{
    switch ( app_drv_memoryData.state )
    {
    case APP_DRV_MEMORY_STATE_INIT:
        MemoryHandle = DRV_MEMORY_Open(DRV_MEMORY_INDEX_0, DRV_IO_INTENT_READWRITE);
        if(MemoryHandle == DRV_HANDLE_INVALID)
        {
            app_drv_memoryData.state = APP_DRV_MEMORY_STATE_ERROR;
            break;
        }

        DRV_MEMORY_TransferHandlerSet(MemoryHandle, MemoryTransferHandler, 0);

        app_drv_memoryData.state = APP_DRV_MEMORY_STATE_WAIT_ATTACH;
        break;

    case APP_DRV_MEMORY_STATE_WAIT_ATTACH:
        if( DRV_MEMORY_IsAttached(MemoryHandle) == false )
            break;
		
        USART1printf("\r\nNVM attached!\r\n");
		
        MemoryGeometry = DRV_MEMORY_GeometryGet(MemoryHandle);
        if (MemoryGeometry == NULL)
        {
            app_drv_memoryData.state = APP_DRV_MEMORY_STATE_ERROR;
            break;
        }
        MemoryReadBlocks  = (NVM_BUFFER_SIZE / MemoryGeometry->geometryTable[NVM_GEOMETRY_TABLE_READ_ENTRY].blockSize);
        MemoryWriteBlocks = (NVM_BUFFER_SIZE / MemoryGeometry->geometryTable[NVM_GEOMETRY_TABLE_WRITE_ENTRY].blockSize);
        MemoryEraseBlocks = (NVM_BUFFER_SIZE / MemoryGeometry->geometryTable[NVM_GEOMETRY_TABLE_ERASE_ENTRY].blockSize);

        app_drv_memoryData.state = APP_DRV_MEMORY_STATE_READ;
        break;

    case APP_DRV_MEMORY_STATE_READ:
        DRV_MEMORY_AsyncRead(MemoryHandle, &MemoryReadHandle, MemoryReadBuf, NVM_BLOCK_START, MemoryReadBlocks);
        if(MemoryReadHandle == DRV_MEMORY_COMMAND_HANDLE_INVALID)
        {
            app_drv_memoryData.state = APP_DRV_MEMORY_STATE_ERROR;
            break;
        }

        app_drv_memoryData.state = APP_DRV_MEMORY_STATE_READ_WAIT_COMPLETE;
        break;

    case APP_DRV_MEMORY_STATE_READ_WAIT_COMPLETE:
        if(MemoryReadComplete == true)
        {
            MemoryReadComplete = false;

            if( !strncmp((char*)MemoryReadBuf, "Count NVM: ", 11) )
            {
                USART1printf("%s\r\n", MemoryReadBuf);
                sscanf(MemoryReadBuf, "Count NVM: %d", &MemoryResetCount);
                MemoryResetCount = (MemoryResetCount+1)%10;
            }
            else
            {
                USART1printf("Geometry NVM: Buff(%d), R(%d), W(%d), E(%d)\r\n",
                                  NVM_BUFFER_SIZE, MemoryReadBlocks, MemoryWriteBlocks, MemoryEraseBlocks);
            }

            app_drv_memoryData.state = APP_DRV_MEMORY_STATE_WRITE;				
        }
        break;

    case APP_DRV_MEMORY_STATE_WRITE:
        sprintf( MemoryWriteBuf, "Count NVM: %d", MemoryResetCount);
        DRV_MEMORY_AsyncEraseWrite(MemoryHandle, &MemoryWriteHandle, MemoryWriteBuf, NVM_BLOCK_START, MemoryWriteBlocks);

        if(MemoryWriteHandle == DRV_MEMORY_COMMAND_HANDLE_INVALID)
        {
            app_drv_memoryData.state = APP_DRV_MEMORY_STATE_ERROR;
        }
        else
        {
            app_drv_memoryData.state = APP_DRV_MEMORY_STATE_WRITE_WAIT_COMPLETE;
        }
        break;

    case APP_DRV_MEMORY_STATE_WRITE_WAIT_COMPLETE:
        if(MemoryWriteComplete == true)
        {
            MemoryWriteComplete = false;

            DRV_MEMORY_Close( MemoryHandle );

            app_drv_memoryData.state = APP_DRV_MEMORY_STATE_IDLE;
        }
        break;

    case APP_DRV_MEMORY_STATE_ERROR:
        USART1printf("DRV_MEMORY error!\r\n");

        app_drv_memoryData.state = APP_DRV_MEMORY_STATE_IDLE;
        break;

    case APP_DRV_MEMORY_STATE_IDLE:
        break;
    }
}


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