/*
 * CAN_Communication.h
 *
 *  Created on: Apr 26, 2022
 *      Author: max
 */

#ifndef INC_CAN_COMMUNICATION_H_
#define INC_CAN_COMMUNICATION_H_

#include "AMS_Errorcodes.h"
#include "Slave_Monitoring.h"
#include "main.h"

#include "stm32g4xx_hal.h"
#include "stm32g4xx_hal_fdcan.h"

#define CANFRAMEBUFFERSIZE 512

#define CAN_ID_SLAVE_EMERGENCY 0x001
#define CAN_ID_CLOCK_SYNC 0x002
#define CAN_ID_AMS_STATUS 0x0A
#define CAN_ID_AUTOBOX_INFO 0x0B
#define CAN_ID_MASTER_HEARTBEAT 0x010
#define CAN_ID_SLAVE_EEPROM_WRITE 0x020
#define CAN_ID_AMS_PANIC 0x42

#define CAN_ID_START_CHARGING 0x446

#define CAN_ID_SHUNT_BASE 0x520
#define CAN_MASK_SHUNT 0xFF0
#define CAN_ID_SHUNT_CURRENT 0x521
#define CAN_ID_SHUNT_VOLTAGE_1 0x522
#define CAN_ID_SHUNT_VOLTAGE_2 0x523
#define CAN_ID_SHUNT_VOLTAGE_3 0x524
#define CAN_ID_SHUNT_BUSBAR_TEMP 0x525
#define CAN_ID_SHUNT_POWER 0x526
#define CAN_ID_SHUNT_AMPERE_SECONDS 0x527
#define CAN_ID_SHUNT_ENERGY 0x528

// Frame ID = Base Address + Slave ID + MessageNr.
#define CAN_ID_SLAVE_STATUS_BASE 0x600
#define CAN_MASK_SLAVE_STATUS 0xF00

typedef struct {
  int16_t FrameID;
  uint8_t data[8];
  uint8_t length;
  uint32_t timestamp;
  uint8_t error;

} canFrame;

extern canFrame framebuffer[CANFRAMEBUFFERSIZE];

extern uint32_t framebufferwritepointer;
extern uint32_t framebufferreadpointer;
extern uint32_t frames_read;

void HAL_FDCAN_RxFifo0Callback(FDCAN_HandleTypeDef* handle,
                               uint32_t interrupt_flags);

void CAN_Init(FDCAN_HandleTypeDef* hcan);
uint8_t CAN_Receive(FDCAN_HandleTypeDef* hcan);
uint8_t CAN_Transmit(FDCAN_HandleTypeDef* hcan, uint16_t frameid,
                     uint8_t* buffer, uint8_t datalen);

void CAN_SendAbxStatus(FDCAN_HandleTypeDef* hcan);
void CAN_SendAMSPanic(FDCAN_HandleTypeDef* hcan, AMSErrorHandle* error);

void CAN_HandleShuntMsg(canFrame* rxFrame);
void CAN_HandleSlaveStatus(canFrame* rxFrame);
void CAN_HandleSlaveEmergency(canFrame* rxFrame);

#endif /* INC_CAN_COMMUNICATION_H_ */
