/**
 * @file        main.c
 *
 * @brief       Main program body
 *
 * @version     V1.0.0
 *
 * @date        2023-07-31
 *
 * @attention
 *
 *  Copyright (C) 2023 Geehy Semiconductor
 *
 *  You may not use this file except in compliance with the
 *  GEEHY COPYRIGHT NOTICE (GEEHY SOFTWARE PACKAGE LICENSE).
 *
 *  The program is only for reference, which is distributed in the hope
 *  that it will be useful and instructional for customers to develop
 *  their software. Unless required by applicable law or agreed to in
 *  writing, the program is distributed on an "AS IS" BASIS, WITHOUT
 *  ANY WARRANTY OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the GEEHY SOFTWARE PACKAGE LICENSE for the governing permissions
 *  and limitations under the License.
 */

/* Includes ***************************************************************/
#include "main.h"

/* Private includes *******************************************************/
#include "apm32f4xx_device_cfg.h"
#include "log.h"

/* Private macro **********************************************************/

/* Private typedef ********************************************************/

/* Private variables ******************************************************/
static const char* tag = "main";

__IO uint32_t captureVal = 0U;
__IO uint32_t captureFreq = 0U;
__IO uint32_t captureDuty = 0U;

/* Private function prototypes ********************************************/

/* External variables *****************************************************/
extern TMR_HandleTypeDef htmr5;

/* External functions *****************************************************/

/**
 * @brief   Main program
 *
 * @param   None
 *
 * @retval  None
 */
int main(void)
{
    /* Device configuration */
    DAL_DeviceConfig();

    /* Start TMR5 channel 1 in input capture mode */
    if (DAL_TMR_IC_Start_IT(&htmr5, TMR_CHANNEL_1) != DAL_OK)
    {
        Error_Handler();
    }

    /* Start TMR5 channel 2 in input capture mode */
    if (DAL_TMR_IC_Start_IT(&htmr5, TMR_CHANNEL_2) != DAL_OK)
    {
        Error_Handler();
    }

    /* Infinite loop */
    while (1)
    {
        LOGI(tag, "Frequency: %d Hz\r\n", captureFreq);
        LOGI(tag, "Duty: %d %%\r\n", captureDuty);
        DAL_Delay(500U);
    }
}

/**
 * @brief  Input Capture callback in non-blocking mode
 *
 * @param  htmr TMR IC handle
 *
 * @retval None
 */
void DAL_TMR_IC_CaptureCallback(TMR_HandleTypeDef *htmr)
{
    if (htmr->Channel == DAL_TMR_ACTIVE_CHANNEL_2)
    {
        captureVal = DAL_TMR_ReadCapturedValue(htmr, TMR_CHANNEL_2);
        
        if (captureVal != 0U)
        {
            /* Duty computation */
            captureDuty = ((DAL_TMR_ReadCapturedValue(htmr, TMR_CHANNEL_1)) * 100U) / captureVal;

            /* Frequency computation */
            captureFreq = (DAL_RCM_GetPCLK1Freq() * 2U) / captureVal;
        }
        else
        {
            captureFreq = 0U;
            captureDuty = 0U;
        }
    }
}
