/*
    ai Task
    
*/

/* Includes ----------------------------------------------------------------- */

#include "task/user_task.h"
/* USER INCLUDE BEGIN */
#include "module/vision_bridge.h"
#include "component/ahrs/ahrs.h"
#include "module/gimbal.h"
#include "module/shoot.h"
#include "bsp/can.h"
#include <string.h>
#include "module/config.h"
/* USER INCLUDE END */
 
/* Private typedef ---------------------------------------------------------- */
/* Private define ----------------------------------------------------------- */

/* Private macro ------------------------------------------------------------ */
/* Private variables -------------------------------------------------------- */
/* USER STRUCT BEGIN */
AI_t ai;
AI_cmd_t aiToCmd;

AI_RawData_t rawdata;
AHRS_Quaternion_t quat_from_imu;
Gimbal_Feedback_t rawdata_from_gimbal;
Shoot_Feedback_t rawdata_from_shoot;
/* USER STRUCT END */

/* Private function --------------------------------------------------------- */
/* Exported functions ------------------------------------------------------- */
void Task_ai(void *argument) {
  (void)argument; /* 未使用argument，消除警告 */

  
  /* 计算任务运行到指定频率需要等待的tick数 */
  const uint32_t delay_tick = osKernelGetTickFreq() / AI_FREQ;

  osDelay(AI_INIT_DELAY); /* 延时一段时间再开启任务 */

  uint32_t tick = osKernelGetTickCount(); /* 控制任务运行频率的计时 */
  /* USER CODE INIT BEGIN */
  AI_Init(&ai, &Config_GetRobotParam()->ai_param);
  /* USER CODE INIT END */
  
  while (1) {
    tick += delay_tick; /* 计算下一个唤醒时刻 */
    /* USER CODE BEGIN */
		
		osMessageQueueGet(task_runtime.msgq.ai.rawdata_FromGimbal, &rawdata_from_gimbal, NULL, 0);	
		osMessageQueueGet(task_runtime.msgq.ai.rawdata_FromIMU, &quat_from_imu, NULL, 0);
		osMessageQueueGet(task_runtime.msgq.ai.rawdata_FromShoot, &rawdata_from_shoot, NULL, 0);
    rawdata.mode=1;
    rawdata.pitch=rawdata_from_gimbal.motor.pit.rotor_abs_angle;
    rawdata.yaw=rawdata_from_gimbal.motor.yaw.rotor_abs_angle;
    rawdata.pitch_vel=rawdata_from_gimbal.motor.pit.rotor_speed;
    rawdata.yaw_vel=rawdata_from_gimbal.motor.yaw.rotor_speed;
    rawdata.q[0]=quat_from_imu.q0;
    rawdata.q[1]=quat_from_imu.q1;
    rawdata.q[2]=quat_from_imu.q2;
    rawdata.q[3]=quat_from_imu.q3;
    rawdata.bullet_speed = 0.0f;  /* TODO: 从shoot反馈中获取 */
    rawdata.bullet_count = 0;     /* TODO: 从shoot反馈中获取 */
    AI_ParseForHost(&ai,&rawdata);
		AI_StartSend(&ai);
		
		AI_StartReceiving(&ai);		
		AI_Get(&ai,&aiToCmd);		

    /* 通过can2把解包后的AI_cmd_t发给下层板 */
    AI_SendCmdOnCan(&ai, &aiToCmd);

    /* USER CODE END */
    osDelayUntil(tick); /* 运行结束，等待下一次唤醒 */
  }
  
}
