#ifndef _FOC_TYPE_H__
#define _FOC_TYPE_H__
#include "libs/types.h"
#include "math/fast_math.h"
#include "pi_controller.h"
#include "ramp_ctrl.h"
typedef struct _alphabeta {
	float alpha;
	float beta;
}alpha_beta_t;

typedef struct _dqaix {
	union {
		float Id;
		float Vd;
	};
	union {
		float Iq;
		float Vq;
	};
}dq_t;

typedef struct _motor_p {
	u8   poles; //������
	float  ld;    //q ����
	float  lq;    //d ����
	float  rs;     //����
	float  flux_linkage; //����
	float  inertia; //ת������
	float  b_emf;
}motor_param_t;

typedef struct _motor_s {
	float theta;//ת�ӵ�Ƕ�, PI
	int angle;//ת�ӵ�Ƕ�, ��
	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,
	CURRENT_CALIBRATE,
	CHARGER_BOOT_CAP,
	READY_TO_RUN,
	RAMPING_START,
	CLOSED_LOOP,
	RUNNING,
	ANY_STOP
}FOCState;

typedef enum {
	FOC_MODE_OPEN_LOOP, //����
	FOC_MODE_PI_CURRENT,      //ֻ������
	FOC_MODE_PI_SPEED,     //ֻ�ٶȻ�
	FOC_MODE_PI_FULL,         //�ٶȣ�����������
	FOC_MODE_CURRENT_CALI,    //У׼������ȡ
}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;
	volatile int   offset_sample_count;
	volatile bool  is_calibrating;
}current_samp_t;

typedef struct _override {
	bool is_theta;
	float theta;
	bool is_vdq;
	dq_t vdq;
}override_param_t;

typedef enum {
	foc_success = 0,
	foc_not_allowed = 1,
	foc_brake_error = 100,
}foc_fault_t;


typedef struct foc_s {
	bool is_ready;
	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 FOCState state;
	volatile foc_mode_t mode;
	override_param_t override;
	bool mosGate;
	ramp_t start_ramp; //��������ĵ�ѹramp,����������ͨ�����õ�ѹ�����Ƶ���
	ramp_t current_ramp; //���ٵ���б��
	ramp_t speed_ramp; //�ı��ٶȵ�ramp���������ű仯��Ҫ����speed_ramp
	foc_fault_t foc_fault;
}motor_foc_t;

typedef enum {
	NoError = 0,
	STMNotAllow = 1,
	
}FError;

#define degree_2_pi(d) ((float)d * M_PI / 180.0f)
#define pi_2_degree(d) ((float)d * 180.0f / M_PI)
#define A_mA(a) ((a*1000))
#define mA_A(ma) (((float)(ma))/1000.0f)

#define RPM_FOR_CLOSE_LOOP 60.0F
#define MAX_SPEED_RPM 3000

#if 1
#define SECTOR_1  0u
#define SECTOR_2  1u
#define SECTOR_3  2u
#define SECTOR_4  3u
#define SECTOR_5  4u
#define SECTOR_6  5u
#else
#define SECTOR_1  3u
#define SECTOR_2  4u
#define SECTOR_3  5u
#define SECTOR_4  0u
#define SECTOR_5  1u
#define SECTOR_6  2u
#endif
#endif /* _FOC_TYPE_H__ */

