/*
 * SPI_Communication.h
 *
 *  Created on: Jun 16, 2022
 *      Author: max
 */

#ifndef INC_SPI_COMMUNICATION_H_
#define INC_SPI_COMMUNICATION_H_

#include "CAN_Communication.h"
#include "main.h"

#define TS_INACTIVE 0
#define TS_PRECHARGE 2
#define TS_DISCHARGE 3
#define TS_ERROR 4
#define TS_ACTIVE 1

#define SEND_SHUNTDATA 0x01
#define SET_TSSTATE 0x02
#define GET_TSSTATE 0x03
#define GET_ERROR 0x04
#define GET_MEASUREMENTS 0x05
#define TOGGLE_STATUS_LED 0x06

#define NUMBEROFSLAVES 6
#define N_CELLS_SERIES 10
#define N_CELLS_PARALLEL 9
#define NUMBEROFTEMPS 32

#define SLAVE_TIMEOUT 200

typedef struct {

  uint16_t slaveID;
  uint16_t cellVoltages[N_CELLS_SERIES];
  uint16_t cellTemps[NUMBEROFTEMPS];
  uint32_t timestamp;
  uint8_t error;
  uint8_t timeout;

} SlaveHandler;

typedef struct {

  uint8_t currentTSState;
  uint8_t targetTSState;
  uint16_t relaisSupplyVoltage;
  uint16_t shutdownCircuitVoltage;
  uint16_t negativeAIRCurrent;
  uint16_t positiveAIRCurrent;
  uint16_t preChargeAIRCurrent;
  uint32_t CtrlBatteryVoltageVehicleSide;
  uint32_t CtrlBatteryVoltageBatterySide;

} TSHandler;

typedef struct {

  uint8_t errorcode;
  uint8_t errorargs[8];
  uint8_t AMS_ERROR_LED;
  uint8_t IMD_ERROR_LED;
  uint8_t IMD_ERROR;
  uint8_t HV_Inactive;
  uint8_t TS_no_voltage_error;
  uint8_t negative_AIR_error;
  uint8_t positive_AIR_or_PC_error;
  uint8_t positive_AIR_and_PC_open;
  uint8_t negative_AIR_open;

} ErrorFlagHandler;

extern SlaveHandler slaves[NUMBEROFSLAVES];
extern ErrorFlagHandler errorflags;
extern TSHandler ctrltsstate;

extern uint8_t actualTSState;

void InitSPI(SPI_HandleTypeDef* spi);
void sendShuntdata();
void sendTSstate(uint8_t targetstate);
void getTSstate();
void getError();
void getMeasurements();
uint8_t waitforSlave();
void toggleSlaveStatusLED();

uint8_t transmittoSlave(uint16_t length);
uint8_t receivefromSlave(uint16_t length);
uint8_t slaveSendCommand(uint8_t command);
void InterSTMFrame(uint8_t targettsstate);
uint8_t calculatechecksum(uint8_t* data, uint8_t datalen);

#endif /* INC_SPI_COMMUNICATION_H_ */