#ifndef _HALL_SENSOR_H__
#define _HALL_SENSOR_H__
#include "os/os_types.h"
#include "bsp/bsp.h"
#include "math/fix_math.h"


#define STATE_0 (uint8_t)0
#define STATE_1 (uint8_t)1
#define STATE_2 (uint8_t)2
#define STATE_3 (uint8_t)3
#define STATE_4 (uint8_t)4
#define STATE_5 (uint8_t)5
#define STATE_6 (uint8_t)6
#define STATE_7 (uint8_t)7

#define THETA_NONE        (float)0xFFFF
#define SAMPLE_MAX_COUNT 16

typedef struct {
	u32       	ticks[SAMPLE_MAX_COUNT];
	float   	angles[SAMPLE_MAX_COUNT];
	u32   		ticks_sum;
	float   	angles_sum;
	u32   		index;
	bool  		full;
}hall_sample_t;

typedef struct {
	float 		estimate_el_angle; //60度区间内的估计电角度
	float 		estimate_delta_angle;		
	float   		measured_el_angle; //hall测量到的电角度
	float 		next_delta_angle;
	float        delta_angle_ts;    //每个控制周期角度的增加量，通过上次的速度计算得到
	float        angle_comp_ts;     //每个控制周期角度增加的补偿量，主要用在加减速，hall角度和60度有偏差的情况
	int             comp_count;
	float 		immediately_el_speed; //当前的即时速度,主要用来判断电机转动是否达到稳定
	float 		el_speed; 		//当前的平均效果的电角速度, 单位：rad/s
	float  		rpm;        		//当前的电速度, 单位：RPM
	bool  			trns_detect;     //速度变化超过阈值
	u8    			hall_stat;
	u32   			hall_ticks;	
	s8    			direction;
	s8              running_dir;
	float   		phase_offset;
	hall_sample_t 	samples;
	u32  			sensor_error;
	float         manual_angle;
	s32  		angle_table[8];
}hall_t;

void hall_sensor_init(void);
void hall_sensor_clear(void);
float hall_sensor_get_theta(void); //return degree
float hall_sensor_get_speed(void); //return rpm;
int hall_offset_increase(int inc);
s32 *hall_get_table(void);
bool hall_detect_angle_finish(void);
void hall_detect_angle(s16 angle);
bool hall_detect_offset_finish(void);
void hall_detect_offset(s16 angle);
void hall_set_direction(s8 direction);

#endif /* _HALL_SENSOR_H__ */

