//
// Created by Professional on 22.04.2023.
//

#include "crc_calc.h"
CRC_HandleTypeDef hcrc;
void MX_CRC_Init(void)
{

    /* USER CODE BEGIN CRC_Init 0 */

    /* USER CODE END CRC_Init 0 */

    /* USER CODE BEGIN CRC_Init 1 */

    /* USER CODE END CRC_Init 1 */
    hcrc.Instance = CRC;
    hcrc.Init.DefaultInitValueUse = DEFAULT_INIT_VALUE_ENABLE;
    hcrc.Init.InputDataInversionMode = CRC_INPUTDATA_INVERSION_BYTE;
    hcrc.Init.OutputDataInversionMode = CRC_OUTPUTDATA_INVERSION_ENABLE;
    hcrc.InputDataFormat = CRC_INPUTDATA_FORMAT_BYTES;
    if (HAL_CRC_Init(&hcrc) != HAL_OK)
    {
        NVIC_SystemReset();
    }
    /* USER CODE BEGIN CRC_Init 2 */

    /* USER CODE END CRC_Init 2 */

}
err_crc_t calculateROM_CRC32(flash_area_enum_t flash_area, uint32_t *val)
{
    if (flash_area == FLASH_AREA_FULLPROG)
    {
        uint32_t len  = *(uint32_t*)(LEN_ADDRESS);
        if (len >= FLASH_SIZE)
            return BLT_FALSE;
        uint32_t crc_calc = ~HAL_CRC_Calculate(&hcrc, (uint32_t*)FLASH_USER_PROG_ADDRESS, len );
        __HAL_CRC_DR_RESET(&hcrc);
        *val =  crc_calc;
            return BLT_TRUE;
    }
    else if (flash_area == FLASH_AREA_MAINPROG)
    {
/*        uint32_t crc32 = *(uint32_t*) CRC32_USER_PROG_AND_USER_LIB_ADDRESS;
        uint32_t crc_calc = ~HAL_CRC_Calculate(&hcrc, FLASH_USER_PROG_ADDRESS, CRC32_USER_PROG_AND_USER_LIB_ADDRESS - 0x8002000);
        __HAL_CRC_DR_RESET(&hcrc);
        if (crc32 == crc_calc)
            return CRC_OK;
        else
            return CRC_ERROR;*/
    }

}

uint32_t calculateBuf_CRC32(uint32_t *buf, uint32_t len)
{
    return HAL_CRC_Accumulate(&hcrc, buf, len);
}

void reset_CrcModule(void)
{
    __HAL_CRC_DR_RESET(&hcrc);
}