#include "main.h"
#include "motorControl.h"

#define MODEL_NAME pmsm_target
#define INIT _init()
#define ISR	_isr(0)
#define ISR_DEC _isr(double)
#define CONCAT(A,B) A ## B
#define PYSIM_INIT(A,B) CONCAT(A, B)
#define PYSIM_ISR(A,B) CONCAT(A, B)

extern void  PYSIM_INIT(MODEL_NAME, INIT);
extern void  PYSIM_ISR(MODEL_NAME,ISR_DEC);

#define OFFSET_THETA	800

extern void SystemClock_Config(void);
extern void findFirstIndex();
extern void MX_TIM1_Init(void);
extern void MC_FOC_Start_PWM_driving(void);
extern void  MC_FOC_EnableInputs();

extern int32_t quadPos, theta_elec;
extern q31_t iq_mes;
extern int first_index_reached;
extern TIM_HandleTypeDef TimHandle_period ;
extern 	uint16_t	potentiometre;
extern uint16_t Ia_mes, Ib_mes, Ic_mes;
extern int32_t	Ia_mes_ext, Ib_mes_ext;
extern 	q31_t alpha, beta, sinVal, cosVal;

int16_t speed_mes;

uint32_t pot;
int16_t Ia_bias, Ib_bias;
uint16_t g_ADCBuffer[3];
int32_t pulse=-1;

void (*rxCompleteCallback) (void);
void can_callback(void);

CAN_Message      rxMsg;
CAN_Message      txMsg;
long int        counter = 0;

uint8_t* aTxBuffer[2];

modbusHandler_t ModbusH2;
uint16_t ModbusDATA2[8];


xSemaphoreHandle xSemaphore_Fast = NULL;
xSemaphoreHandle xSemaphore_Slow = NULL;
xQueueHandle qh = NULL;
extern q31_t  iq_err, iq_cde;
int32_t theta_elec_ex;
int32_t tab_speed[5000];
int FC1, FC2;

extern double potentiometre_pysim;
extern double speed_pysim;
extern double Ia_pysim;
extern double Ib_pysim;
extern double theta_elec_pysim;
extern double duty1_pysim, duty2_pysim, duty3_pysim;
extern double Id_pysim;
extern double Iq_pysim;
extern double pulse_pysim;

static volatile int16_t g_last_applied_speed_rpm = 0;
static volatile int16_t g_pending_limit_speed_rpm = 0;
static volatile uint8_t g_limit_command_pending = 0U;
static volatile uint16_t g_limit_trigger_pin = 0U;

static void ApplySpeedCommand(int16_t rpm, const char *origin);
static int16_t DetermineOppositeSpeed(uint16_t gpio_pin);


#define TAILLE 500
int tab_id[TAILLE];
int tab_iq[TAILLE];
int tab_vit[TAILLE];

// Déclaration en entête de fichier (hors de toute fonction)
int16_t rpm = 100; // La valeur initiale peut être 0



static void ApplySpeedCommand(int16_t rpm, const char *origin)
{
	if (rpm > 500) {
		rpm = 500;
	} else if (rpm < -500) {
		rpm = -500;
	}

	g_last_applied_speed_rpm = rpm;
	pulse = (int32_t)rpm;

	if (origin == NULL) {
		origin = "CMD";
	}

	term_printf("[CMD %s] %d rpm\r\n", origin, rpm);
}

static int16_t DetermineOppositeSpeed(uint16_t gpio_pin)
{
	if (g_last_applied_speed_rpm > 0) {
		return -500;
	}

	if (g_last_applied_speed_rpm < 0) {
		return 500;
	}

	if (gpio_pin == GPIO_PIN_4) {
		return 500;
	}

	if (gpio_pin == GPIO_PIN_5) {
		return -500;
	}

	return -g_last_applied_speed_rpm;
}

//============================================================================
static void Fast_Task(void *pvParameters)
{
	vTaskDelay(5);
	Ia_bias=Ia_mes;
	Ib_bias=Ib_mes;
	int cnt_5 = 4;
	int16_t signe;
	int index=0;
	static int compteur = 0;
	for (;;)
	{

		if (first_index_reached == 0)
			{

			#if USE_MOTOR
				findFirstIndex();	// stm32F446_nucleo_ihm07m1_enib.c
			#else
				first_index_reached = 1;
			#endif

			}
		else
			{

		HAL_GPIO_WritePin(GPIOC, GPIO_PIN_9, 1);		// PC9 MES PER 1 --> To profile function
		//---------------------------------------------------
		potentiometre_pysim=(double)rpm; //#################################"
		pulse_pysim = (double)pulse;

		//---------------------------------------------------
 		quadPos = quadEncoder_GetPos16();			// cf quadEncoder.c
		signe=((int16_t)quadPos+OFFSET_THETA);

		if (signe>8000)
		{quadPos = quadPos + OFFSET_THETA - 8000;}
		else
		{quadPos = quadPos + OFFSET_THETA;}

		theta_elec=quadPos%2000 ;	//theta_elec=quadPos/POLE_PAIR; // [0 8000] --> [0 2000]
		theta_elec_ex=(int32_t)(theta_elec)*16; // [0-32000]

		theta_elec_pysim=theta_elec_ex;
		//........................................................

		Ia_mes_ext=((int32_t)Ia_mes)-Ia_bias;
		Ib_mes_ext=((int32_t)Ib_mes)-Ib_bias;


		Ia_pysim=Ia_mes_ext;
		Ib_pysim=Ib_mes_ext;

		//........................................................

	    if (cnt_5 == 0)
	    {

			//Inports.pulse=pulse;
	    	speed_mes=-quadEncoder_GetSpeed();
	    	speed_pysim=speed_mes;
	    	cnt_5 = 4;

	    	if(index < 5000)
	    	{
	    		tab_speed[index]=speed_mes;
	    		index++;
	    	}

	    }
	    cnt_5--;
	    PYSIM_ISR(MODEL_NAME,ISR);
 		// Update Duty Cycle
		pwmSetDutyCycle((uint16_t)duty1_pysim,(uint16_t)duty2_pysim,(uint16_t)duty3_pysim);

		HAL_GPIO_WritePin(GPIOC, GPIO_PIN_9, 0);		// PC9
		xSemaphoreGive( xSemaphore_Slow);

			}

	xSemaphoreTake( xSemaphore_Fast, portMAX_DELAY );
	}
}
//############################################################################
int modbus_log[1000];

void ModbusUserSlave_Task(void *argument)
{
 static int i = 0;

  for(;;)
  {

	xSemaphoreTake(ModbusH2.ModBusSphrHandle , portMAX_DELAY);
	//HAL_GPIO_WritePin(LD2_GPIO_Port, LD2_Pin, ModbusH2.u16regs[0] & 0x1); // UTILISATION DU MESSAGE REçU

	ModbusH2.dts_stm_rpi[0]=i++;

	if( ModbusH2.u8Buffer[1] == 16 ) //  Func : Write Multiple Registers(16)
	{
		term_printf("modbus : %d %d\n\r",ModbusH2.u16regs[0],ModbusH2.u8Buffer[1]);
		modbus_log[(i++)%1000]=ModbusH2.u16regs[0];
	}

	xSemaphoreGive(ModbusH2.ModBusSphrHandle);
	xSemaphoreTake( xSemaphore_Slow, portMAX_DELAY );
	vTaskDelay(200);
  }

}
//############################################################################

//============================================================================
//	>>>>>>>>>>>>>>>>>>>>>>>>>>	MAIN  <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
//============================================================================
int main(void){
  HAL_Init();
  SystemClock_Config();

  uart1_Init();
  uart2_Init();
  adc1_Init();

  quadEncoder_Init();
  pwmTimer_Init();


  tickTimerInit(FAST_TASK_COUNT_PERIOD);

  first_index_reached=0;
  MC_FOC_Nucleo_Init();
  MC_FOC_Start_PWM_driving();
  pwmSetDutyCycle(420,420,420);
  HAL_GPIO_WritePin(GPIOB,GPIO_PIN_2,GPIO_PIN_SET); //BSP_X_NUCLEO_FAULT_LED_ON();
  MC_FOC_EnableInputs();


  //######################################################################
  ModbusH2.uModbusType = MB_SLAVE;
  ModbusH2.port =  &huart1;
  ModbusH2.u8id = 17;	// ADDRESS ######################################
  ModbusH2.u16timeOut = 1000;
  ModbusH2.EN_Port = NULL;
  ModbusH2.u16regs = ModbusDATA2;
  ModbusH2.u16regsize= sizeof(ModbusDATA2)/sizeof(ModbusDATA2[0]);
  //Initialize Modbus library
  ModbusH2.xTypeHW = USART_HW;
  ModbusInit(&ModbusH2);
  ModbusStart(&ModbusH2); //Start capturing traffic on serial Port

  HAL_Delay(100);

  PYSIM_INIT(MODEL_NAME, INIT);


  //--------------------------------------------
  // 				FREERTOS
  //--------------------------------------------


 xTaskCreate( Fast_Task, ( const portCHAR * ) "Fast_Task", 512, NULL, tskIDLE_PRIORITY+10, NULL );
 xTaskCreate( ModbusUserSlave_Task, ( const portCHAR * ) "USER TASK SLAVE", 512, NULL, tskIDLE_PRIORITY+7, NULL );


  vSemaphoreCreateBinary(xSemaphore_Fast);
  xSemaphoreTake( xSemaphore_Fast, portMAX_DELAY );

  vSemaphoreCreateBinary(xSemaphore_Slow);
  xSemaphoreTake( xSemaphore_Slow, portMAX_DELAY );


  __HAL_TIM_ENABLE_IT(&TimHandle_period,TIM_IT_UPDATE);
  HAL_TIM_OC_Start(&TimHandle_period, TIM_CHANNEL_1);
  HAL_ADC_Start_DMA(&hadc1, (uint32_t*)g_ADCBuffer, 3);


  vTaskStartScheduler();

  return 0;
}
//============================================================================
//		INTERRUPTION CALLBACK ON TIMER PERIOD
//============================================================================
void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
{

	static BaseType_t xHigherPriorityTaskWoken;

	if (htim->Instance==TIM3)	// Fast Task
	{
		xSemaphoreGiveFromISR( xSemaphore_Fast,&xHigherPriorityTaskWoken );
		portYIELD_FROM_ISR( xHigherPriorityTaskWoken );
	}


}
//====================================================================
//			INTERRUPT CALLBACK ON CAN RECEIVE
//====================================================================
void can_callback(void)
{
	CAN_Message msg_rcv;
	int i=0;

	can_Read(&msg_rcv);
	txMsg.id=0x55;			// Identifiant du message à envoyer

	for(i=0;i<8;i++)
	{
	txMsg.data[i]=msg_rcv.data[i]+1;
	}
	txMsg.len=8;			// Nombre d'octets à envoyer
	txMsg.format=CANStandard;
	txMsg.type=CANData;

	can_Write(txMsg);
}
//============================================================================
//		INTERRUPTION EXTI --> BLUE BUTTON / INDEX / FC1 / FC2
//============================================================================
void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin)
{
	if(GPIO_Pin==GPIO_PIN_13)
	{
	 MC_FOC_Nucleo_Init();
	 first_index_reached=0;
	 MC_FOC_Start_PWM_driving();
	 pwmSetDutyCycle(420,420,420);
	 HAL_GPIO_WritePin(GPIOB,GPIO_PIN_2,GPIO_PIN_SET);//BSP_X_NUCLEO_FAULT_LED_ON();
	 MC_FOC_EnableInputs();
	 __HAL_TIM_ENABLE_IT(&TimHandle_period,TIM_IT_UPDATE); // ??
	 HAL_TIM_OC_Start(&TimHandle_period, TIM_CHANNEL_1);

	}
	else if (GPIO_Pin==GPIO_PIN_10)
	{
	 quadEncoder_CallbackIndexZ();
	}

}
//=================================================================
// Called if stack overflow during execution
extern void vApplicationStackOverflowHook(xTaskHandle *pxTask,
		signed char *pcTaskName)
{
	//term_printf("stack overflow %x %s\r\n", pxTask, (portCHAR *)pcTaskName);
	/* If the parameters have been corrupted then inspect pxCurrentTCB to
	 * identify which task has overflowed its stack.
	 */
	for (;;) {
	}
}
//=================================================================
//This function is called by FreeRTOS idle task
extern void vApplicationIdleHook(void)
{
}
//=================================================================
// brief This function is called by FreeRTOS each tick
extern void vApplicationTickHook(void)
{
//	HAL_IncTick();
}
//================================================================
#ifdef USE_FULL_ASSERT

/**
   * @brief Reports the name of the source file and the source line number
   * where the assert_param error has occurred.
   * @param file: pointer to the source file name
   * @param line: assert_param error line source number
   * @retval None
   */
void assert_failed(uint8_t* file, uint32_t line)
{
  /* USER CODE BEGIN 6 */
  /* User can add his own implementation to report the file name and line number,
    ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  /* USER CODE END 6 */

}

#endif
