/*
 * AesaStream.h
 *
 *  Created on: 21/set/2023
 */

#ifndef AESASTREAM_H_
#define AESASTREAM_H_

#include <stdint.h>

#include "aesa_if_types.h"

#define BEAM_DIRECTION_FACTOR_LSB       /* 3.05e-5F */(2.0f/0xffff)

struct raw_antenna_reply_buffer_t
{
    unsigned int updates;
	unsigned int hstate;
    unsigned int response_decoded;
	unsigned int msg_count_errors;
	unsigned int timeouterr;
	unsigned int crcerr;
	unsigned int lenerr;
	unsigned int rxerr;
	int pri_err;
	int ignore_aesa_status;
	unsigned int download_map_executed;
	unsigned int spare[6];
	unsigned int data_udpates;
	unsigned int data_size;
};

class AesaStream
{
public:
    uint8_t* d;
    unsigned int s;
    unsigned int pos;

    AesaStream(const void* p, unsigned int max_size):
        d((uint8_t*)(p)),
        s(max_size),
        pos(3)
    {
    }

    uint8_t pop()
    {
        uint8_t v=d[pos];
        if (pos==0)
        {
            pos=3;
            d+=4;
        }
        else
            --pos;
        return v;
    }
    uint16_t pop16()
    {
        uint16_t v=pop(); //push(v & 0xFF);
        v|=pop()<<8; //push((v>>8) & 0xFF);
        return v;
    }

    uint16_t pops16()
    {
        return static_cast<int16_t>(pop16());
    }

    float popuv()
    {
    	int16_t x=pops16();
		return x*BEAM_DIRECTION_FACTOR_LSB;

    }
};

class AesaDeserializer
{
public:
	enum { max_msg=2048};

	struct DesResultMsg
	{
		int error;
		int timeout;
		unsigned int area;
		unsigned int tag;
		unsigned int id;
		const char* name;

		unsigned int exp_response;

		unsigned int payload_id;
		unsigned int payload_destination;

		union {
			aesa::beam_calculation_t beam_cmd;
			aesa::cti_status_t cti_sts;
		} payload;
	};

	struct DesResults
	{
		int ok;
		int errors;
		int crc;
		int timeout;
		int len;

		unsigned int msg_num;
		DesResultMsg msg[max_msg];
	};

	static const char* desCommand(DesResults* res, const void* data, unsigned int ax_size);

	static const char* desResponse(DesResults* res, const void* data, unsigned int ax_size);
};

#endif /* AESASTREAM_H_ */
