#include "arm_math.h"
#include "PMSM_FOC_Core.h"
#include "PMSM_FOC_Params.h"
#include "foc/core/e_ctrl.h"
#include "math/fix_math.h"
#include "math/fast_math.h"
#include "foc/motor/current.h"
#include "foc/motor/motor.h"
#include "foc/core/svpwm.h"
#include "foc/core/torque.h"
#include "foc/samples.h"
#include "foc/limit.h"
#include "app/nv_storage.h"
#include "bsp/pwm.h"
#include "libs/logger.h"
#include "math/fir.h"

PMSM_FOC_Ctrl gFoc_Ctrl;
static Fir_t phase1, phase2;

static bool g_focinit = false;

static u32 PMSM_FOC_Debug_Task(void *p);

static __INLINE void RevPark(DQ_t *dq, float angle, AB_t *alpha_beta) {
	float c,s;
#if 0
	SinCos_Lut(angle, &s, &c);
#else
	s = gFoc_Ctrl.out.sin;
	c = gFoc_Ctrl.out.cos;
#endif

	alpha_beta->a = dq->d * c - dq->q * s;
	alpha_beta->b = dq->d * s + dq->q * c;
}

static __INLINE void Clark(float A, float B, float C, AB_t *alpha_beta){
	alpha_beta->a = A;
	alpha_beta->b = ONE_BY_SQRT3 * (B - C);
}

static __INLINE void Park(AB_t *alpha_beta, float angle, DQ_t *dq) {
	float c,s;
#if 0
	SinCos_Lut(angle, &s, &c);
#else
	s = gFoc_Ctrl.out.sin;
	c = gFoc_Ctrl.out.cos;
#endif
	dq->d = alpha_beta->a * c + alpha_beta->b * s;
	dq->q = -alpha_beta->a * s + alpha_beta->b * c;
}

#define VD_PRIO_HIGH
static __INLINE float Circle_Limitation(DQ_t *vdq, float vDC, float module, DQ_t *out) {
	float sq_vdq = vdq->d * vdq->d + vdq->q * vdq->q;
	float vDC_m = vDC * module;
	float sq_vDC = vDC_m * vDC_m;
	if (sq_vdq > sq_vDC) {
#ifdef VD_PRIO_HIGH		
		out->d = vdq->d;
		out->q = sqrtf(sq_vDC - out->d*out->d);
#else
		float r = sqrtf(sq_vDC / sq_vdq);
		out->d = vdq->d * r;
		out->q = vdq->q * r;
#endif
	}else {
		out->d = vdq->d;
		out->q = vdq->q;
	}
	return sqrtf(sq_vdq/sq_vDC);
}

static __INLINE void FOC_Set_DqRamp(dq_Rctrl *c, float target, int time) {	
	float cp = c->s_Cp;
	c->s_FinalTgt = target; 
	c->s_Step = (c->s_FinalTgt - cp) / (float)time;
}

static __INLINE float FOC_Get_DqRamp(dq_Rctrl *c) {
	if (++c->n_StepCount == c->n_CtrlCount) {
		c->s_Cp += c->s_Step;
		if (c->s_Step < 0) {
			if (c->s_Cp < c->s_FinalTgt) {
				c->s_Cp = c->s_FinalTgt;
			}
		}else {
			if (c->s_Cp > c->s_FinalTgt) {
				c->s_Cp = c->s_FinalTgt;
			}
		}
		c->n_StepCount = 0;
	}
	return c->s_Cp;
}

static __INLINE void FOC_DqRamp_init(dq_Rctrl *c, int count) {
	c->n_CtrlCount = count;
	c->n_StepCount = 0;
	c->s_Cp = 0;
	c->s_FinalTgt = 0;
	c->s_Step = 0;
}

static __INLINE void FOC_Set_iDqRamp(dq_Rctrl *c, float target) {
	FOC_Set_DqRamp(c, target, (/*CONFIG_IDQ_CTRL_TS/CONFIG_SPD_CTRL_TS - 1*/CURRENT_LOOP_RAMP_COUNT));
}

static __INLINE void FOC_Set_vDqRamp(dq_Rctrl *c, float target) {
	FOC_Set_DqRamp(c, target, (CONFIG_FOC_VDQ_RAMP_FINAL_TIME/1000*((CONFIG_IDQ_CTRL_TS/CONFIG_FOC_VDQ_RAMP_TS))));
}


static void PMSM_FOC_Reset_PID(void) {
	PI_Controller_Reset(gFoc_Ctrl.pi_id, 0);
	PI_Controller_Reset(gFoc_Ctrl.pi_iq, 0);
	PI_Controller_Reset(gFoc_Ctrl.pi_speed, 0);
	PI_Controller_Reset(gFoc_Ctrl.pi_fw, 0);
	PI_Controller_Reset(gFoc_Ctrl.pi_torque, 0);
	PI_Controller_Reset(gFoc_Ctrl.pi_lock, 0);
	PI_Controller_Reset(gFoc_Ctrl.pi_power, 0);
}

static void PMSM_FOC_Conf_PID(void) {
	gFoc_Ctrl.pi_id->kp = nv_get_foc_params()->pid_conf[PID_D_id].kp;
	gFoc_Ctrl.pi_id->ki = nv_get_foc_params()->pid_conf[PID_D_id].ki;
	gFoc_Ctrl.pi_id->kb = nv_get_foc_params()->pid_conf[PID_D_id].kb;
	gFoc_Ctrl.pi_id->DT = (1.0f/(float)CONFIG_IDQ_CTRL_TS);

	gFoc_Ctrl.pi_iq->kp = nv_get_foc_params()->pid_conf[PID_Q_id].kp;
	gFoc_Ctrl.pi_iq->ki = nv_get_foc_params()->pid_conf[PID_Q_id].ki;
	gFoc_Ctrl.pi_iq->kb = nv_get_foc_params()->pid_conf[PID_Q_id].kb;
	gFoc_Ctrl.pi_iq->DT = (1.0f/(float)CONFIG_IDQ_CTRL_TS);

	gFoc_Ctrl.pi_torque->kp = nv_get_foc_params()->pid_conf[PID_TRQ_id].kp;
	gFoc_Ctrl.pi_torque->ki = nv_get_foc_params()->pid_conf[PID_TRQ_id].ki;
	gFoc_Ctrl.pi_torque->kb = nv_get_foc_params()->pid_conf[PID_TRQ_id].kb;
	gFoc_Ctrl.pi_torque->DT = (1.0f/(float)CONFIG_SPD_CTRL_TS);

	gFoc_Ctrl.pi_speed->kp = nv_get_foc_params()->pid_conf[PID_Spd_id].kp;
	gFoc_Ctrl.pi_speed->ki = nv_get_foc_params()->pid_conf[PID_Spd_id].ki;
	gFoc_Ctrl.pi_speed->kb = nv_get_foc_params()->pid_conf[PID_Spd_id].kb;
	gFoc_Ctrl.pi_speed->DT = (1.0f/(float)CONFIG_SPD_CTRL_TS);

	gFoc_Ctrl.pi_power->kp = nv_get_foc_params()->pid_conf[PID_Pow_id].kp;
	gFoc_Ctrl.pi_power->ki = nv_get_foc_params()->pid_conf[PID_Pow_id].ki;
	gFoc_Ctrl.pi_power->kb = nv_get_foc_params()->pid_conf[PID_Pow_id].kb;
	gFoc_Ctrl.pi_power->DT = (1.0f/(float)CONFIG_SPD_CTRL_TS);

	gFoc_Ctrl.pi_lock->kp = nv_get_foc_params()->pid_conf[PID_Lock_id].kp;
	gFoc_Ctrl.pi_lock->ki = nv_get_foc_params()->pid_conf[PID_Lock_id].ki;
	gFoc_Ctrl.pi_lock->kb = nv_get_foc_params()->pid_conf[PID_Lock_id].kb;
	gFoc_Ctrl.pi_lock->DT = (1.0f/(float)CONFIG_SPD_CTRL_TS);

	gFoc_Ctrl.pi_fw->kp = nv_get_foc_params()->pid_conf[PID_FW_id].kp;
	gFoc_Ctrl.pi_fw->ki = nv_get_foc_params()->pid_conf[PID_FW_id].ki;
	gFoc_Ctrl.pi_fw->kb = nv_get_foc_params()->pid_conf[PID_FW_id].kb;
	gFoc_Ctrl.pi_fw->DT = (1.0f/(float)CONFIG_SPD_CTRL_TS);
	PI_Controller_max(gFoc_Ctrl.pi_fw, 0, -CONFIG_MAX_FW_D_CURR);
}

static void PMSM_FOC_UserInit(void) {
	memset(&gFoc_Ctrl.userLim, 0, sizeof(gFoc_Ctrl.userLim));
	gFoc_Ctrl.userLim.s_iDCLim = min(nv_get_foc_params()->s_LimitiDC, gFoc_Ctrl.hwLim.s_iDCMax);
	gFoc_Ctrl.userLim.s_motRPMLim = min(nv_get_foc_params()->s_maxRPM, gFoc_Ctrl.hwLim.s_motRPMMax);
	gFoc_Ctrl.userLim.s_torqueLim = nv_get_foc_params()->s_maxTorque;//MAX_TORQUE;
	gFoc_Ctrl.userLim.s_PhaseCurrLim = min(nv_get_foc_params()->s_PhaseCurrLim, gFoc_Ctrl.hwLim.s_PhaseCurrMax);
	gFoc_Ctrl.userLim.s_vDCMaxLim = nv_get_foc_params()->s_maxDCVol;
	gFoc_Ctrl.userLim.s_vDCMinLim = nv_get_foc_params()->s_minDCVol;
	gFoc_Ctrl.userLim.s_iDCeBrkLim = nv_get_foc_params()->s_iDCeBrkLim;
	gFoc_Ctrl.userLim.s_PhaseCurreBrkLim = nv_get_foc_params()->s_PhaseCurreBrkLim;
	gFoc_Ctrl.userLim.s_PhaseVoleBrkLim = gFoc_Ctrl.hwLim.s_PhaseVolMax;
	
	gFoc_Ctrl.protLim.s_iDCLim = gFoc_Ctrl.userLim.s_iDCLim;
	gFoc_Ctrl.protLim.s_PhaseCurrLim = gFoc_Ctrl.userLim.s_PhaseCurrLim;
}

void PMSM_FOC_RT_LimInit(void) {
	eRamp_init_target(&gFoc_Ctrl.rtLim.rpmLimRamp, gFoc_Ctrl.userLim.s_motRPMLim, CONFIG_LIMIT_RAMP_TIME, CONFIG_LIMIT_RAMP_TIME);
	eRamp_init_target(&gFoc_Ctrl.rtLim.phaseCurrLimRamp, gFoc_Ctrl.userLim.s_PhaseCurrLim, CONFIG_LIMIT_RAMP_TIME, CONFIG_LIMIT_RAMP_TIME);
	eRamp_init_target(&gFoc_Ctrl.rtLim.DCCurrLimRamp, gFoc_Ctrl.userLim.s_iDCLim, CONFIG_LIMIT_RAMP_TIME, CONFIG_LIMIT_RAMP_TIME);
}

void PMSM_FOC_CoreInit(void) {
	Fir_init(&phase1);
	Fir_init(&phase2);
	gFoc_Ctrl.pi_id = &PI_Ctrl_ID;
	gFoc_Ctrl.pi_iq = &PI_Ctrl_IQ;
	gFoc_Ctrl.pi_speed = &PI_Ctrl_Spd;
	gFoc_Ctrl.pi_fw = &PI_Ctrl_fw;
	gFoc_Ctrl.pi_torque = &PI_Ctrl_trq;
	gFoc_Ctrl.pi_lock = &PI_Ctrl_lock;
	gFoc_Ctrl.pi_power = &PI_Ctrl_Power;

	PMSM_FOC_Conf_PID();
	
	memset(&gFoc_Ctrl.in, 0, sizeof(gFoc_Ctrl.in));
	memset(&gFoc_Ctrl.out, 0, sizeof(gFoc_Ctrl.out));
	
	gFoc_Ctrl.hwLim.s_iDCMax = CONFIG_MAX_VBUS_CURRENT;
	gFoc_Ctrl.hwLim.s_motRPMMax = CONFIG_MAX_MOT_RPM;
	gFoc_Ctrl.hwLim.s_PhaseCurrMax = CONFIG_MAX_PHASE_CURR;
	gFoc_Ctrl.hwLim.s_PhaseVolMax = CONFIG_MAX_PHASE_VOL;
	gFoc_Ctrl.hwLim.s_vDCMax      = CONFIG_MAX_DC_VOL;
	gFoc_Ctrl.hwLim.s_torqueMax  = CONFIG_MAX_TORQUE;
	gFoc_Ctrl.hwLim.s_FWDCurrMax = CONFIG_MAX_FW_D_CURR;
	if (!g_focinit) {
		PMSM_FOC_UserInit();
		PMSM_FOC_RT_LimInit();
		shark_task_create(PMSM_FOC_Debug_Task, NULL);
		g_focinit = true;
	}
	
	gFoc_Ctrl.params.n_modulation = CONFIG_SVM_MODULATION;//SVM_Modulation;
	gFoc_Ctrl.params.n_PhaseFilterCeof = (CONFIG_CURR_LP_PARAM>1.0f?1.0f:CONFIG_CURR_LP_PARAM);
	gFoc_Ctrl.params.n_poles = nv_get_motor_params()->poles;//MOTOR_POLES;
	gFoc_Ctrl.in.s_manualAngle = INVALID_ANGLE;
	gFoc_Ctrl.in.b_fwEnable = nv_get_foc_params()->n_FwEnable;
	gFoc_Ctrl.in.s_vDC = nv_get_foc_params()->s_maxDCVol;//(CONFIG_RATED_DC_VOL);

	eRamp_init_target(&gFoc_Ctrl.in.cruiseRpmRamp, 0, CONFIG_ACC_TIME, CONFIG_DEC_TIME);
	
	gFoc_Ctrl.out.n_RunMode = CTRL_MODE_OPEN;
	gFoc_Ctrl.out.f_vdqRation = 0;

	FOC_DqRamp_init(&gFoc_Ctrl.idq_ctl[0], 1);
	FOC_DqRamp_init(&gFoc_Ctrl.idq_ctl[1], 1);

	FOC_DqRamp_init(&gFoc_Ctrl.vdq_ctl[0], (CONFIG_IDQ_CTRL_TS/CONFIG_FOC_VDQ_RAMP_TS));
	FOC_DqRamp_init(&gFoc_Ctrl.vdq_ctl[1], (CONFIG_IDQ_CTRL_TS/CONFIG_FOC_VDQ_RAMP_TS));	
	PMSM_FOC_Reset_PID();

	gFoc_Ctrl.plot_type = Plot_None;
}

//#define PHASE_LFP_FIR
//#define PHASE_LFP
static __INLINE void PMSM_FOC_Update_Hardware(void) {
	AB_t vAB;
#ifdef PHASE_LFP	
	float *iabc = gFoc_Ctrl.in.s_iABCComp;
#elif defined PHASE_LFP_FIR
	float *iabc = gFoc_Ctrl.in.s_iABCFilter;
#else
	float *iabc = gFoc_Ctrl.in.s_iABC;
#endif

	if (!gFoc_Ctrl.in.b_MTPA_calibrate && (gFoc_Ctrl.in.s_manualAngle != INVALID_ANGLE)) {
		gFoc_Ctrl.in.s_motAngle = gFoc_Ctrl.in.s_manualAngle;
		gFoc_Ctrl.in.s_hallAngle = motor_encoder_get_angle();
	}else {
		gFoc_Ctrl.in.s_hallAngle = motor_encoder_get_angle();
		gFoc_Ctrl.in.s_motAngle = gFoc_Ctrl.in.s_hallAngle;
	}
#ifdef CONFIG_DQ_STEP_RESPONSE
	gFoc_Ctrl.in.s_hallAngle = 0;
	gFoc_Ctrl.in.s_motAngle = 0;
#endif
	SinCos_Lut(gFoc_Ctrl.in.s_motAngle, &gFoc_Ctrl.out.sin, &gFoc_Ctrl.out.cos);
	
	gFoc_Ctrl.in.s_motRPM = motor_encoder_get_speed();
	gFoc_Ctrl.in.s_vDC = get_vbus_int();
	//sample current
	phase_current_get(gFoc_Ctrl.in.s_iABC);
	get_phase_vols(gFoc_Ctrl.in.s_vABC);
#if 0
	gFoc_Ctrl.in.s_vABC[0] -= gFoc_Ctrl.in.s_vDC/2.0f;
	gFoc_Ctrl.in.s_vABC[1] -= gFoc_Ctrl.in.s_vDC/2.0f;
	gFoc_Ctrl.in.s_vABC[2] -= gFoc_Ctrl.in.s_vDC/2.0f;

	Clark(gFoc_Ctrl.in.s_vABC[0], gFoc_Ctrl.in.s_vABC[1], gFoc_Ctrl.in.s_vABC[2], &vAB);
	
	Park(&vAB, gFoc_Ctrl.in.s_motAngle, &gFoc_Ctrl.out.s_RealVdq);
#endif
#ifdef PHASE_LFP
	LowPass_Filter(gFoc_Ctrl.in.s_iABCFilter[0], gFoc_Ctrl.in.s_iABC[0], gFoc_Ctrl.params.n_PhaseFilterCeof);
	LowPass_Filter(gFoc_Ctrl.in.s_iABCFilter[1], gFoc_Ctrl.in.s_iABC[1], gFoc_Ctrl.params.n_PhaseFilterCeof);
	LowPass_Filter(gFoc_Ctrl.in.s_iABCFilter[2], gFoc_Ctrl.in.s_iABC[2], gFoc_Ctrl.params.n_PhaseFilterCeof);
	float comp = lp_compestion(gFoc_Ctrl.in.s_motRPM/60.0f*4.0f, CONFIG_CURR_LP_CUT_FREQ);
	gFoc_Ctrl.in.s_iABCComp[0] = gFoc_Ctrl.in.s_iABCFilter[0] * comp;
	gFoc_Ctrl.in.s_iABCComp[1] = gFoc_Ctrl.in.s_iABCFilter[1] * comp;
	gFoc_Ctrl.in.s_iABCComp[2] = gFoc_Ctrl.in.s_iABCFilter[2] * comp;
#elif defined PHASE_LFP_FIR
	gFoc_Ctrl.in.s_iABCFilter[1] = Fir_Filter(&phase1, gFoc_Ctrl.in.s_iABC[1]);
	gFoc_Ctrl.in.s_iABCFilter[2] = Fir_Filter(&phase2, gFoc_Ctrl.in.s_iABC[2]);
	gFoc_Ctrl.in.s_iABCFilter[0] = -(gFoc_Ctrl.in.s_iABCFilter[1] + gFoc_Ctrl.in.s_iABCFilter[2]);
#endif
	Clark(iabc[0], iabc[1], iabc[2], &vAB);

	Park(&vAB, gFoc_Ctrl.in.s_motAngle, &gFoc_Ctrl.out.s_RealIdq);

}

static __INLINE void PMSM_FOC_Update_PI_Idq(void) {
	/* update id pi ctrl */
	gFoc_Ctrl.params.maxvDQ.d = gFoc_Ctrl.in.s_vDC * gFoc_Ctrl.params.n_modulation;//CONFIG_RATED_DC_VOL;
	gFoc_Ctrl.params.minvDQ.d = -gFoc_Ctrl.in.s_vDC * gFoc_Ctrl.params.n_modulation;//CONFIG_RATED_DC_VOL;
	gFoc_Ctrl.params.maxvDQ.q = gFoc_Ctrl.in.s_vDC * gFoc_Ctrl.params.n_modulation;//CONFIG_RATED_DC_VOL;
	gFoc_Ctrl.params.minvDQ.q = -gFoc_Ctrl.in.s_vDC * gFoc_Ctrl.params.n_modulation;//CONFIG_RATED_DC_VOL;

	if (gFoc_Ctrl.params.maxvDQ.d != gFoc_Ctrl.pi_id->max) {
		gFoc_Ctrl.pi_id->max = gFoc_Ctrl.params.maxvDQ.d;
	}
	if (gFoc_Ctrl.params.minvDQ.d != gFoc_Ctrl.pi_id->min) {
		gFoc_Ctrl.pi_id->min = gFoc_Ctrl.params.minvDQ.d;
	}
	/* update iq pi ctrl */
	if (gFoc_Ctrl.params.maxvDQ.q != gFoc_Ctrl.pi_iq->max) {
		gFoc_Ctrl.pi_iq->max = gFoc_Ctrl.params.maxvDQ.q;
	}
	if (gFoc_Ctrl.params.minvDQ.q != gFoc_Ctrl.pi_iq->min) {
		gFoc_Ctrl.pi_iq->min = gFoc_Ctrl.params.minvDQ.q;
	}	
}


#ifdef CONFIG_DQ_STEP_RESPONSE
float target_d = 0.0f;
float target_q = 0.0f;
#endif

static u32 PMSM_FOC_Debug_Task(void *p) {
	if (gFoc_Ctrl.in.b_motEnable) {
#ifdef CONFIG_DQ_STEP_RESPONSE
		if (gFoc_Ctrl.plot_type == Plot_D_Step) {
			plot_2data16(FtoS16x10(target_d), FtoS16x10(gFoc_Ctrl.out.s_RealIdq.d));
		}if (gFoc_Ctrl.plot_type == Plot_Q_Step) {
			plot_2data16(FtoS16x10(target_q), FtoS16x10(gFoc_Ctrl.out.s_RealIdq.q));
		}
#else
		if (gFoc_Ctrl.plot_type == Plot_D_flow) {
			plot_2data16(FtoS16x10(gFoc_Ctrl.idq_ctl[0].s_Cp), FtoS16x10(gFoc_Ctrl.out.s_RealIdq.d));
		}else if (gFoc_Ctrl.plot_type == Plot_Q_flow) {
			plot_2data16(FtoS16x10(gFoc_Ctrl.idq_ctl[1].s_Cp), FtoS16x10(gFoc_Ctrl.out.s_RealIdq.q));
		}else if (gFoc_Ctrl.plot_type == Plot_DQ_Curr) {
			plot_3data16(FtoS16x10(gFoc_Ctrl.out.s_RealIdq.d), FtoS16x10(gFoc_Ctrl.out.s_RealIdq.q), FtoS16x10(gFoc_Ctrl.out.s_FilteriDC));
		}else if (gFoc_Ctrl.plot_type == Plot_Spd_flow) {
			plot_2data16(gFoc_Ctrl.in.s_targetRPM, gFoc_Ctrl.in.s_motRPM);
		}
#endif
	}
	return 1;
}

void PMSM_FOC_Schedule(void) {
	AB_t vAB;

	gFoc_Ctrl.ctrl_count++;

	PMSM_FOC_Update_Hardware();

	if (gFoc_Ctrl.out.n_RunMode != CTRL_MODE_OPEN) {

		PMSM_FOC_Update_PI_Idq();
	#ifndef CONFIG_DQ_STEP_RESPONSE
		float target_d = FOC_Get_DqRamp(&gFoc_Ctrl.idq_ctl[0]);
	#endif
		float err = target_d - gFoc_Ctrl.out.s_RealIdq.d;
		gFoc_Ctrl.in.s_targetVdq.d = PI_Controller_RunSerial(gFoc_Ctrl.pi_id, err);
	#ifndef CONFIG_DQ_STEP_RESPONSE
		float target_q = FOC_Get_DqRamp(&gFoc_Ctrl.idq_ctl[1]);
	#endif
		err = target_q - gFoc_Ctrl.out.s_RealIdq.q;
		gFoc_Ctrl.in.s_targetVdq.q = PI_Controller_RunSerial(gFoc_Ctrl.pi_iq, err);
	}else {
		gFoc_Ctrl.in.s_targetVdq.d = FOC_Get_DqRamp(&gFoc_Ctrl.vdq_ctl[0]);
		gFoc_Ctrl.in.s_targetVdq.q = FOC_Get_DqRamp(&gFoc_Ctrl.vdq_ctl[1]);	
	}

	gFoc_Ctrl.out.f_vdqRation = Circle_Limitation(&gFoc_Ctrl.in.s_targetVdq, gFoc_Ctrl.in.s_vDC, gFoc_Ctrl.params.n_modulation, &gFoc_Ctrl.out.s_OutVdq);
	
	RevPark(&gFoc_Ctrl.out.s_OutVdq, gFoc_Ctrl.in.s_motAngle, &vAB);
	
	SVM_Duty_Fix(&vAB, gFoc_Ctrl.in.s_vDC, FOC_PWM_Half_Period, &gFoc_Ctrl.out);

	phase_current_point(&gFoc_Ctrl.out);
	
	pwm_update_duty(gFoc_Ctrl.out.n_Duty[0], gFoc_Ctrl.out.n_Duty[1], gFoc_Ctrl.out.n_Duty[2]);
	pwm_update_sample(gFoc_Ctrl.out.n_Sample1, gFoc_Ctrl.out.n_Sample2, gFoc_Ctrl.out.n_CPhases);

#ifdef NO_SAMPLE_IDC
	LowPass_Filter(gFoc_Ctrl.out.s_FilterIdq.d, gFoc_Ctrl.out.s_RealIdq.d, 0.01f);
	LowPass_Filter(gFoc_Ctrl.out.s_FilterIdq.q, gFoc_Ctrl.out.s_RealIdq.q, 0.01f);
#endif

	if (gFoc_Ctrl.plot_type != Plot_None) {
		if (gFoc_Ctrl.ctrl_count % 5 == 0) {
			if (gFoc_Ctrl.plot_type == Plot_Phase_curr) {
				plot_3data16(FtoS16(gFoc_Ctrl.in.s_iABC[0]), FtoS16(gFoc_Ctrl.in.s_iABC[1]), FtoS16(gFoc_Ctrl.in.s_iABC[2]));
			}else if (gFoc_Ctrl.plot_type == Plot_Phase_vol) {
				plot_3data16(FtoS16(gFoc_Ctrl.in.s_vABC[0]), FtoS16(gFoc_Ctrl.in.s_vABC[1]), FtoS16(gFoc_Ctrl.in.s_vABC[2]));
			}
		}
	}
}

void PMSM_FOC_LogDebug(void) {

}

/*called in media task */
u8 PMSM_FOC_CtrlMode(void) {
	u8 preMode = gFoc_Ctrl.out.n_RunMode;
	if (gFoc_Ctrl.in.b_cruiseEna && gFoc_Ctrl.in.s_motRPM < CONFIG_MIN_CRUISE_RPM) {
		gFoc_Ctrl.in.b_cruiseEna = false;
	}
	if (!gFoc_Ctrl.in.b_motEnable) {
		gFoc_Ctrl.out.n_RunMode = CTRL_MODE_OPEN;
	}else if (gFoc_Ctrl.in.n_ctlMode == CTRL_MODE_OPEN) {
		gFoc_Ctrl.out.n_RunMode = CTRL_MODE_OPEN;
	}else if (gFoc_Ctrl.in.n_ctlMode == CTRL_MODE_SPD || gFoc_Ctrl.in.b_cruiseEna){
		gFoc_Ctrl.out.n_RunMode = CTRL_MODE_SPD;
	}else if (gFoc_Ctrl.in.n_ctlMode == CTRL_MODE_CURRENT) {
		gFoc_Ctrl.out.n_RunMode = CTRL_MODE_CURRENT;
	}else if (gFoc_Ctrl.in.n_ctlMode == CTRL_MODE_CURRENT_BRK) {
		gFoc_Ctrl.out.n_RunMode = CTRL_MODE_CURRENT_BRK;
	}else {
		if (!gFoc_Ctrl.in.b_cruiseEna) {
			gFoc_Ctrl.out.n_RunMode = CTRL_MODE_TRQ;
		}
	}
	if (preMode != gFoc_Ctrl.out.n_RunMode) {
		if ((preMode == CTRL_MODE_SPD) && (gFoc_Ctrl.out.n_RunMode == CTRL_MODE_TRQ)) {
			PI_Controller_Reset(gFoc_Ctrl.pi_torque, gFoc_Ctrl.in.s_targetTorque);
		}else if ((preMode == CTRL_MODE_TRQ) && (gFoc_Ctrl.out.n_RunMode == CTRL_MODE_SPD)) {
			float target_troque = gFoc_Ctrl.in.s_targetTorque;
			if (gFoc_Ctrl.pi_id->is_sat || gFoc_Ctrl.pi_iq->is_sat) {
				target_troque = PMSM_FOC_Get_Real_Torque();
			}
			PI_Controller_Reset(gFoc_Ctrl.pi_speed, target_troque);
		}else if ((preMode == CTRL_MODE_CURRENT) && (gFoc_Ctrl.out.n_RunMode == CTRL_MODE_TRQ)) {
			PI_Controller_Reset(gFoc_Ctrl.pi_torque, gFoc_Ctrl.in.s_targetTorque);
		}else if ((preMode == CTRL_MODE_TRQ) && (gFoc_Ctrl.out.n_RunMode == CTRL_MODE_CURRENT_BRK)) {
			float real_trq = PMSM_FOC_Get_Real_Torque() * 0.9f;
			eCtrl_reset_Current(min(real_trq, gFoc_Ctrl.in.s_targetTorque));
			eCtrl_set_TgtCurrent(-PMSM_FOC_GeteBrkPhaseCurrent());
		}	
	}
	
	return gFoc_Ctrl.out.n_RunMode;
}

/* MPTA, 弱磁, 功率限制，主要是分配DQ轴电流 */
static __INLINE void PMSM_FOC_FieldWeak(void) {
	if (!gFoc_Ctrl.in.b_fwEnable) {
		return;
	}
}
static __INLINE float PMSM_FOC_Limit_iDC(float maxTrq) {
#if 1
	PI_Ctrl_Power.max = maxTrq;
	float errRef = eRamp_get_intepolation(&gFoc_Ctrl.rtLim.DCCurrLimRamp) - gFoc_Ctrl.out.s_FilteriDC;
	return PI_Controller_run(gFoc_Ctrl.pi_power, errRef);
#else
	return maxTrq;
#endif
}
static __INLINE void PMSM_FOC_idq_Assign(void) {
	if (gFoc_Ctrl.out.n_RunMode == CTRL_MODE_CURRENT || gFoc_Ctrl.out.n_RunMode == CTRL_MODE_CURRENT_BRK) {
		if (gFoc_Ctrl.in.b_MTPA_calibrate && (gFoc_Ctrl.in.s_manualAngle != INVALID_ANGLE)) {
			float s, c;
			normal_sincosf(degree_2_pi(gFoc_Ctrl.in.s_manualAngle + 90.0f), &s, &c);
			gFoc_Ctrl.in.s_targetIdq.d = gFoc_Ctrl.in.s_targetCurrent * c;
			
			if (gFoc_Ctrl.in.s_targetIdq.d > gFoc_Ctrl.hwLim.s_FWDCurrMax) {
				gFoc_Ctrl.in.s_targetIdq.d = gFoc_Ctrl.hwLim.s_FWDCurrMax;
			}else if (gFoc_Ctrl.in.s_targetIdq.d < -gFoc_Ctrl.hwLim.s_FWDCurrMax) {
				gFoc_Ctrl.in.s_targetIdq.d = -gFoc_Ctrl.hwLim.s_FWDCurrMax;
			}
			gFoc_Ctrl.in.s_targetIdq.q = sqrtf(SQ(gFoc_Ctrl.in.s_targetCurrent) - SQ(gFoc_Ctrl.in.s_targetIdq.d));
		}else {
			gFoc_Ctrl.in.s_targetIdq.d = 0;
			gFoc_Ctrl.in.s_targetIdq.q = gFoc_Ctrl.in.s_targetCurrent;
		}
	}else if ((gFoc_Ctrl.out.n_RunMode == CTRL_MODE_TRQ) || (gFoc_Ctrl.out.n_RunMode == CTRL_MODE_SPD)) {
		torque_get_idq(gFoc_Ctrl.in.s_targetTorque, gFoc_Ctrl.in.s_motRPM, &gFoc_Ctrl.in.s_targetIdq);
		PMSM_FOC_FieldWeak();
	}
	u32 mask = cpu_enter_critical();
	FOC_Set_iDqRamp(&gFoc_Ctrl.idq_ctl[0], gFoc_Ctrl.in.s_targetIdq.d);
	FOC_Set_iDqRamp(&gFoc_Ctrl.idq_ctl[1], gFoc_Ctrl.in.s_targetIdq.q);
	cpu_exit_critical(mask);
}

/*called in media task */
void PMSM_FOC_idqCalc(void) {
	if (gFoc_Ctrl.in.b_AutoHold) {
		gFoc_Ctrl.pi_lock->max = CONFIG_DEFAULT_LOCK_PHASE_CURR_LIM;
		gFoc_Ctrl.pi_lock->min = -CONFIG_DEFAULT_LOCK_PHASE_CURR_LIM;
		float vel_count = motor_encoder_get_vel_count();
		float errRef = 0 - vel_count;
		gFoc_Ctrl.in.s_targetTorque = PI_Controller_run(gFoc_Ctrl.pi_lock ,errRef);
		PMSM_FOC_idq_Assign();
		return;
	}
	if ((gFoc_Ctrl.out.n_RunMode == CTRL_MODE_CURRENT) || (gFoc_Ctrl.out.n_RunMode == CTRL_MODE_CURRENT_BRK)) {
		gFoc_Ctrl.in.s_targetCurrent = eCtrl_get_RefCurrent();
		if (gFoc_Ctrl.out.n_RunMode == CTRL_MODE_CURRENT_BRK) {
			if (eCtrl_get_FinalCurrent() < 0.0001f && gFoc_Ctrl.in.s_motRPM < CONFIG_MIN_RPM_EXIT_EBRAKE) {
				gFoc_Ctrl.in.s_targetCurrent = 0;
			}
		}
	}else if (gFoc_Ctrl.out.n_RunMode == CTRL_MODE_TRQ) {
		float refTorque = min(eCtrl_get_RefTorque(), eRamp_get_intepolation(&gFoc_Ctrl.rtLim.phaseCurrLimRamp));
		if (refTorque >= 0) {
			gFoc_Ctrl.pi_torque->max = refTorque;
			gFoc_Ctrl.pi_torque->min = 0;
		}else {
			gFoc_Ctrl.pi_torque->min = refTorque;
			gFoc_Ctrl.pi_torque->max = 0;
		}
		float errRef = eRamp_get_intepolation(&gFoc_Ctrl.rtLim.rpmLimRamp) - gFoc_Ctrl.in.s_motRPM;
		float maxTrq = PI_Controller_RunSat(gFoc_Ctrl.pi_torque, errRef);
		gFoc_Ctrl.in.s_targetTorque = PMSM_FOC_Limit_iDC(maxTrq);
	}else if (gFoc_Ctrl.out.n_RunMode == CTRL_MODE_SPD){
		float maxSpeed = eCtrl_get_FinalSpeed();
		float refSpeed = eCtrl_get_RefSpeed();
		if (gFoc_Ctrl.in.b_cruiseEna) {
			maxSpeed = eRamp_get_target(&gFoc_Ctrl.in.cruiseRpmRamp);
			refSpeed = eRamp_get_intepolation(&gFoc_Ctrl.in.cruiseRpmRamp);//gFoc_Ctrl.in.s_cruiseRPM;
		}
		if (maxSpeed >= 0) {
			gFoc_Ctrl.pi_speed->max = eRamp_get_intepolation(&gFoc_Ctrl.rtLim.phaseCurrLimRamp);//gFoc_Ctrl.userLim.s_PhaseCurrLim;
			gFoc_Ctrl.pi_speed->min = -gFoc_Ctrl.userLim.s_PhaseCurreBrkLim;
		}else if (maxSpeed < 0) {
			gFoc_Ctrl.pi_speed->min = -eRamp_get_intepolation(&gFoc_Ctrl.rtLim.phaseCurrLimRamp);//gFoc_Ctrl.userLim.s_PhaseCurrLim;
			gFoc_Ctrl.pi_speed->max = gFoc_Ctrl.userLim.s_PhaseCurreBrkLim;
		}

		if ((maxSpeed == 0) && (gFoc_Ctrl.in.s_motRPM < CONFIG_MIN_RPM_EXIT_EBRAKE)) {
			gFoc_Ctrl.pi_speed->max = 0;
			gFoc_Ctrl.pi_speed->min = 0; //防止倒转
		}
		gFoc_Ctrl.in.s_targetRPM = refSpeed;
		float errRef = refSpeed - gFoc_Ctrl.in.s_motRPM;
		float maxTrq = PI_Controller_RunSat(gFoc_Ctrl.pi_speed, errRef);
		gFoc_Ctrl.in.s_targetTorque = PMSM_FOC_Limit_iDC(maxTrq);
	}

	PMSM_FOC_idq_Assign();
}

void PMSM_FOC_RunTime_Limit(void) {
	float dclim = (float)vbus_current_vol_lower_limit();
	float phaselim = (float)phase_current_temp_high_limit();

	dclim = (dclim!=CURRENT_LIMIT_NONE)?dclim:gFoc_Ctrl.userLim.s_iDCLim;
	phaselim = (phaselim!=CURRENT_LIMIT_NONE)?phaselim:gFoc_Ctrl.userLim.s_PhaseCurrLim;

	dclim = min(dclim, gFoc_Ctrl.userLim.s_iDCLim);
	phaselim = min(phaselim, gFoc_Ctrl.userLim.s_PhaseCurrLim);

	if (phaselim < gFoc_Ctrl.rtLim.phaseCurrLimRamp.target) {
		eRamp_set_step_target(&gFoc_Ctrl.rtLim.phaseCurrLimRamp, phaselim, CONFIG_eCTRL_STEP_TS);
	}
	if (dclim < gFoc_Ctrl.rtLim.DCCurrLimRamp.target) {
		eRamp_set_step_target(&gFoc_Ctrl.rtLim.DCCurrLimRamp, dclim, CONFIG_eCTRL_STEP_TS);
	}
	gFoc_Ctrl.protLim.s_iDCLim = dclim;
	gFoc_Ctrl.protLim.s_PhaseCurrLim = phaselim;
}

void PMSM_FOC_Slow_Task(void) {
	eRamp_running(&gFoc_Ctrl.rtLim.phaseCurrLimRamp);
	eRamp_running(&gFoc_Ctrl.rtLim.rpmLimRamp);
	eRamp_running(&gFoc_Ctrl.rtLim.DCCurrLimRamp);
	eRamp_running(&gFoc_Ctrl.in.cruiseRpmRamp);

	PMSM_FOC_idqCalc();
}

float PMSM_FOC_Get_Real_Torque(void) {
	if (gFoc_Ctrl.out.s_RealCurrent == 0) {
		gFoc_Ctrl.out.s_RealCurrent = sqrtf(SQ(gFoc_Ctrl.out.s_FilterIdq.d) + SQ(gFoc_Ctrl.out.s_FilterIdq.q));
	}
	return gFoc_Ctrl.out.s_RealCurrent;
}

PMSM_FOC_Ctrl *PMSM_FOC_Get(void) {
	return &gFoc_Ctrl;
}

void PMSM_FOC_Start(u8 nCtrlMode) {
	if (gFoc_Ctrl.in.b_motEnable) {
		return;
	}
	PMSM_FOC_CoreInit();
	eCtrl_Reset();
	gFoc_Ctrl.in.n_ctlMode = nCtrlMode;
	gFoc_Ctrl.in.b_motEnable = true;
}

void PMSM_FOC_Stop(void) {
	if (!gFoc_Ctrl.in.b_motEnable) {
		return;
	}
	PMSM_FOC_CoreInit();
	gFoc_Ctrl.in.b_motEnable = false;
}

bool PMSM_FOC_Is_Start(void) {
	return gFoc_Ctrl.in.b_motEnable;
}

void PMSM_FOC_DCCurrLimit(float ibusLimit) {
	float minCurr = min(gFoc_Ctrl.hwLim.s_iDCMax, gFoc_Ctrl.protLim.s_iDCLim);
	if (ibusLimit > minCurr) {
		ibusLimit = minCurr;
	}
	gFoc_Ctrl.userLim.s_iDCLim = (ibusLimit);
	if (ABS(gFoc_Ctrl.in.s_motRPM) < 10){
		eRamp_reset_target(&gFoc_Ctrl.rtLim.DCCurrLimRamp, ibusLimit);
	}else {
		eRamp_set_step_target(&gFoc_Ctrl.rtLim.DCCurrLimRamp, ibusLimit, CONFIG_eCTRL_STEP_TS);
	}
}

float PMSM_FOC_GetDCCurrLimit(void) {
	return gFoc_Ctrl.userLim.s_iDCLim;
}

void PMSM_FOC_SpeedLimit(float speedLimit) {
	PMSM_FOC_SpeedRampLimit(speedLimit, CONFIG_LIMIT_RAMP_TIME);
}

void PMSM_FOC_SpeedRampLimit(float speedLimit, u32 rampTime) {
	if (speedLimit > gFoc_Ctrl.hwLim.s_motRPMMax) {
		speedLimit = gFoc_Ctrl.hwLim.s_motRPMMax;
	}
	bool need_reset = false;
	if (speedLimit < gFoc_Ctrl.userLim.s_motRPMLim){
		need_reset = true;
	}
	gFoc_Ctrl.userLim.s_motRPMLim = (speedLimit);
	eRamp_set_time(&gFoc_Ctrl.rtLim.rpmLimRamp, rampTime, rampTime);
	if (need_reset) {
		if ((gFoc_Ctrl.out.n_RunMode == CTRL_MODE_TRQ) && gFoc_Ctrl.out.f_vdqRation >= 1.0f) {
			PI_Controller_Reset(gFoc_Ctrl.pi_torque, gFoc_Ctrl.out.s_RealCurrent);
		}else if ((gFoc_Ctrl.out.n_RunMode == CTRL_MODE_SPD) && gFoc_Ctrl.pi_speed->is_sat) {
			PI_Controller_Reset(gFoc_Ctrl.pi_speed, gFoc_Ctrl.out.s_RealCurrent);
		}
	}
	if (ABS(gFoc_Ctrl.in.s_motRPM) < 10) {
		eRamp_reset_target(&gFoc_Ctrl.rtLim.rpmLimRamp, speedLimit);
	}else {
		eRamp_set_step_target(&gFoc_Ctrl.rtLim.rpmLimRamp, speedLimit, CONFIG_eCTRL_STEP_TS);
	}
}


/* 扭矩模式下的限速，主要是处理转把对应的最高速 */
void PMSM_FOC_Torque_SpeedLimit(float speedLimit) {
	if (speedLimit > gFoc_Ctrl.hwLim.s_motRPMMax) {
		speedLimit = gFoc_Ctrl.hwLim.s_motRPMMax;
	}
	if (speedLimit > gFoc_Ctrl.userLim.s_motRPMLim) {
		speedLimit = gFoc_Ctrl.userLim.s_motRPMLim;
	}
	eRamp_set_time(&gFoc_Ctrl.rtLim.rpmLimRamp, 1000, 1000);
	if (gFoc_Ctrl.in.s_motRPM == 0) {
		eRamp_reset_target(&gFoc_Ctrl.rtLim.rpmLimRamp, speedLimit/1.3f);//1.3的系数防止限速过冲
		eRamp_set_step_target(&gFoc_Ctrl.rtLim.rpmLimRamp, speedLimit, CONFIG_eCTRL_STEP_TS);
	}else {
		eRamp_set_step_target(&gFoc_Ctrl.rtLim.rpmLimRamp, speedLimit, CONFIG_eCTRL_STEP_TS);
	}
}

float PMSM_FOC_GetSpeedLimit(void) {
	return gFoc_Ctrl.userLim.s_motRPMLim;
}

void PMSM_FOC_TorqueLimit(float torqueLimit) {
	if (torqueLimit > gFoc_Ctrl.hwLim.s_torqueMax) {
		torqueLimit = gFoc_Ctrl.hwLim.s_torqueMax;
	}
	gFoc_Ctrl.userLim.s_torqueLim = torqueLimit;
}
float PMSM_FOC_GetTorqueLimit(void) {
	return gFoc_Ctrl.userLim.s_torqueLim;
}

void PMSM_FOC_SeteBrkPhaseCurrent(float curr) {
	gFoc_Ctrl.userLim.s_PhaseCurreBrkLim = curr;
}

float PMSM_FOC_GeteBrkPhaseCurrent(void) {
	return gFoc_Ctrl.userLim.s_PhaseCurreBrkLim ;
}

float PMSM_FOC_GetVbusVoltage(void) {
	return gFoc_Ctrl.in.s_vDC;
}

float PMSM_FOC_GetVbusCurrent(void) {
	return gFoc_Ctrl.out.s_FilteriDC;
}

DQ_t* PMSM_FOC_GetDQCurrent(void) {
	return &gFoc_Ctrl.out.s_RealIdq;
}

bool PMSM_FOC_SetCtrlMode(u8 mode) {
	if (mode > CTRL_MODE_CURRENT_BRK) {
		PMSM_FOC_SetErrCode(FOC_Param_Err);
		return false;
	}
	gFoc_Ctrl.in.n_ctlMode = mode;
	return true;
}


u8 PMSM_FOC_GetCtrlMode(void) {
	return gFoc_Ctrl.in.n_ctlMode;
}

void PMSM_FOC_PhaseCurrLim(float lim) {
	float minCurr = min(gFoc_Ctrl.hwLim.s_PhaseCurrMax, gFoc_Ctrl.protLim.s_PhaseCurrLim);
	if (lim > minCurr) {
		lim = minCurr;
	}
	gFoc_Ctrl.userLim.s_PhaseCurrLim = lim;
	if (ABS(gFoc_Ctrl.in.s_motRPM) < 10){
		eRamp_reset_target(&gFoc_Ctrl.rtLim.phaseCurrLimRamp, lim);
	}else {
		eRamp_set_step_target(&gFoc_Ctrl.rtLim.phaseCurrLimRamp, lim, CONFIG_eCTRL_STEP_TS);
	}
}

void PMSM_FOC_RT_PhaseCurrLim(float lim) {
	float minCurr = min(gFoc_Ctrl.hwLim.s_PhaseCurrMax, gFoc_Ctrl.protLim.s_PhaseCurrLim);
	if (lim > minCurr) {
		lim = minCurr;
	}
	eRamp_init_target(&gFoc_Ctrl.rtLim.phaseCurrLimRamp, lim, CONFIG_LIMIT_RAMP_TIME, CONFIG_LIMIT_RAMP_TIME);
}

float PMSM_FOC_GetPhaseCurrLim(void) {
	return gFoc_Ctrl.userLim.s_PhaseCurrLim;
}

void PMSM_FOC_SetOpenVdq(float vd, float vq) {
	FOC_Set_vDqRamp(&gFoc_Ctrl.vdq_ctl[0], vd);
	FOC_Set_vDqRamp(&gFoc_Ctrl.vdq_ctl[1], vq);
}


bool PMSM_FOC_EnableCruise(bool enable) {
	if (enable != gFoc_Ctrl.in.b_cruiseEna) {
		float motSpd = PMSM_FOC_GetSpeed();
		if (enable && (motSpd < CONFIG_MIN_CRUISE_RPM)) { //
			PMSM_FOC_SetErrCode(FOC_NowAllowed_With_Speed);
			return false;
		}
		eRamp_init_target(&gFoc_Ctrl.in.cruiseRpmRamp, motSpd, CONFIG_ACC_TIME, CONFIG_DEC_TIME);
		gFoc_Ctrl.in.s_cruiseRPM = motSpd;
		gFoc_Ctrl.in.b_cruiseEna = enable;
	}
	
	return true;
}

bool PMSM_FOC_Is_CruiseEnabled(void) {
	return (gFoc_Ctrl.in.b_cruiseEna && (gFoc_Ctrl.out.n_RunMode == CTRL_MODE_SPD));
}

bool PMSM_FOC_Set_Speed(float rpm) {
	if (gFoc_Ctrl.in.b_cruiseEna) {
		return false;
	}
	eCtrl_set_TgtSpeed(min(ABS(rpm), gFoc_Ctrl.userLim.s_motRPMLim)*SIGN(rpm));
	return true;
}

#if 0
bool PMSM_FOC_Set_epmMode(bool epm) {
	if (epm && !gFoc_Ctrl.in.b_motEnable) {
		PMSM_FOC_SetErrCode(FOC_NotAllowed);
		return false;
	}
	if (gFoc_Ctrl.in.b_epmMode != epm) {
		if (PMSM_FOC_GetSpeed() != 0.0f) {
			PMSM_FOC_SetErrCode(FOC_NowAllowed_With_Speed);
			return false;
		}
		gFoc_Ctrl.in.epmDirection = EPM_Dir_None;
		gFoc_Ctrl.in.b_epmMode = epm;
		if (epm) {
			PMSM_FOC_SpeedLimit(nv_get_foc_params()->s_maxEpmRPM);
			eCtrl_set_TgtSpeed(0);
			PMSM_FOC_SetCtrlMode(CTRL_MODE_SPD);
		}else {
			PMSM_FOC_SetCtrlMode(CTRL_MODE_TRQ);
			PMSM_FOC_SpeedLimit(nv_get_foc_params()->s_maxRPM);
		}
	}
	return true;
}

bool PMSM_FOC_Start_epmMove(bool move, EPM_Dir_t dir) {
	if (!gFoc_Ctrl.in.b_epmMode) {
		return false;
	}
	if (move) {
		if (gFoc_Ctrl.in.epmDirection != EPM_Dir_None) {
			return false;
		}
		gFoc_Ctrl.in.epmDirection = dir;
	}else {
		gFoc_Ctrl.in.epmDirection = EPM_Dir_None;
	}
	return true;
}

EPM_Dir_t PMSM_FOC_Get_epmDir(void) {
	return gFoc_Ctrl.in.epmDirection;
}
#endif

bool PMSM_FOC_Set_Current(float is) {
	if (is > gFoc_Ctrl.userLim.s_PhaseCurrLim) {
		is = gFoc_Ctrl.userLim.s_PhaseCurrLim;
	}else if (is < -gFoc_Ctrl.userLim.s_PhaseCurrLim) {
		is = -gFoc_Ctrl.userLim.s_PhaseCurrLim;
	}
	eCtrl_set_TgtCurrent(is);
	return true;
}

bool PMSM_FOC_Set_Torque(float trq) {
	if (trq > gFoc_Ctrl.userLim.s_torqueLim) {
		trq = gFoc_Ctrl.userLim.s_torqueLim;
	}else if (trq < -gFoc_Ctrl.userLim.s_torqueLim) {
		trq = -gFoc_Ctrl.userLim.s_torqueLim;
	}
	eCtrl_set_TgtTorque(trq);
	return true;
}

void PMSM_FOC_Reset_Torque(void) {
	float real_trq = PMSM_FOC_Get_Real_Torque();
	eCtrl_reset_Torque(real_trq);
}

bool PMSM_FOC_Set_CruiseSpeed(float rpm) {
	if (PMSM_FOC_Is_CruiseEnabled()) {
		if (rpm < CONFIG_MIN_CRUISE_RPM) {
			PMSM_FOC_SetErrCode(FOC_NowAllowed_With_Speed);
			return false;
		}
		gFoc_Ctrl.in.s_cruiseRPM = min(ABS(rpm), gFoc_Ctrl.userLim.s_motRPMLim)*SIGN(rpm);
		eRamp_set_step_target(&gFoc_Ctrl.in.cruiseRpmRamp, gFoc_Ctrl.in.s_cruiseRPM, CONFIG_eCTRL_STEP_TS);
		return true;
	}
	PMSM_FOC_SetErrCode(FOC_NotCruiseMode);
	return false;
}

void PMSM_FOC_MTPA_Calibrate(bool enable) {
	if (enable) {
		gFoc_Ctrl.in.b_MTPA_calibrate = true;
		gFoc_Ctrl.in.s_manualAngle = 0;
		eCtrl_set_ebrk_time(CONFIG_MTPA_CALI_RAMP_TIME);
	}else {
		gFoc_Ctrl.in.s_manualAngle = INVALID_ANGLE;
		gFoc_Ctrl.in.b_MTPA_calibrate = false;
	}
}

void PMSM_FOC_Set_Angle(float angle) {
	gFoc_Ctrl.in.s_manualAngle = (angle);
}

void PMSM_FOC_Get_TgtIDQ(DQ_t * dq) {
	dq->d = gFoc_Ctrl.in.s_targetIdq.d;
	dq->q = gFoc_Ctrl.in.s_targetIdq.q;
}

float PMSM_FOC_GetSpeed(void) {
	return gFoc_Ctrl.in.s_motRPM;
}


void PMSM_FOC_AutoHold(bool lock) {
	if (gFoc_Ctrl.in.b_AutoHold != lock) {
		motor_encoder_lock_pos(lock);
		PI_Controller_Reset(gFoc_Ctrl.pi_lock, 0);
		if (!lock) {
			//解锁后为了防止倒溜，需要把当前
			if (gFoc_Ctrl.out.n_RunMode == CTRL_MODE_TRQ) {
				PI_Controller_Reset(gFoc_Ctrl.pi_torque, gFoc_Ctrl.in.s_targetTorque);
			}else if (gFoc_Ctrl.out.n_RunMode == CTRL_MODE_SPD) {
				PI_Controller_Reset(gFoc_Ctrl.pi_speed, gFoc_Ctrl.in.s_targetTorque);
			}
			eCtrl_reset_Torque(gFoc_Ctrl.in.s_targetTorque);
		}
		gFoc_Ctrl.in.b_AutoHold = lock;
	}
}


bool PMSM_FOC_AutoHoldding(void) {
	return gFoc_Ctrl.in.b_AutoHold;
}

static PI_Controller *_pid(u8 id) {
	PI_Controller *pi = NULL;
	if (id == PID_D_id) {
		pi = gFoc_Ctrl.pi_id;
	}else if (id == PID_Q_id) {
		pi = gFoc_Ctrl.pi_iq;
	}else if (id == PID_TRQ_id) {
		pi = gFoc_Ctrl.pi_torque;
	}else if (id == PID_Spd_id) {
		pi = gFoc_Ctrl.pi_speed;
	}
	return pi;
}

void PMSM_FOC_SetPid(u8 id, float kp, float ki, float kb) {
	if (id > PID_Max_id) {
		return;
	}
	PI_Controller *pi = _pid(id);
	if (pi != NULL) {
		pi->kp = kp;
		pi->ki = ki;
		pi->kb = kb;
	}
}

void PMSM_FOC_GetPid(u8 id, float *kp, float *ki, float *kb) {
	if (id > PID_Max_id) {
		return;
	}
	PI_Controller *pi = _pid(id);
	if (pi != NULL) {
		*kp = pi->kp;
		*ki = pi->ki;
		*kb = pi->kb;
	}
}

void PMSM_FOC_SetErrCode(u8 error) {
	if (gFoc_Ctrl.out.n_Error != error) {
		gFoc_Ctrl.out.n_Error = error;
	}
}

u8 PMSM_FOC_GetErrCode(void) {
	return gFoc_Ctrl.out.n_Error;
}

void PMSM_FOC_SetCriticalError(u8 err) {
	gFoc_Ctrl.out.n_CritiCalErrMask |= (1u << err);
}

void PMSM_FOC_ClrCriticalError(u8 err) {
	gFoc_Ctrl.out.n_CritiCalErrMask &= ~(1u << err);
}

u32 PMSM_FOC_GetCriticalError(void) {
	return gFoc_Ctrl.out.n_CritiCalErrMask;
}

void PMSM_FOC_Set_PlotType(Plot_t t) {
	gFoc_Ctrl.plot_type = t;
}
//获取母线电流和实际输出电流矢量大小
void PMSM_FOC_Calc_Current(void) {
	float vd = gFoc_Ctrl.out.s_OutVdq.d;
	float vq = gFoc_Ctrl.out.s_OutVdq.q;

	float id = gFoc_Ctrl.out.s_FilterIdq.d;
	float iq = gFoc_Ctrl.out.s_FilterIdq.q;
    /*
		根据公式（等幅值变换，功率不等）:
		iDC x vDC = 2/3(iq x vq + id x vd);
	*/
	float m_pow = (vd * id + vq * iq); //s32q10
	float id_thr = ABS(id);
	if (id_thr >= 100.0f) {
		id_thr = 100.0f;
	}
	float raw_idc = m_pow / get_vbus_float() * (1.0f - 0.2f * id_thr/100.0f);// * 1.5f * 0.66f; //s16q5
	LowPass_Filter(gFoc_Ctrl.out.s_FilteriDC, raw_idc, 0.1f);

	gFoc_Ctrl.out.s_RealCurrent = sqrtf(SQ(gFoc_Ctrl.out.s_FilterIdq.d) + SQ(gFoc_Ctrl.out.s_FilterIdq.q));

}

void PMSM_FOC_Brake(bool brake) {
	gFoc_Ctrl.in.b_eBrake = brake;
	if (gFoc_Ctrl.in.b_eBrake & gFoc_Ctrl.in.b_cruiseEna) {
		gFoc_Ctrl.in.b_cruiseEna = false;
	}
	eCtrl_brake_signal(brake);
}

