#ifndef __CAN_J1939_H__
#define __CAN_J1939_H__
#include "msystem.h"
#include "mthread.h"


#define CAN_EXTERNDED_ID(Pri,PF,DA,SA)    ((uint32_t)((((Pri)&0x7)<<26)|((PF)<<16)|((DA)<<8)|(SA)))

#define CAN_J939_SA(CAN_ID)         ((uint8_t)((CAN_ID)&0xFF))
#define CAN_J939_DA(CAN_ID)         ((uint8_t)(((CAN_ID)>>8)&0xFF))
#define CAN_J939_PF(CAN_ID)         ((uint8_t)(((CAN_ID)>>16)&0xFF))
#define CAN_J939_PRI(CAN_ID)        ((uint8_t)(((CAN_ID)>>26)&0x7))
#define CAN_J939_PGN(CAN_ID)        ((uint32_t)(((CAN_ID)>>8)&0x00FFFF))

#define SAE_J1939_PGN(PF, PS)		((uint32_t)(((PF)<<8)|(PS)))
#define SAE_J1939_PS(PGN)			((PGN)&0xFF)
#define SAE_J1939_PF(PGN)			(((PGN)>>8)&0xFF)


typedef struct tpcm
{
	uint32_t PGN;
	uint8_t DA;
	uint8_t SA;
	uint8_t rpkgs;  // 可接收数据的总包数（一般等于发送数据的总包数）
	uint8_t tpkgs;	// 发送数据的总包数

	uint16_t index;  // 当前传输字节位置
	uint16_t bytes;  // 数据报总字节数
	uint8_t *buff;
}tpcm_t;


void can_J1939_init_TPCM(tpcm_t* tp, uint32_t PGN, uint8_t DA, uint8_t SA, uint8_t* data, int len);

typedef struct can_j1939
{
	int	fd;
	int bitrate;
	const char* can_name;

	uint8_t rxbuff[1785+3];
	uint8_t txbuff[1785+3];
	tpcm_t rxtpcm;
	tpcm_t txtpcm;

	tpcm_t *rxtp;
	tpcm_t *txtp;
	int rxtp_quit;
	int txtp_quit;

	int64_t rxframe_ms;
	int64_t txframe_ms;
	
	int quit;

}can_j1939_t;

void printTxCanFrame(const char* can_name, struct can_frame *frame);
void printRxCanFrame(const char* can_name, struct can_frame *frame);

int can_J1939_init(can_j1939_t* dev, const char* can_name, int bitrate);
void can_J1939_exit(can_j1939_t* dev);

int	can_J1939_read(can_j1939_t* dev, struct can_frame *frame, int timeout);
int	can_J1939_send(can_j1939_t* dev, struct can_frame *frame);

int can_J1939_send_TPCM_RTS(can_j1939_t* dev, tpcm_t* tp);
int can_J1939_send_TPCM_CTS(can_j1939_t* dev, tpcm_t* tp, uint8_t pkgsn);
int can_J1939_send_TPCM_EOMACK(can_j1939_t* dev, tpcm_t* tp);
int can_J1939_send_TPCM_ABORT(can_j1939_t* dev, tpcm_t* tp);
int can_J1939_send_TPCM_BAM(can_j1939_t* dev, tpcm_t* tp);
int can_J1939_send_TPDT(can_j1939_t* dev, tpcm_t* tp, uint8_t pkgsn);


#endif//__CAN_J1939_H__
