/*****************************************************************************/
/**
 * @file time_ctrl.h
 * @author FanHao (hao_fan_bit_ee@163.com)
 * @brief Time sync controller driver header file.
 * @version 0.0
 * @date 2023-12-20
 * @copyright Copyright(c) 2024 Beijing Institute of Technology.\n
 * Lab of Communication and Network
 *
 ******************************************************************************/

/**
 * @defgroup TimeController_Driver
 * @{
 */

#ifndef TIME_CTRL_H_
#define TIME_CTRL_H_

/***************************** Include Files *********************************/
#include <stdint.h>
/************************** Constant Definitions *****************************/
#define TIME_FRAC_MAX 500000 // how many 10ns in a 5ms
/***************** Macros (Inline Functions) Definitions *********************/
/**************************** Type Definitions *******************************/
/**
 * @enum TIMECTRL_ADJ_TYPE
 * @brief defines the time adjustment methods
 */
typedef enum
{
	TM_ADJ_NONE = 0, ///< none
	TM_ADJ_ADD = 1, ///< adjust time by add
	TM_ADJ_SET = 2  ///< adjust time by set
} TIMECTRL_ADJ_TYPE;

typedef uint32_t TIME_FRAC;
typedef uint32_t TIME_INT;

/**
 * @struct TIME_WORD
 * @brief Time controller time word
 */
typedef struct
{
	TIME_INT int_part; ///< 5ms each LSB
	TIME_FRAC frac_part; ///< 10ns each LSB
} TIME_WORD;

/**
 * @struct TMC_CONFIG
 * @brief TmcConfig holds the initialization parameters of time controller
 */
typedef struct
{
	uintptr_t baseAddr;
	uint32_t reset; // time for reset (unit: us)
} TMC_CONFIG;

/**
 * @struct TMC_INST
 * @brief An instance struct of time controller
 */
typedef struct
{
	TMC_CONFIG config;
	uint32_t modelVer;
} TMC_INST;

/************************** Function Prototypes ******************************/
int32_t TimeCtrl_Init(TMC_INST **instPtr, TMC_CONFIG *config);
uint32_t TimeCtrl_GetVersion(TMC_INST *instPtr);
void TimeCtrl_Destroy(TMC_INST *instPtr);
void TimeCtrl_Reset(TMC_INST *instPtr);
void TimeCtrl_ResetLow(TMC_INST *instPtr);
void TimeCtrl_ResetHigh(TMC_INST *instPtr);

TIME_INT TimeCtrl_GetIntCnt(TMC_INST *instPtr);
TIME_FRAC TimeCtrl_GetFracCnt(TMC_INST *instPtr);

void TimeCtrl_GetCurrentTime(TMC_INST *instPtr, TIME_WORD *tmWord);
void TimeCtrl_GetCurrentStep(TMC_INST *instPtr, TIME_FRAC *tmFrac);

void TimeCtrl_SetOptimizeStep(TMC_INST *instPtr, TIME_FRAC *tmFrac);
void TimeCtrl_TimeAdjust(TMC_INST *instPtr, const TIME_WORD *tmWord, TIMECTRL_ADJ_TYPE type);
void TimeCtrl_CalculateTimeGap(const TIME_WORD *a, const TIME_WORD *b, TIME_WORD *gap);

#endif /* TIME_SYNC_H_ */

/** @} */