/*
 * bldc.h
 *
 * Created: 10/03/2021 14:38:14
 *  Author: Nick-XMG
 */ 

#ifndef BLDC_H_
#define BLDC_H_

// ----------------------------------------------------------------------
// 	header files
// ----------------------------------------------------------------------
#include "arm_math.h"
#include "atmel_start.h"
#include "control.h"
#include "motor_params.h"

/* if the Hall sensor reads 0x0 or 0x7 that means either one of the hall sensor is damaged or disconnected*/
#define INVALID_HALL_0              (0U)    
#define INVALID_HALL_7              (7U)
	
// ----------------------------------------------------------------------
// 	ADC Parameters
// ----------------------------------------------------------------------
#define ADC_VOLTAGE_REFERENCE		(3.3f)
#define ADC_RESOLUTION				(12)
#define ADC_MAX_COUNTS				(1<<ADC_RESOLUTION)
#define ADC_LSB_SIZE				(ADC_VOLTAGE_REFERENCE/ADC_MAX_COUNTS)

// ----------------------------------------------------------------------
// Define the control and PWM frequencies:
// ----------------------------------------------------------------------
// 16kHz is the maximum frequency according to the calculation duration in the mode run and spin.
#define DEVICE_MCU_FREQUENCY_Hz        (100000000U)
#define DEVICE_SPEEDTC_DIV			   (4U)
#define DEVICE_SPEEDTC_FREQUENCY_Hz    (100000000U/DEVICE_SPEEDTC_DIV)
#define DEVICE_PWM_FREQUENCY_kHz       (25.0f)
#define DEVICE_ISR_FREQUENCY_kHz       DEVICE_PWM_FREQUENCY_kHz
#define DEVICE_ISR_PERIOD_Sec		   (0.001f/DEVICE_ISR_FREQUENCY_kHz)


// ----------------------------------------------------------------------
// Define the device quantities (voltage, current, speed)
// ----------------------------------------------------------------------
#define DEVICE_DC_VOLTAGE_V					24.0f   // max. ADC bus voltage(PEAK) [V]
#define DEVICE_SHUNT_CURRENT_A				2.5f    // phase current(PEAK) [A]
#define CURRENT_SENSOR_SENSITIVITY			0.4f    //V/A
#define ONEON_CURRENT_SENSOR_SENSITIVITY	2.5f    //V/A

// ----------------------------------------------------------------------
// 	Type Definitions
// ----------------------------------------------------------------------
volatile typedef struct
{
	volatile float32_t A;          // Phase A
	volatile float32_t B;          // Phase B
	volatile float32_t C;          // Phase C
	volatile float32_t Bus;        // Currently Active Phase Current
} MOTOR_3PHASES_t;

volatile typedef struct
{
	volatile int16_t A;          // Phase A measured offset
	volatile int16_t B;          // Phase B measured offset
} MOTOR_phase_offset_t;

volatile typedef struct timerflags
{
	volatile bool pwm_cycle_tic;
	volatile bool current_loop_tic;
	volatile bool control_loop_tic; //! Is motor synchronized? Does not have any meaning when motorStopped is TRUE.
	volatile bool motor_telemetry_flag;
}	TIMERflags_t;

volatile typedef struct
{
	volatile PI_t	Pi_Idc;
	volatile PID_t	Pid_Speed;
	volatile PI_t	Pi_Pos;
}	MOTOR_Control_Structs;

volatile typedef struct
{
	volatile uint8_t desiredDirection;	//! The desired direction of rotation.
	volatile uint8_t directionOffset;
	volatile float32_t desired_torque;
	volatile int16_t   desired_speed;
	volatile int16_t   desired_position;
	volatile float32_t max_torque;
	volatile float32_t max_current;
	volatile int16_t   max_velocity;
}	MOTOR_Setpoints;

volatile typedef struct
{
	volatile uint8_t actualDirection;	//! The actual direction of rotation.
	volatile uint16_t duty_cycle;
	volatile float32_t calc_rpm;
	volatile int32_t Num_Steps;
	/* Hall States */
	volatile uint8_t prevHallPattern;
	volatile uint8_t currentHallPattern;
	volatile uint8_t nextHallPattern;
	/* Commutation State */
	volatile uint8_t cur_comm_step;
	volatile uint8_t prev_comm_step;
}	MOTOR_Status;

// ----------------------------------------------------------------------
// 	Function Pointers
// ----------------------------------------------------------------------
typedef uint8_t (*ReadHallFunc)(void);
typedef void (*DisableMotorFunc)(void);
typedef void (*SetMotorDutyCycle)(uint16_t);

volatile typedef struct BLDCmotor
{
	/* Hardware */
	const Tcc *hw;
	const uint16_t *motor_commutation_Pattern;
	/* Status */
	MOTOR_Status motor_status;
	/* Measured Values */
	volatile MOTOR_3PHASES_t Iphase_pu;
	volatile MOTOR_phase_offset_t Voffset_lsb;
	volatile float32_t VdcBus_pu;
	volatile float32_t VoneByDcBus_pu;
	/* Motor Flags */
	volatile TIMERflags_t timerflags;	
	volatile uint8_t regulation_loop_count;
	/* Controllers */
	volatile MOTOR_Control_Structs controllers;	
	/* Setpoints */	
	volatile MOTOR_Setpoints motor_setpoints;		
	/* Functions */
	ReadHallFunc ReadHall;	
	DisableMotorFunc DisableMotor;
	SetMotorDutyCycle SetDutyCycle;
} BLDCMotor_t;


// ----------------------------------------------------------------------
// 	global variables
// ----------------------------------------------------------------------

static const uint8_t HALL_PATTERN_ARRAY[16]		= {0, 5, 3, 1, 6, 4, 2, 0, 0, 3, 6, 2, 5, 1, 4, 0 };
static const uint8_t MOTOR_COMMUTATION_STEPS[8] = {9, 1, 3, 2, 5, 6, 4, 9};
	
volatile BLDCMotor_t Motor1;
volatile BLDCMotor_t Motor2;
volatile BLDCMotor_t Motor3;

// ----------------------------------------------------------------------
// 	functions
// ----------------------------------------------------------------------
void BldcInitStruct(BLDCMotor_t *motor);
void BldcInitFunctions(void);



void select_active_phase(BLDCMotor_t *Motor, uint8_t hall_state);
void read_zero_current_offset_value(void);
int32_t adc_sync_read_channel(struct adc_async_descriptor *const descr, const uint8_t channel, uint8_t *const buffer, const uint16_t length);
static uint16_t adc_read(struct adc_async_descriptor *const descr, const uint8_t channel);
void exec_commutation(void);
uint8_t get_dir_hall_code(void);
uint8_t get_hall_state(void);

uint8_t HALLPatternGet(void);
uint8_t PDEC_HALLPatternGet(void);
void calculate_motor_speed(void);
void DisableMotor(BLDCMotor_t *motor);
void BLDC_runSpeedCntl(BLDCMotor_t *motor, volatile float speedfbk, volatile float speedRef);
void BLDC_runCurrentCntl(BLDCMotor_t *motor, volatile float curfbk, volatile float curRef);
void BLDC_runPosCntl(BLDCMotor_t *motor, int16_t posfbk, int16_t posRef);

// ----------------------------------------------------------------------
//  Functions used with function pointers
// ----------------------------------------------------------------------
uint8_t readM1Hall(void);
uint8_t readM2Hall(void);
uint8_t readM3Hall(void);
void DisableM1GateDrivers(BLDCMotor_t *motor);
void DisableM2GateDrivers(BLDCMotor_t *motor);
void DisableM3GateDrivers(BLDCMotor_t *motor);
void SetM1DutyCycle(uint16_t duty);
void SetM2DutyCycle(uint16_t duty);
void SetM3DutyCycle(uint16_t duty);

// ----------------------------------------------------------------------
//  all controller objects, variables and helpers:
// ----------------------------------------------------------------------

//Motor2.ReadHall = readM2Hall;
//Motor3.ReadHall = readM3Hall;



#endif /* BLDC_H_ */