/*
 * goose.h
 *
 *  Created on: 16-07-2020
 *      Author: Krzysztof Jakubczyk
 */

#ifndef GOOSE_H_
#define GOOSE_H_

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

#define GOOSE_NORMAL 0
#define GOOSE_VLAN	 1

#define GOOSE_TAG_GOCBREF			0x80
#define GOOSE_TAG_TTL				0x81
#define GOOSE_TAG_DATSET			0x82
#define GOOSE_TAG_ID				0x83
#define GOOSE_TAG_T					0x84
#define GOOSE_TAG_STNUM				0x85
#define GOOSE_TAG_SQNUM				0x86
#define GOOSE_TAG_SIMULATION		0x87
#define GOOSE_TAG_CONFREV			0x88
#define GOOSE_TAG_NDSCOM			0x89
#define GOOSE_TAG_NUMDATSETENTRIES	0x8a
#define GOOSE_TAG_ALLDATA			0xAB
#define GOOSE_TAG_PDU				0x61

#define GOOSE_DATA_ARRAY			0x81
#define GOOSE_DATA_STRUCT			0xA2
//#define GOOSE_DATA_STRUCT			0x82
#define GOOSE_DATA_BOOLEAN			0x83
#define GOOSE_DATA_BITSTRING		0x84
#define GOOSE_DATA_INTEGER			0x85
#define GOOSE_DATA_UNSIGNED			0x86
#define GOOSE_DATA_FLOAT			0x87
#define GOOSE_DATA_OCTETSTRING		0x89
#define GOOSE_DATA_VISIBLESTRING	0x8A
#define GOOSE_DATA_TIMEOFDAY		0x8C
#define GOOSE_DATA_BCD				0x8D
#define GOOSE_DATA_BOOLEANARRAY		0x8E

#define GOOSE_ETHERTYPE_LE			0xb888
#define SV_ETHERTYPE_LE				0xba88

struct goose_queue
{
	u32 cur;
	u32 next;
	u32 lost;
	char buf[GOOSE_QUEUE_DEPTH][GOOSE_MAX_FR_SIZE];
	char status[GOOSE_QUEUE_DEPTH];
};

#define GOOSE_TO_PROCESS		0x01
#define SV_TO_PROCESS			0x02

struct goose_frame
{
	u16 appid;
	u16 len;
	u32 reserved;
	u8 pdu_tag;
	u8 pdu_len;
	u8 pdu_data[];
}__attribute__((__packed__));

struct goose_frame2
{
	u16 appid;
	u16 len;
	u32 reserved;
	u8 pdu_tag;
	u8 pdu_taglen;
	u8 pdu_len;
	u8 pdu_data[];
}__attribute__((__packed__));

struct goose_frame_vlan
{
	u8 dst_mac[6];
	u8 src_mac[6];
	u16 tpid; // 802.1Q
	u16 tci;  // 802.1Q
	u16 ethertype;
	struct goose_frame goose;
}__attribute__((__packed__));

struct goose_frame_normal
{
	u8 dst_mac[6];
	u8 src_mac[6];
	u16 ethertype;
	struct goose_frame goose;
}__attribute__((__packed__));

extern struct goose_queue gqueue;

struct goose_logic
{
	float *recv_cnt;
	struct binary_io state[8];
	struct binary_io expired;
	struct binary_io ndscom;
	struct binary_io test;
	char *goose_id;
	char *goose_dataset;
	char *goose_cbref;
	char *goose_dstaddr;
	char *sv_id;
	char *sv_dstaddr;
	uint64_t ttl;
	uint64_t stnum;
	uint64_t sqnum;
	u8 values;
};

struct goose_io
{
	u32 recv_cnt_float_out;
	u32 state_out[8];
	u32 expired_out;
	u32 ndscom_out;
	u32 test_out;
}__attribute__((__packed__));


struct goose_params
{
	u32 bits;
	u32 appid;
	u32 data_index[8];
	u32 cfg_rev;
	u32 strings_start;
}__attribute__((__packed__));

struct goose_args
{
	struct goose_io io;
	struct goose_params params;
//	u16 crc;
}__attribute__((__packed__));

extern void goose(void *args, void *logic);
extern int goose_initlog(void *arguments, void *logic);

extern void iec61850_goose_recv(struct goose_frame *gfr,int len,char type);

#endif
