/*
 * eth.h
 *
 *  Created on: 22-03-2019
 *      Author: Krzysztof Jakubczyk
 */

#ifndef ETH_H_
#define ETH_H_

#include "tdefs.h"
#include "mkstream.h"
#include "helper.h"
#include "comm.h"

#define ETH_STREAM_PORT			31337
#define ETH_WAIT_FOR_ARM_TIME	200
#define ETH_MAX_STREAMS			3
#define ETH_MAX_RECV_STREAMS	8

#define ETH_STREAM_BUF_SIZE		16//8
#define LINK_TIMEOUT_TIME		1000
#define LINK_UP_TIME			5

extern volatile u8 str_bits[ETH_MAX_RECV_STREAMS][ETH_STREAM_BUF_SIZE];
extern struct str_eth_frame r87l_tx_packet;

extern volatile u32 str_pos[ETH_MAX_RECV_STREAMS];
extern struct stream_frame str[ETH_MAX_RECV_STREAMS][ETH_STREAM_BUF_SIZE] __attribute__((aligned(4)));

struct str_eth_frame
{
	u8 dst_mac[6];
	u8 src_mac[6];
	u8 lenh;
	u8 lenl;
	u32 padding1;
	struct stream_frame str;
	struct ping_info ping;
	u8 padding2[14];
}__attribute__((__packed__));

struct eth_logic
{
	struct binary_io en;
	struct binary_io stream_en;
	struct stream_frame *stream_in;
	struct binary_io alive;
	struct binary_io clr;
	struct binary_io ping;
	struct stream_frame stream_out[ETH_MAX_STREAMS];
	struct binary_io stream_act[ETH_MAX_STREAMS];
	struct binary_io link[ETH_MAX_STREAMS];
	float *stream_errs[ETH_MAX_STREAMS];
	float *stream_synt_errs[ETH_MAX_STREAMS];
	float *ping_time;
	u16 s_delay;
	u32 state;
	u32 tcnt;
	u32 prev_pos[ETH_MAX_STREAMS];
	u32 link_timeout_cnt[ETH_MAX_STREAMS];
	u32 link_up_cnt[ETH_MAX_STREAMS];
	u32 ping_time_prev;
	u16 prev_timestamp;
};

struct eth_io
{
	u32 en_in;
	u32 stream_en_in;
	u32 stream_ptr_in;
	u32 clr_in;
	u32 ping_in;
	u32 alive_out;
	u32 stream0_ptr_out;
	u32 stream0_act_out;
	u32 stream1_ptr_out;
	u32 stream1_act_out;
	u32 stream2_ptr_out;
	u32 stream2_act_out;
	u32 link0_out;
	u32 stream0_errs_float_out;
	u32 link1_out;
	u32 stream1_errs_float_out;
	u32 link2_out;
	u32 stream2_errs_float_out;
	u32 ping_float_out;
	u32 stream0_synt_errs_float_out;
	u32 stream1_synt_errs_float_out;
	u32 stream2_synt_errs_float_out;
}__attribute__((__packed__));


//bits
#define ETH_EN			0x01
#define ETH_EN_BCASTS	0x02
#define ETH_NO_SYNC		0x04

struct eth_params
{
	u32 bits;
	u32 sample_delay;
	u32 multicast_id;
}__attribute__((__packed__));

struct eth_args
{
	struct eth_io io;
	struct eth_params params;
//	u16 crc;
}__attribute__((__packed__));

extern void ethernet_recv(char *buf);
extern void ethernet(void *args, void *logic);
extern int ethernet_initlog(void *arguments, void *logic);

#endif
