#include "qingxie_bms.h"
#include "common.h"
#include "soft_p_2_c.h"
#include "soft_can.h"
qingxie_bms_status_t _qx_bms[4] = {0};


void send_info_to_Qx(void) 
{
  if(_Aqx_bms_link.connect_status != COMP_NORMAL)
    return;
  
  uint8_t can_buf[8] = {0};
  
  if(planep.lock_status == 0)
    can_buf[0] = 0;
  else if(planep.lock_status == 1)
    can_buf[0] = 1;
  else if(planep.lock_status == 4)
    can_buf[0] = 2;

  can_buf[1] = (planep.thr_pwm - 1000) / 10;
  
  can_send_msg_normal(&can_buf[0], 8, 0x66B);
}

Connect_check _qx_bms_link[4] = {0};
Connect_check _Aqx_bms_link;
void QxBmsCanRecvHookFunction(uint32_t id, uint8_t data[], uint8_t len)
{
  int bms_id = 0;

  _Aqx_bms_link.connect_status = COMP_NORMAL;

  if (id == QINGXIE_BMS0_CAN_ID1 || id == QINGXIE_BMS1_CAN_ID1 ||
      id == QINGXIE_BMS2_CAN_ID1 || id == QINGXIE_BMS3_CAN_ID1) 
  {
    if (id == QINGXIE_BMS1_CAN_ID1) {
      bms_id = 1;
    } else if (id == QINGXIE_BMS2_CAN_ID1) {
      bms_id = 2;
    } else if (id == QINGXIE_BMS3_CAN_ID1) {
      bms_id = 3;
    }
    _qx_bms_link[bms_id].connect_status = COMP_NORMAL;
    _qx_bms_link[bms_id].recv_time = HAL_GetTick();

    _qx_bms[bms_id].bat_voltage = data[1] + (data[0] << 8);
    _qx_bms[bms_id].servo_current = data[3] + (data[2] << 8);
    _qx_bms[bms_id].stack_voltage = data[5] + (data[4] << 8);
    _qx_bms[bms_id].servo_voltage = data[7] + (data[6] << 8);
    
  } 
  else if (id == QINGXIE_BMS0_CAN_ID2 || id== QINGXIE_BMS1_CAN_ID2 ||
              id== QINGXIE_BMS2_CAN_ID2 || id== QINGXIE_BMS3_CAN_ID2) 
  {
    if (id == QINGXIE_BMS1_CAN_ID2) {
      bms_id = 1;
    } else if (id == QINGXIE_BMS2_CAN_ID2) {
      bms_id = 2;
    } else if (id == QINGXIE_BMS3_CAN_ID2) {
      bms_id = 3;
    }
    _qx_bms[bms_id].gas_tank_pressure = data[1] + (data[0] << 8);
    _qx_bms[bms_id].pipe_pressure = data[3] + (data[2] << 8);
    _qx_bms[bms_id].pcb_temp = data[5] + (data[4] << 8);
    _qx_bms[bms_id].stack_temp = data[7] + (data[6] << 8);
  } else if (id == QINGXIE_BMS0_CAN_ID3 || id == QINGXIE_BMS1_CAN_ID3 ||
              id == QINGXIE_BMS2_CAN_ID3 || id == QINGXIE_BMS3_CAN_ID3) {
    if (id == QINGXIE_BMS1_CAN_ID3) {
      bms_id = 1;
    } else if (id == QINGXIE_BMS2_CAN_ID3) {
      bms_id = 2;
    } else if (id == QINGXIE_BMS3_CAN_ID3) {
      bms_id = 3;
    }
    _qx_bms[bms_id].work_status = data[0];
    _qx_bms[bms_id].self_chek = data[1];
    _qx_bms[bms_id].falt_status = data[3] + (data[2] << 8);
    _qx_bms[bms_id].bat_refuel_current = data[5] + (data[4] << 8);
  }
}
