/*
 * Copyright (c) 2016, Freescale Semiconductor, Inc.
 * Copyright (c) 2016-2021, NXP
 * All rights reserved.
 *
 * SPDX-License-Identifier: BSD-3-Clause
 */
#include "common.h"
#include "MKM35Z7.h"
#include "defines.h"
#include "math.h"
#include "Application.h"
#include "MeteringLPRT.h"
#include "MeteringInterface3Ph.h"
#include "Calibration3Ph.h"
#include "ComPortDriver.h"
#include "PowerModes.h"
#include "appstructures.h"
#include "fsl_cmp.h"
#include "fsl_qtmr.h"
#include "UserInterface.h"
#include "Timer.h"
#include "AppInterface.h"

/*******************************************************************************
* Prototypes
******************************************************************************/
uint8  SyncVChl;
uint16 Syncing;
uint8  StopMetering;
uint32 ActAccumulator;
uint32 ReactAccumulator;

/*******************************************************************************
 * Code
 ******************************************************************************/
/*!
 * @brief Handles phase on which comparator is locked to for computing frequency.
 */  
void DoSyncing(void)
{
  /* Syncing */
  if (Syncing == 0xAAAA)
  {
    /* Indicates CMP got a zero-crossing and triggerred the timer used for frequency calculation */
    Syncing = 0;
    /* So, do nothing after this and continue to use the current channel for frequency calculation */
  }
  else
  {
    /* Indicates that CMP didn't get a zero-crossing, so count up to a threshold value */
    Syncing++;
    if (Syncing == 0x200)
    {
      /* Change i/p channel to compare using CMP after a (sample)count has expired */
      SyncVChl |= 0x10;
      Syncing = 0;
      SyncVChl++;
      if (SyncVChl == SYNC_TRYING_V2)
      {
        CMP_SetInputChannels(CMP1, YPHASE_CMP_IP_PSEL, CMP_IP_NSEL);
      }
      if (SyncVChl == SYNC_TRYING_V3)
      {
        CMP_SetInputChannels(CMP1, BPHASE_CMP_IP_PSEL, CMP_IP_NSEL);
      }
      if (SyncVChl > SYNC_TRYING_V3)
      {
        SyncVChl = SYNC_TRYING_V1;
        CMP_SetInputChannels(CMP1, RPHASE_CMP_IP_PSEL, CMP_IP_NSEL);
      }
    }
  }
}

/*!
 * @brief Invokes Calib LED functions. This function is used to expose the GPIO interface used for generating 
 * calib LED.
 */
void ON_KWH_LED(void)
{
  ON_KWHLED;
}

void OFF_KWH_LED(void)
{
  OFF_KWHLED;
}

void ON_KVARH_LED(void)
{
  ON_KVARHLED;
}

void OFF_KVARH_LED(void)
{
  OFF_KVARHLED;
}
