/**
*   @copyright       © 2025 Microchip Technology Inc.
    Microchip Technology Inc. and its subsidiaries. You may use this
    software and any derivatives exclusively with Microchip products.

    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, OR ITS INTERACTION WITH MICROCHIP PRODUCTS, COMBINATION
    WITH ANY OTHER PRODUCTS, OR USE IN ANY APPLICATION.

    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.

    MICROCHIP PROVIDES THIS SOFTWARE CONDITIONALLY UPON YOUR ACCEPTANCE OF THESE
    TERMS. 
*
*************************************************************************/

#include "test.h"
#include "diag_flash.h"
#include "diag_flash_shared.h"
#include <stddef.h>
#include <stdint.h>
#include <xc.h>

static uint32_t testResult;
static uint32_t status;

#if DEMO_FLASH_AVAILABLE

#define TEST_FLASH_LOCATION             0x822000U
#define TEST_FLASH_CRC_START_ADDRESS    0x870000
#define TEST_FLASH_CRC_END_ADDRESS      0x871000

void __attribute__ ( ( interrupt, no_auto_psv ) ) _NVMECCInterrupt( )
{
    IFS0bits.NVMECCIF = 0;  //Clear the single bit error flag
    DIAG_FLASH_Callback();
}

uint32_t DEMO_FLASH_TestTask()
{
    status = DEMO_TEST_PASS;
    
    DIAG_FLASH_DATA_WRITE dataCheck;
    uint32_t previousCRC;
    
    testResult = DIAG_FLASH_SingleDoubleErrorDetectionTest((uint32_t *)TEST_FLASH_LOCATION);
    if(testResult == DIAG_FAIL)
    {
        status = DEMO_TEST_FAIL;
    }
    
    testResult = DIAG_FLASH_IntegrityReadPractice((uint32_t *)TEST_FLASH_LOCATION); 
    if(testResult == DIAG_FAIL)
    {
        status = DEMO_TEST_FAIL;
    }
    
    dataCheck.data[0] = 0xFFFFFFFFU;
    dataCheck.data[1] = 0xFFFFFFFFU;
    dataCheck.data[2] = 0xFFFFFFFFU;
    dataCheck.data[3] = 0xFFFFFFFFU;
    testResult = DIAG_FLASH_WriteVerifyPractice((uint32_t *)TEST_FLASH_LOCATION, dataCheck);
    if(testResult == DIAG_FAIL)
    {
        status = DEMO_TEST_FAIL;
    }
    
    previousCRC = DIAG_FLASH_CRCCalculate((uint32_t *)TEST_FLASH_CRC_START_ADDRESS,
    (uint32_t *)TEST_FLASH_CRC_END_ADDRESS);
    testResult = DIAG_FLASH_CRCPractice((uint32_t *)TEST_FLASH_CRC_START_ADDRESS,
    (uint32_t *)TEST_FLASH_CRC_END_ADDRESS, previousCRC);
    if(testResult == DIAG_FAIL)
    {
        status = DEMO_TEST_FAIL;
    }
    
    return status;
}
#endif