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

#include "can.h"
#include "ADBMS_Abstraction.h"
#include "state_machine.h"

//#define CAN_ID_IN   0x501
//#define CAN_ID_OUT  0x502
void can_init(CAN_HandleTypeDef* hcan) { ftcan_init(hcan); }

/*
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% (1 bit)
- Battery: SoC (1B), Pack Voltage (2B), Current (1B), 
  Min/Max. Cell Temp (ID, Min Temp, ID, Max Temp)(4B), 
  Min/Max Cell Voltage (ID, Min Voltage, ID, Max Voltage)(4B)

bit 0-2: status
bit 0-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() {
  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%    
  data[2] = mV_from_ADBMS6830(RELAY_BAT_SIDE_VOLTAGE);          // Battery voltage 16 bit 45 bit
  data[4] = CURRENT_MEASUREMENT;                                // 16 bit measurement
  
  int8_t id = -1;
  int16_t temp = INT16_MIN;
  sm_check_cell_temps(&id, &temp);
  data[6] = (id << 5) | (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] == 0b1000000 && data[1] == 0x00){
    sm_handle_ams_in(data);
  } else if (data[0] == 0b1100000 && 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().
*/
void ftcan_msg_received_cb(uint16_t id, size_t datalen, const uint8_t *data){
  if (id == 0x501 && datalen == 16){
    can_handle_recieve_command(data);
  }
}
