/*
 * 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

// Frame ID = Base Address + Slave ID + MessageNr.
#define SLAVE_STATUS_BASE_ADDRESS 0x600
#define SLAVE_CMD_BASE_ADDRESS 0x500  //
#define SLAVE_EMERGENCY_ADDRESS 0x001 // Emergency Frame
#define CLOCK_SYNC_ADDRESS 0x002
#define MASTER_HEARTBEAT_ADDRESS 0x010
#define SLAVE_EEPROM_WRITE_ADDRESS 0x020

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 updateSlaveInfo(uint8_t slaveID, uint8_t MessageID, canFrame rxFrame);

#endif /* INC_CAN_COMMUNICATION_H_ */
