/*
 * timing_manager.h
 *
 *  Created on: Oct 3, 2025
 *      Author: herli
 */

#ifndef INC_TIMING_MANAGER_H_
#define INC_TIMING_MANAGER_H_

#include "stdint.h"
#include "id.h"

extern float refClock;
static inline uint8_t TM_GET_IN_BUFFER_ID(uint32_t C);


typedef struct {
    uint32_t ic;      // TIM2->CNT capture
    float    rpm;     // instantaneous rpm estimated for this edge's interval
    float 	accel;
    uint8_t isInj;
    uint8_t new;
} EdgeSample;
extern volatile EdgeSample edgeBuf[TW_PERCYL_TEETH+1];


extern void UpdateEdgeBuffer(uint32_t tickNew, float rpm_est, uint8_t tooth, uint8_t isInj);
extern void ClearEdgeBuffer();
//extern uint8_t TM_GET_IN_BUFFER_ID(uint32_t C);
extern float TM_TIME_FROM_NEAREST_TOOTH(uint32_t C_Ticks, uint8_t fw);

extern float TM_GET_REAL_BIP_ANGLE(uint32_t C_Ticks);

extern float TM_INTEGRATE_ANGLE_FROM_NEAREST_TOOTH(uint32_t C_Ticks, uint8_t fw);
extern float INTEGRATE_ANGLE_FROM_REFERENCE(float time, float reference, uint8_t fw);

extern float TM_INTEGRATE_ANGLE_FROM_REFERENCE(uint32_t C_Ticks, float refAngle, uint8_t fw);
extern float TM_INTEGRATE_TIME_FROM_REFERENCE(float C_Angle, uint8_t teeth_f);
extern float TM_INTEGRATE_TIME_FROM_REFERENCE_PREDICTIVE(float C_Angle, uint8_t teeth_f);

extern float TM_INTEGRATE_TIME_BIP(float C_Angle, uint8_t teeth_i);
extern float TM_INTEGRATE_TIME_BIP_PREDICTIVE(float C_Angle, uint8_t teeth_i);

extern float TM_GET_PHIAD_dTEIN(float EOI_Angle, float MT_RPM);

extern float TM_INTEGRATE_TIME_TO_EOI(float C_Angle, uint8_t teeth_i);
extern float TM_INTEGRATE_TIME_FROM_REFERENCE_Forward(float C_Angle, uint8_t teeth_i, float InitInj);

extern float TM_GET_LOCAL_ACC_TO_ANGLE(float C_Angle, uint8_t roundingMode);
extern float TM_GET_RPM_FROM_NEAREST_TOOTH(uint32_t C_Ticks, uint8_t fw);
extern uint8_t TM_GET_TRIGGER_TEETH_FROM_REFERENCE_AND_TIME(float C_Angle, float time);
extern float TM_UPDATE_ACCELERATION(float last_MT_RPM, float now_MT_RPM, uint32_t dt_mt);
extern float TM_GET_ACCEL_CORRECTION(float last_MT_RPM, float now_MT_RPM, float TEETH_RPM, uint8_t triggerTeeth);
extern float TM_GET_INJ_ACCEL(uint8_t currentTooth);

extern float TM_UPDATE_ACCEL_CORRECTION_BIP(float last_MT_RPM, float now_MT_RPM, float TEETH_RPM);

extern uint16_t TM_GET_T_DELAY_END();

extern void TM_UPDATE_INJECTION_RPM_AND_ALPHA(float EOI_angle, float BIP_angle, uint32_t IC_EOI, uint32_t IC_BIP);
#endif /* INC_TIMING_MANAGER_H_ */
