/*
 * ts_comms.h
 *
 *  Created on: 22 Oct 2020
 *      Author: Dmitrijs
 */

#ifndef TS_COMMS_H_
#define TS_COMMS_H_

#include <stdint.h>

typedef unsigned char crc_t;

#define TS_CAN_ID 0

#ifndef TS_CAN_ID
#error Set CAN ID !!! ts_comms.h
#endif

// Timeouts for comms: in mS
// Timeout for receive 2 bytes after <cmd>
#define RECEIVE_INDEX_TIMEOUT			10
//Timeout for receive 4 bytes of OFFSET and COUNT
#define RECEIVE_DATA_LOCATION_TIMEOUT	10
//Time out for receive block of data
#define RECEIVE_DATA_TIMEOUT			255
//Timeout for RESET sequence.
#define RECEIVE_RESET_TIMEOUT			1
#define RECEIVE_TABLE_TIMEOUT			255

//Define SCI MODES
#define IDLE							0
#define TRANSMISSION_IN_PROGRESS		1
#define RECEIVE_INDEX					1
#define RECEIVE_DATA_LOCATION			2
#define RECEIVE_DATA					3
#define RECEIVE_TABLE_DATA				4
#define RECEIVE_CANID					5
#define RECEIVE_RESET_CMD				10

//DEFINE ERROR CODES FOR TS COMMS
#define DATA_OVERRUN_ERROR						1
#define FRAME_ERROR								2
#define PARITY_ERROR							3
#define UNRECOGNIZED_1_LETTER_CMD				4
#define REQUEST_TO_TRANSMIT_WHILE_TRANSMITTING	5
#define RESET_SEQUENCE_FAILED					6
#define RESET_SEQUENCE_RECEIVED					7
#define MEMORY_ACCESS_VIOLATION					8
#define RX_TIMEOUT								9
#define NOICE_ERROR								10

#define SCI_FLAGS_CRC32					1
#define SCI_FLAGS_TX_VARIABLES			2

#define READ_DATA_FROM_ADC0			0
#define READ_DATA_FROM_ADC1			1
#define READ_DATA_FROM_CONFIG_ADC0	2
#define READ_DATA_FROM_CONFIG_ADC1	3
#define READ_DATA_FROM_Z0			4
#define READ_DATA_FROM_Z1			5

typedef struct {

	unsigned char mode;				//1
	unsigned char cmd;					//2
	unsigned char CANid;				//3
	unsigned char table_index;			//4
	unsigned short offset;				//5
	unsigned short data_size;			//7
	unsigned short cnt;					//9
	unsigned short bytes_done;			//11
	unsigned char *address;			//13
	unsigned char current_table_index;	//15
	unsigned char error_cnt;			//16
	unsigned char error_code;			//17
	unsigned short timeout;				//18
	unsigned char pause_flag;
	unsigned char dummy;
	unsigned long crc32;				//19
	unsigned char can_bufer[256];
} comms_status;

void Rx_Char(unsigned char data);			// pass RX byte stream here
void Poll_Tx(void);			// function returns pointer to buffer and sets count
							// of bytes to be transmitted
void TX_Done(void);		// call this function when all data has been transmitted
void Comms_Init(void);

void Write_Config(void);

extern comms_status RX;
extern comms_status TX;
extern unsigned char SCI_flags;
extern const char Signature[20];
extern const char Revision[20];
extern char crc32_bufer[8];
void Comms_Reset(comms_status *CS);
void TX_Schedule(unsigned char *data, unsigned short count);
void Copy_Tx_Vars(void);
void CRC32(void);
crc_t calc_crc(crc_t message[], int nBytes);
uint32_t crc32(void *buf, uint32_t size);
uint32_t crc32inc(void *buf, uint32_t crc, uint32_t size);
void TS_Comms_RX_Timeout(void);

#endif /* TS_COMMS_H_ */
