//*****************************************************************************/
// @Module              FOC Speed Control
// @Filename            FSC_CTRL.H
// @Controller          XC16x Series
//
//
// @Description     This file contains references for Speed control through FOC
//
//*****************************************************************************/
#ifndef _FSC_CTRL_H_
#define _FSC_CTRL_H_

//****************************************************************************
// @Includes
//****************************************************************************

//****************************************************************************
// @Defines
//****************************************************************************
struct pi_controller                                       // PI-controller parameter            
{                                                                                
    long yn;    
    int  kp;                                               // Proportional constant          
    int  ki;        
    int  ymax;                                             // Maximal ouput limit    
    int  ymin;                                             // Minimal ouput limit    
};

// DECOUPLING
#if DAVECG_ENABLE_DECOUPLING

struct cartesian                                
{                                               
int d;                                        
int q;                                        
};

#endif


//****************************************************************************
// @Macros
//****************************************************************************

// FOC Start
//****************************************************************************
#define CTRL_VAR_DECL()\
    extern BIT gb_motor_status;\
    extern BIT gb_ctrap;\
    extern BIT gb_off;\
    extern BIT gb_on;\
    extern BIT gb_overcurrent;\
    extern C_BDATA g_status_word; \
    extern int C_SDATA g_once;\
    extern int C_SDATA g_i_counter;\
    extern int C_SDATA g_counter_positioning;\
    extern int C_SDATA g_mod_index;\
    extern int C_SDATA g_iq_comp_ref;\
    extern int C_SDATA g_id_comp_ref;\
    extern int C_SDATA g_adc_off[];\
    extern int C_SDATA g_voltage_angle;\
    extern int C_SDATA g_counter0;\
    extern int C_SDATA g_rotor_angle_calibration;\
    extern int C_SDATA g_phi_rotor;\
    extern int C_SDATA g_phase_current_ref;\
    extern int C_SDATA g_i_phase_s;\
    extern int C_SDATA g_i_phase_t;\
    extern int C_SDATA g_i_alpha;\
    extern int C_SDATA g_i_beta;\
    extern int C_SDATA g_id_comp;\
    extern int C_SDATA g_iq_comp;\
    extern int C_SDATA g_f_d_comp;\
    extern int C_SDATA g_f_q_comp;\
    extern int C_SDATA g_phi_control;\
    extern int C_SDATA g_test_speed_kp;\
    extern int C_SDATA g_test_speed_ki;\
    extern int C_SDATA g_test_speed_ymax;\
    extern int C_SDATA g_test_speed_ymin;\
    extern int C_SDATA g_test_current_kp;\
    extern int C_SDATA g_test_current_ki;\
    extern int C_SDATA g_test_current_ymax;\
    extern int C_SDATA g_test_current_ymin;\
    extern int C_SDATA g_trap_reset;\
    extern int C_SDATA g_increment_free;\
    extern int C_SDATA g_encoder_pos;\
    extern int C_SDATA g_nv_start_ref0;\
    extern int C_SDATA g_nv_end_ref;\
    extern int C_SDATA g_nv_start_ref;\
    extern int C_SDATA g_speed_ref;\

    extern unsigned int C_SDATA g_adc_start;\
    extern unsigned int C_SDATA g_encoder_meass[];\
    extern unsigned int C_SDATA g_circ_index;\
    extern int C_SDATA g_speed_enc;\
    extern long C_SDATA g_position_ref_user;\
    extern unsigned long C_SDATA g_time_step;\
    extern unsigned long C_SDATA g_counter1;\
    extern unsigned long C_SDATA g_ramp_up_time;\
    extern struct pi_controller C_SDATA g_pi_current_d;\
    extern struct pi_controller C_SDATA g_pi_current_q;\
    extern struct pi_controller C_SDATA g_pi_speed;\
    extern struct cartesian C_SDATA E_dec;\
    extern int C_SDATA F_d_dec;\
    extern int C_SDATA F_q_dec; 
               

#define CTRL_FUNC_DECL()\
    extern void motor_start(void);\
    extern void motor_stop(void);\
    extern void speed_ref_ramp(void); \
    extern void angle_calibration(void);\
    extern void blink_led(void);\
    extern void modulator(int ampl, int phi);\
    extern int pi_con_pos_co(int *pi_parameter,int reference,int actual);\
    extern int clarke_trans_co(int I_phase_s, int I_phase_t , int *ia);\
    extern int park_trans_co(int e_a,int e_b,int phi,int *a_b);\
    extern int cart_polar_conv_co(int real,int imaginar,int *phase);\
    extern int P_controller_co(long *x,int Kp);\
    extern void modulator_co(int ampl, int phi);\
    extern long generator_co(long *x,long y);\
    extern int pi_controller64(long *pi_parameter,int reference,int actual);\
    extern int mul3_exp_co(int x,int y, int z, int n);\
    extern int adc_offset(int);\
    extern int decoupling_co(int ein_a0,int ein_b0,int ein_c,int *ein_d,int *aus_b);\
    extern void nv_ref_ramp_generation(void);

//****************************************************************************

CTRL_VAR_DECL()
CTRL_FUNC_DECL()
#if DAVECG_CONTROL_PANEL_ENABLE
COMM_FUNC_DECL()
#endif

#if DAVECG_KEIL
void ADC_viConv(void);
#endif // (KEIL == 1)
#if DAVECG_TASKING
    interrupt (ADC_C_INT) _localbank(-1)_cached void ADC_viConv(void);
#endif
//*************************************************************************************************
#if DAVECG_KEIL

#define ADC_ERROR_BANK1_SIG()\
void ADC_viError(void) interrupt ADC_E=CACHED using _FAST_ABANK1_ \
{

#define ADC_ERROR_BANK2_SIG()\
void ADC_viError(void) interrupt ADC_E_INT using Reg_bank_ADC \
{

#endif // DAVECG_KEIL

#if DAVECG_TASKING

#define ADC_ERROR_BANK1_SIG()\
interrupt (ADC_E_INT) _localbank(-1)_cached void ADC_viError(void) \
{

#define ADC_ERROR_BANK2_SIG()\
interrupt (ADC_E_INT) using (Reg_bank_ADC) void ADC_viError(void) \
{

#endif // DAVECG_TASKING

//******************************

#define HALF_REVOLUTION (int)ENCODER_IMP*2
#define ONE_REVOLUTION (int)ENCODER_IMP*4
#define CONDITION_OPERATOR >
#define POSITION_EXP 4
#define DUTY_CYCLE_THRESHOLD PWPD

//*************************************************************************************************

INLINE void FOC_PARAM_INIT(void)
{
    g_nv_start_ref		=	MOTOR_START_REF;
    g_nv_end_ref		=	MOTOR_END_REF;
    g_phase_current_ref =	MOTOR_CURRENT_REF;
    g_ramp_up_time		=	RAMP_UP_TIME;
	g_trap_reset		=	1;
	gb_motor_status		=	CONTROL_PANEL_ENABLE;
}

INLINE void INIT_CCU6_VAR(void)
{

    CCU6_T12PR   =  PULSE_PERIOD;
    CCU6_T13PR   =  T13_PERIOD;
	CCU6_T12DTC  =  (CCU6_T12DTC & 0xFFC0) | DEAD_TIME;
	CCU6_PSLR    =  PASSIVE_STATE;
	CCU6_TCTR4  =  0x4040;      // load CCU6 timer control register 4
}

INLINE void INIT_PI_VAR(void)
{
	g_test_speed_kp    = INIT_SPEED_KP; 
    g_test_speed_ki    = INIT_SPEED_KI; 
    g_test_speed_ymax  = PIC_SPEED_YMAX; 
    g_test_speed_ymin  = PIC_SPEED_YMIN; 
    g_test_current_kp    = INIT_CURRENT_KP; 
    g_test_current_ki    = INIT_CURRENT_KI; 
    g_test_current_ymax  = PIC_CURRENT_YMAX; 
    g_test_current_ymin  = PIC_CURRENT_YMIN;
}

INLINE void SET_PI_VAR(void)
{
	g_pi_current_d.kp   = g_test_current_kp; 
	g_pi_current_d.ki   = g_test_current_ki; 
	g_pi_current_d.ymax = g_test_current_ymax; 
	g_pi_current_d.ymin = g_test_current_ymin; 
	g_pi_current_q.kp   = g_test_current_kp; 
	g_pi_current_q.ki   = g_test_current_ki; 
	g_pi_current_q.ymax = g_test_current_ymax; 
	g_pi_current_q.ymin = g_test_current_ymin; 
	g_pi_speed.kp   = g_test_speed_kp; 
	g_pi_speed.ki   = g_test_speed_ki; 
	g_pi_speed.ymax = g_test_speed_ymax; 
	g_pi_speed.ymin = g_test_speed_ymin;
}

INLINE void INIT_CTRL_VAR(void)
{
    gb_motor_status = 1;
    g_rotor_angle_calibration = 0x0001;
    g_once = 0x0; 
    g_status_word = 0x0002; 
    g_phase_current_ref = 536;
}

//*************************************************************************************************


INLINE void MOTOR_RAMP_GEN(void)
{
	nv_ref_ramp_generation();
}


INLINE void TRAP_RESET(void)
{
    if (g_trap_reset == 1) 
    { 
        g_trap_reset = 0x0000; 
        gb_ctrap = 0; 
    }
}

INLINE void BLINK_LED(void) 
{
    blink_led();
}

INLINE void SET_TRAP(void)
{
    gb_ctrap = 1;
}


INLINE void SET_MONITOR_TRAP(void)
{
    motor_stop(); 
    gb_motor_status = 1; 
    SET_TRAP();
}

INLINE void MOTOR_STOP(void)
{
	motor_stop();
}

INLINE void MONITOR_MOTOR_CONTROL(void) 
{
    if (gb_ctrap) 
    { 
        gb_motor_status = 1; 
    } 
    else 
    { 
        if (gb_motor_status == 0) 
        { 
            motor_start(); 
        } 
        else 
        { 
            MOTOR_STOP();
        } 
    }
}

//*************************************************************************************************
      
INLINE void SET_ADC_SRC_DST_PTR(void)
{
    SRCP7 = C_SOF(g_adc_start);
    DSTP7 = C_SOF(ADC_CTR0);
}

INLINE void SET_ADC_CTR2(void)
{
#if CPU_FREQUENCY <= 20
    ADC_CTR2 = 0x0000;
    ADC_CTR2IN = 0x0000;
#endif // CPU_FREQUENCY <= 20
}

INLINE void SET_ADC_FST_INT(void)
{
#if REG_BANK_ADC == 1
    SET_FINT_CTRL_REG(ADC_viConv, BNKSEL0)
#endif // REG_BANK_ADC == 1
}

//*************************************************************************************************

INLINE void ADC_INIT3_CBLOCK(void)
{
    SRCP7 = C_SOF(g_adc_start);
    DSTP7 = C_SOF(ADC_CTR0);

#if REG_BANK_ADC == 1
    SET_FINT_CTRL_REG(ADC_viConv, BNKSEL0)
#endif // REG_BANK_ADC == 1

#if CPU_FREQUENCY <= 20
    ADC_CTR2 = 0x0000;
    ADC_CTR2IN = 0x0000;
#endif // CPU_FREQUENCY <= 20

}

//*************************************************************************************************

INLINE void GPT1_TMR22_CBLOCK(void)
{
//GPT1 TIMER2 Speed calculation Block
    GPT12E_T2 += T2_PERIOD; 
	g_speed_enc  = (GPT12E_T3 - g_encoder_meass[g_circ_index]) << SHIFT_VAL; 
	g_encoder_meass[g_circ_index] = GPT12E_T3; 
	g_circ_index++; 
    g_circ_index &= CIRC_INDEX_VAL;

//GPT1 TIMER22 Speed control Block
#if DAVECG_KEIL
  if((gb_off == 0) && (g_rotor_angle_calibration == 2))
  {
    g_iq_comp_ref = pi_controller64(&g_pi_speed.yn,g_speed_ref,g_speed_enc);
    C_CoLOAD_0_1(0, g_iq_comp_ref);
    C_CoMIN_0_1(0, CURRENT_MAX);
    C_CoMAX_0_1(0, -CURRENT_MAX);
    g_iq_comp_ref = C_CoSTOREMAS();
    g_iq_comp_ref = C_CoSTOREMAS();
  }
#endif

#if DAVECG_TASKING
if((gb_off == 0) && (g_rotor_angle_calibration == 2))
{
g_iq_comp_ref = pi_controller64(&g_pi_speed.yn,g_speed_ref,g_speed_enc);
Int_CoLimit(0,g_iq_comp_ref,-CURRENT_MAX,CURRENT_MAX);
g_iq_comp_ref = _CoSTOREMAS();
}
#endif

//Over Current Check
#if DAVECG_CURRENT_SENSE
    if((gb_off == 0) && (g_rotor_angle_calibration == 2)) 
    { 
        if((g_iq_comp >= OVER_CURRENT_MAX)||((g_iq_comp <= -OVER_CURRENT_MAX))) 
        { 
            g_i_counter++; 
            if(g_i_counter == OVER_CURRENT_TIME) 
            { 
                motor_stop(); 
                gb_motor_status = 1; 
                gb_overcurrent = 1; 
            } 
        } 
        else 
        { 
            if(g_i_counter > 0) 
            { 
                g_i_counter--; 
            } 
        } 
    }
#endif // (CURRENT_SENSE == 1)  
}

//*************************************************************************************************
// ROTOR ANGLE CALCULATION

INLINE void ROTOR_ANGLE_CALCULATION(void)
{
    #if DAVECG_TASKING
      if((int)(GPT12E_T3 - g_encoder_pos) >  HALF_REVOLUTION)
      {
        g_encoder_pos += ONE_REVOLUTION;
      }
      if((int)(GPT12E_T3 - g_encoder_pos) < -HALF_REVOLUTION)
      {
        g_encoder_pos -= ONE_REVOLUTION;
      }
      _CoMULsu((GPT12E_T3 - g_encoder_pos),ROTOR_ANGLE_FACTOR);
      _CoSHR(16 - ROTOR_ANGLE_EXP);
      g_phi_rotor = _CoSTOREMAL();

    #elif DAVECG_KEIL
      if((int)(GPT12E_T3 - g_encoder_pos) >  HALF_REVOLUTION)
      {
        g_encoder_pos += ONE_REVOLUTION;
      }
      if((int)(GPT12E_T3 - g_encoder_pos) < -HALF_REVOLUTION)
      {
        g_encoder_pos -= ONE_REVOLUTION;
      }
     _mac_(CoMULsu ,(GPT12E_T3 - g_encoder_pos),ROTOR_ANGLE_FACTOR);
      g_phi_rotor = _lmac_() >> (16 - ROTOR_ANGLE_EXP);
    #endif
}

//*************************************************************************************************
//PHASE CURRENT 

INLINE void PHASE_CURRENT_READ(void)
{
  if(g_adc_start == 0xA692)
  {
    g_i_phase_s = g_adc_off[0] - (ADC_DAT   & 0x0FFC);
    g_i_phase_t = g_adc_off[1] - (ADC_DAT2  & 0x0FFC);
  }
  else
  {
    g_i_phase_s = g_adc_off[0] - (ADC_DAT2  & 0x0FFC);
    g_i_phase_t = g_adc_off[1] - (ADC_DAT   & 0x0FFC);
  }
}

//*************************************************************************************************

INLINE void ROTOR_ANGLE_CALLIBRATION(void)
{
	angle_calibration();
}

//*************************************************************************************************
// 3 / 2 TRANSFORMATION

INLINE void CLARKE_TRANSFORMATION(void)
{
    g_i_beta  = clarke_trans_co(g_i_phase_s, g_i_phase_t, &g_i_alpha);
}
//*************************************************************************************************

// ROTOR ORIENTATION
INLINE void PARK_TRANSFORMATION(void)
{
    g_id_comp = park_trans_co(g_i_alpha,g_i_beta,g_phi_rotor,&g_iq_comp);
}

//*************************************************************************************************

// CURRENT CONTROL (D COMPONENT)
INLINE void CURRENT_CONTROL_FLUX_COMPONENT(void)
{
    g_f_d_comp  = pi_controller64(&g_pi_current_d.yn,g_id_comp_ref,g_id_comp);
}

//*************************************************************************************************

// CURRENT CONTROL (Q COMPONENT)
INLINE void CURRENT_CONTROL_TORQUE_COMPONENT(void)
{
    g_f_q_comp  = pi_controller64(&g_pi_current_q.yn,g_iq_comp_ref,g_iq_comp);
}

//*************************************************************************************************
// DECOUPLING

INLINE void ENABLE_DECOUP(void)
{
#if ENABLE_DECOUPLING == 1
E_dec.d = mul3_exp_co(g_id_comp,g_speed_enc,DECOUP_FACTOR,DECOUP_EXP);
E_dec.q = mul3_exp_co(g_iq_comp,g_speed_enc,DECOUP_FACTOR,DECOUP_EXP);
F_d_dec = decoupling_co(g_f_d_comp,g_f_q_comp,g_speed_enc,&E_dec.d,&F_q_dec);
#endif
}

//*************************************************************************************************
// STATOR ORIENTATION

INLINE void CARTESIAN_TO_POLAR_CONVERSION(void)
{
#if ENABLE_DECOUPLING == 1
    g_mod_index = cart_polar_conv_co(F_d_dec,F_q_dec,&g_phi_control);
#else
    g_mod_index = cart_polar_conv_co(g_f_d_comp,g_f_q_comp,&g_phi_control);
#endif 
}
//*************************************************************************************************
INLINE void MODULATOR_CO(void)
{
  modulator_co(g_mod_index, g_voltage_angle);
  CCU6_TCTR4    = 0x0040;
}

//*************************************************************************************************

INLINE void TRACE(void)
{
#if DAVECG_CONTROL_PANEL_ENABLE
  trace();
#endif
}

//*************************************************************************************************
//CHANGE  ADC TRIGGER

INLINE void CHANGE_ADC_TRIGGER(void)
{
  if(g_speed_ref > 0)
  {
    if((CCU6_CC61SR < DUTY_CYCLE_THRESHOLD) && (CCU6_CC62SR > (PWPD / 2)))
    {
      ADC_DAT2   = 0x2000;
      g_adc_start  = 0xA694;
    }
    if((CCU6_CC62SR < DUTY_CYCLE_THRESHOLD) && (CCU6_CC62SR < CCU6_CC61SR))
    {
      ADC_DAT2   = 0x4000;
      g_adc_start  = 0xA692;
    }
  }
  else
  {
    if((CCU6_CC62SR < DUTY_CYCLE_THRESHOLD) && (CCU6_CC61SR > (PWPD / 2)))
    {
      ADC_DAT2   = 0x4000;
      g_adc_start  = 0xA692;
    }
    if((CCU6_CC61SR < DUTY_CYCLE_THRESHOLD) && (CCU6_CC61SR < CCU6_CC62SR))
    {
      ADC_DAT2   = 0x2000;
      g_adc_start  = 0xA694;
    }
  } 
}
//*************************************************************************************************

INLINE void ADC_ISSR(void)
{

ROTOR_ANGLE_CALCULATION();
PHASE_CURRENT_READ();
if(g_rotor_angle_calibration == 1)
{
    ROTOR_ANGLE_CALLIBRATION();
}
else
{
    CLARKE_TRANSFORMATION();
    PARK_TRANSFORMATION();
    CURRENT_CONTROL_FLUX_COMPONENT();
    CURRENT_CONTROL_TORQUE_COMPONENT();
    ENABLE_DECOUP();
    CARTESIAN_TO_POLAR_CONVERSION();
    g_voltage_angle  = g_phi_control + g_phi_rotor;
}
MODULATOR_CO();
TRACE();
CHANGE_ADC_TRIGGER();
g_increment_free = 1;
}
//*************************************************************************************************
// FOC End
//*************************************************************************************************

#endif // _FSC_CTRL_H_
