/*
 * bldc_types.h
 *
 * Created: 8/5/2021 9:40:45 AM
 *  Author: ge37vez
 */ 


#ifndef BLDC_TYPES_H_
#define BLDC_TYPES_H_

#include "atmel_start.h"
#include "control.h"
#include "motorparameters.h"
#include "statemachine.h"

// ----------------------------------------------------------------------
// 	function Pointer
// ----------------------------------------------------------------------
typedef uint8_t (*readHallSensor)(void);

// ----------------------------------------------------------------------
// 	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_PHASES_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;
	volatile bool adc_readings_ready_tic;
	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 int16_t calc_rpm;
	volatile int16_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;

// ----------------------------------------------------------------------
// 	Main BLDC Struct
// ----------------------------------------------------------------------
volatile typedef struct BLDCmotor
{
	/* Hardware */
	volatile BLDCMotor_param_t *motor_param;
	volatile MOTOR_STATE_t motor_state;
	/* Status */
	volatile MOTOR_Status motor_status;
	/* Measured Values */
	volatile MOTOR_PHASES_t Iphase_pu;
	volatile MOTOR_phase_offset_t Voffset_lsb;
	volatile float32_t VdcBus_pu, 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;
	/* Function Pointers*/
	volatile readHallSensor readHall;
} BLDCMotor_t;



#endif /* BLDC_TYPES_H_ */