#include <string.h>
#include "lin_common.h"

const unsigned char sllin_id_parity_table[64] = {
        0x80,0xc0,0x40,0x00,0xc0,0x80,0x00,0x40,
        0x00,0x40,0xc0,0x80,0x40,0x00,0x80,0xc0,
        0x40,0x00,0x80,0xc0,0x00,0x40,0xc0,0x80,
        0xc0,0x80,0x00,0x40,0x80,0xc0,0x40,0x00,
        0x00,0x40,0xc0,0x80,0x40,0x00,0x80,0xc0,
        0x80,0xc0,0x40,0x00,0xc0,0x80,0x00,0x40,
        0xc0,0x80,0x00,0x40,0x80,0xc0,0x40,0x00,
        0x40,0x00,0x80,0xc0,0x00,0x40,0xc0,0x80
};


int sllin_setup_msg(struct sllin *sl, int mode, int id,
		unsigned char *data, int len)
{
	if (id > 0x3f)
		return -1;

	sl->rx_cnt = 0;
	sl->tx_cnt = 0;
	sl->rx_expect = 0;

	sl->tx_buff[SLLIN_BUFF_BREAK] = 0;
	sl->tx_buff[SLLIN_BUFF_SYNC]  = 0x55;
	sl->tx_buff[SLLIN_BUFF_ID]    = id | sllin_id_parity_table[id];
	sl->tx_lim = SLLIN_BUFF_DATA;

	if ((data != NULL) && len) {
		int i;
		unsigned csum  = 0;

		sl->tx_lim += len;
		memcpy(sl->tx_buff + SLLIN_BUFF_DATA, data, len);
		/* compute data parity there */
		for (i = SLLIN_BUFF_DATA; i < sl->tx_lim; i++) {
			csum += sl->tx_buff[i];
			if (csum > 255)
				csum -= 255;
		}

		sl->tx_buff[sl->tx_lim++] = csum;
	}
	if (len != 0)
		sl->rx_lim += len + 1;

	return 0;
}

