/*
 * CAN.h

 *
 *  Created on: Dec 04, 2018
 *      Author: v0stap
 */

#ifndef _CAN_H_
#define _CAN_H_

#define		CAN_ID_STD		0x00000000U
#define		CAN_ID_EXT		0x00000004U
#define 	CAN_RTR_DATA	0x00000000U
#define		CAN_RTR_REMOTE	0x00000002U

#define STD_FORMAT		0
#define EXTD_FORMAT		1

#define DATA_FRAME       0
#define REMOTE_FRAME     1

#define		CAN_250KBS		0x031c000b
#define 	CAN_500KBS		0x031c0005
#define 	CAN_1000KBS		0x031c0002

typedef struct {
	uint32_t id;               // 29 bit identifier
	uint8_t data[8];            // Data field
	uint8_t lenght;                // Length of data field in bytes
	uint8_t format;             // 0 - STANDART, 1- EXTENDED
	uint8_t frame;              // 0 - DATA FRAME, 1 - REMOTE FRAME
} can_msg_typedef;
typedef struct {
	can_msg_typedef data[16];
	uint8_t todo;
	uint8_t corent;
	uint8_t done;
} can_buffer_typedef;

typedef struct {
	CAN_TypeDef *can_port;
	uint8_t mode;
	uint32_t speed;
	uint8_t filter;
	uint8_t rx_pin;
	uint8_t tx_pin;
	GPIO_TypeDef *port;
	uint8_t tx_ready;
	uint8_t rx_ready;
} can_config_typedef;

void CAN_Init(void);
void CAN_Setup(uint32_t speed);
void CAN_Start(void);
void CAN_Wait_Ready(void);
void CAN_Send_Msg(can_msg_typedef *msg);
void CAN_Recive_Msg(can_msg_typedef *msg);
void CAN_Write_Filter(uint32_t id, uint8_t format);
void CAN_Send_TX_Buffer(void);
void CAN_Add_TX_Buffer(can_msg_typedef *data);
void CAN_Add_RX_Buffer(void);
void CAN_Read_RX_Buffer(can_msg_typedef *data);

extern can_msg_typedef CAN_TX_Msg;		// CAN message for transmit
extern can_msg_typedef CAN_RX_Msg;		// CAN received message
extern uint8_t CAN_TX_Rdy;		// CAN hardware ready to transmit a message
extern uint8_t CAN_RX_Rdy;		// CAN hardware received a message
extern uint32_t CAN_Speed;		// CAN Speed / CAN BTR register
extern can_buffer_typedef CAN_TX_Buffer;
extern can_buffer_typedef CAN_RX_Buffer;
#endif // _CAN_H_

