/*
 *          can.c
 *  Created on: Mai 23, 2024
 *      Author: Hamza
 */

#include "can.h"

//#define CAN_ID_IN   0x501
//#define CAN_ID_OUT  0x502
int can_delay_manager = 0;
void can_init(CAN_HandleTypeDef* hcan) { 
  ftcan_init(hcan); 
  ftcan_add_filter(CAN_ID_IN, 0xFFF);
}
/*
This function sends the status of the mvbms, the battery and of powerground.
once every 1s in states: INACTIVE, PRECHARGE, DISCHARGE, CHARGING, ERROR.
once every 0.5s in states: READY, ACTIVE.
with format of:
CAN Messages:
  MVBMS Status (1B), Powerground Status 0-100% (1B)
  Battery: SoC (1B), Pack Voltage (2B), Current (1B), 

  Min/Max. Cell Temp (ID, Min Temp, ID, Max Temp)(3B), 
  Min/Max Cell Voltage (ID, Min Voltage, ID, Max Voltage)(3B)

bit 0-2: status
bit 3-7:
bit 8-15: State of Charge from 0-100%
bit 16-31: Battery voltage
bit 32-47: Current measurement 
bit 48-50: id of cell with highest temperature
bit 51-62: temperature of the cell with highest temperature (12 bits moved 4 bit to the left)
*/

void can_handle_send_status() {
  if (can_delay_manager > HAL_GetTick())
    return;
  else
    can_delay_manager = HAL_GetTick() + CAN_STATUS_FREQ;
  
  uint8_t data[8] = {};
  data[0] = (state.current_state << 5);                         // save 5 bit since codes are from 0-7 61 bits left 
  //data[1] =                                                   // in 8 bits from 0-100%    
  ftcan_marshal_unsigned(&data[2], RELAY_BAT_SIDE_VOLTAGE, 2);                 // Battery voltage 16 bit 45 bit
  ftcan_marshal_unsigned(&data[4], CURRENT_MEASUREMENT, 2);                                // 16 bit measurement
  
  int8_t id = -1;
  int16_t temp = INT16_MIN;
  sm_check_cell_temps(&id, &temp);
  data[6] = (id << 4) | (temp >> 4);                            // there are only 7 TMP1075
  ftcan_transmit(CAN_ID_OUT, data, sizeof(data));

  ;
  
}

/*
can_handle_recieve_command() should only check if the message is valid and then hand it
to the sm_handle_ams_in() which handles the state machine transition.
*/
void can_handle_recieve_command(const uint8_t *data){
  if (data[0] == 0x00 && data[1] == 0x00){
    sm_handle_ams_in(data);
  } else if (data[0] == 0x01 && data[1] == 0x00){
    sm_handle_ams_in(data);
  } else if (data[0] == 0x02 && data[1] <= 100) { 
    sm_handle_ams_in(data);
  }
}

/*
implements the _weak method ftcan_msg_recieved_cb() which throws an interrupt when a CAN message is recieved.
it only checks if the id is and datalen is correct thans hands data over to can_handle_recieve_command().

in MXCUBE under CAN NVIC settings "USB low priority or CAN_RX0 interrupts" has to be on 
*/
void ftcan_msg_received_cb(uint16_t id, size_t datalen, const uint8_t *data){
  if (id == 0x501 && datalen == 2){
    can_handle_recieve_command(data);
  }
}
