#ifndef _FOC_TYPE_H__
#define _FOC_TYPE_H__
#include "libs/types.h"
#include "math/fast_math.h"
#include "pi_controller.h"

typedef struct _alphabeta {
	float alpha;
	float beta;
}alpha_beta_t;

typedef struct _dqaix {
	float d;
	float q;
}dq_t;

typedef struct _motor_p {
	u8   poles; //极对数
	int  ld;    //q 轴电感
	int  lq;    //d 轴电感
	int  r;     //内阻
	int  flux_linkage; //磁链
}motor_param_t;

typedef struct _motor_s {
	float theta;//转子电角度
	float rpm; //转速
}motor_stat_t;

typedef struct _phase_time {
	u32 A;
	u32 B;
	u32 C;
	u32 low;
	u32 midle;
	u32 high;
}phase_time_t; //三相pwn的duty cnt

typedef enum {
	IDLE = 0,
	START = 1,
	CHARGER_BOOT_CAP = 2,
	READY_TO_RUN = 3
}foc_state_t;

typedef enum {
	FOC_MODE_OPEN_LOOP, //开环
	FOC_MODE_PI_DQ,      //只电流环
	FOC_MODE_PI_SPEED,     //只速度环
	FOC_MODE_PI_FULL         //速度，电流环都有
}foc_mode_t;

typedef struct current_sample {
	u32   adc_offset_a;
	u32   adc_offset_b;
	u32   adc_offset_c;
	float ia;
	float ib;
	float ic;
	u8    sector;
	u32   adc_inject_flags;
}current_samp_t;

typedef struct _override {
	bool is_override_theta;
	float theta;
	bool is_override_v_dq;
	dq_t v_dq;
}override_param_t;

typedef struct foc_s {
	alpha_beta_t alpha_beta;
	current_samp_t current_samp; /* 三相电流采样 */
	dq_t dq_ref; //如果是正常模式下，由速度环输出
	int  rpm_ref; //用户设置的速度
	dq_t dq_v;
	u8   sector; //svpwm 扇区
	float vbus; //母线电压
	motor_param_t motor_p;
	motor_stat_t  motor_s;
	phase_time_t phase_time;
	PI_ctrl_t    PI_id;
	PI_ctrl_t    PI_iq;
	PI_ctrl_t    PI_speed;
	volatile foc_state_t state;
	volatile foc_mode_t mode;
	override_param_t override_p;
	bool gate_output;
	u16  hall_table[8];
}motor_foc_t;

#define degree_2_pi(d) ((float)d * M_PI / 180.0f)
#define pi_2_degree(d) ((float)d * 180.0f / M_PI)

#define SECTOR_1  0u
#define SECTOR_2  1u
#define SECTOR_3  2u
#define SECTOR_4  3u
#define SECTOR_5  4u
#define SECTOR_6  5u

#endif /* _FOC_TYPE_H__ */

