/*
 * @Author: wzh
 * @Date: 2024-11-26 11:09:41
 * @LastEditors: mypx mypx_coder@163.com
 * @LastEditTime: 2025-08-15 15:23:58
 * @Description:
 *
 * Copyright (c) 2024 by wzh, All Rights Reserved.
 */
#ifndef __ET_ENCODER_UTILS_H__
#define __ET_ENCODER_UTILS_H__
#include "etk_utils.h"
#include <stdbool.h>
#include <stdint.h>

#ifdef __cplusplus
extern "C"
{
#endif

/**
 * @brief Calculate the shaft rotation speed (RPS) based on encoder count and current tick.
 * @param current_count The current encoder count.
 * @param last_count The last encoder count.
 * @param overflow_cnt The overflow count from HAL_TIM_PeriodElapsedCallback.
 * @param encoder_max_counter The maximum counter value of the encoder.This is a
 *        const value config in TIM Period args.
 * @param cur_tick The current tick value(ms).
 * @return The calculated shaft rotation speed in RPS. Return -1 if division by zero occurs.
 * note: Note the macro ET_ENCODER_MAX_COUNT&ET_ENCODER_TOTAL_PPR should defined in you project.
*/
float et_encoder_calculate_rps(int32_t current_count, int64_t *last_count, volatile int32_t *overflow_cnt,
                               uint32_t cur_tick);

/**
 * @brief Calculate the total count based on encoder count, overflow count,
 * and encoder maximum counter.
 * @param current_count The current encoder count form TIM Encoder.
 * @param last_count The last encoder whole count.
 * @param overflow_cnt The overflow count from HAL_TIM_PeriodElapsedCallback.
 * @param encoder_max_counter The maximum counter value of the encoder.This is a
 *        const value config in TIM Period args.
 * @param of_reset The last_count&overflow reset flag.
 * @return The delta count.
 */
int64_t et_encoder_get_delta_count(int32_t current_count, int64_t *last_count, volatile int32_t *overflow_cnt,
                                   uint32_t encoder_max_count, bool of_reset);

/**
 * @brief Calculate the total encoder count by combining the current counter value 
 *        and accumulated overflow counts.
 * 
 * @param current_count Current reading from the encoder's timer counter (TIMx->CNT).
 * @param overflow_cnt Pointer to the overflow counter that tracks net overflows.
 *                    Increments on forward overflow, decrements on backward overflow.
 * @param encoder_max_count Maximum value of the encoder counter (TIMx->ARR register setting).
 * 
 * @return int64_t The combined 64-bit position value of the encoder.
 */
int64_t et_encoder_get_whole_count(int32_t current_count, volatile int32_t *overflow_cnt, uint32_t encoder_max_count);
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif
