/*
 * Copyright (c) 2010-2016, Freescale Semiconductor, Inc.
 * Copyright (c) 2016-2021, NXP
 * All rights reserved.
 *
 * SPDX-License-Identifier: BSD-3-Clause
 */
#include "common.h"
#include "fsl_qtmr.h"
#include "boot_loader.h"
#include "AppCommon.h"
#include "Timer.h"
#include "EEPROMDriver.h"

/*******************************************************************************
 * Definitions
 ******************************************************************************/
#define GPTimerEventHandler                     TMR1_IRQHandler
/*******************************************************************************
* Prototypes
******************************************************************************/

/*******************************************************************************
 * Code
 ******************************************************************************/
 /*!
* @brief Implements the callback function of high resoution timing for timing 
* and control of meter application.
*/
void GPTimerEventHandler(void)
{
  /* Clear interrupt flag.*/
  QTMR_ClearStatusFlags(TMR1, kQTMR_CompareFlag);
  
  if (I2CTimeout)
  {
    I2CTimeout--;
  }
  
  SDK_ISR_EXIT_BARRIER;
}

/*!
 * @brief Initializes a tick timer and second timer which are used for various 
 * timing and control for meter application.
 */
void GPTimerModuleInit(void)
{
  uint32 ModValue = 0;
  qtmr_config_t qtmrConfig;
  
  /*
  Initliazing the Configurable timer
  It will use Quad Timer 1
  Enable the Quad Timer Clock
  Interrupt Frequency Desired= 25ms
  Interrupt Frequency in terms of Bus Clock= (Interrupt Time*Bus Freq)
  Configuring the timer in Free Running Mode
   */
  ModValue = BUS_CLOCK/1000 ;

  ModValue = ModValue / 128;
  ModValue=ModValue* INTERRUPT_FREQUENCY;
  QTMR_GetDefaultConfig(&qtmrConfig);
  
  /* Set clock prescaler */
  qtmrConfig.primarySource = kQTMR_ClockDivide_128;
  QTMR_Init(TMR1, &qtmrConfig);
  
  QTMR_SetTimerPeriod(TMR1, ModValue);
  
  /* Enable timer compare interrupt */
  QTMR_EnableInterrupts(TMR1, kQTMR_CompareInterruptEnable);
  
  /* Enable at the NVIC */
  NVIC_SetPriority(TMR1_IRQn, TMR1_INTERRUPT_PRIORITY);
  EnableIRQ(TMR1_IRQn);
  
  /* Start timer */
  QTMR_StartTimer(TMR1, kQTMR_PriSrcRiseEdge);
}