/*****************************************************************************/
/**
 * @file phy_layer.c
 * @author FanHao (hao_fan_bit_ee@163.com)
 * @brief Physical layer control header file.
 * @version 0.0
 * @date 2023-04-24
 *
 * @copyright Copyright(c) 2024 Beijing Institute of Technology.\n
 * Lab of Communication and Network
 *
 ******************************************************************************/

/**
 * @defgroup PhysicalLayer
 * @{
 */

#ifndef PHY_CTRL_H_
#define PHY_CTRL_H_

/***************************** Include Files *********************************/
#include <stdint.h>
#include "common.h"
#ifndef EMULATION
#include "xbram.h"
#include "xadcps.h"
#include "../config/app_config.h"
#endif
#include "../../system_monitor.h"
#include "../../time_ctrl/time_ctrl.h"
/************************** Constant Definitions *****************************/
/**
 * @name PhysicalLayer_Common_Constant
 * @{
 */
#define L1_NUM_ANT_NRRW_PATTERN 37
#define L1_INIT_BEAM_NO 0
#define L1_INIT_ANT_WD PHY_ANT_BEAM_120
#define L1_ANT_NUM_CH 4

#define L1_FRAME_NONE_LEN UINT32_MAX  // byte
#define L1_FRAME_NONE_COMP UINT32_MAX // *10ns(Timer_L)
#define L1_FRAME_NONE_HOPS UINT32_MAX
#define L1_FRAME_MAX_HOPS 81
#define L1_FRAME_2KBPS_20MS_HOPS 1
#define L1_FRAME_2KBPS_100MS_HOPS 81
#define L1_FRAME_10KBPS_10MS_HOPS 1
#define L1_FRAME_10KBPS_20MS_HOPS 11
#define L1_FRAME_40KBPS_20MS_HOPS 19
#define L1_FRAME_40KBPS_10MS_HOPS 9
#define L1_FRAME_200KBPS_5MS_HOPS 20
#define L1_FRAME_1M2BPS_5MS_HOPS 20
#define PHY_LOG_EXPIRE 40 // 50*5ms
/** @} */
/***************** Macros (Inline Functions) Definitions *********************/
/**************************** Type Definitions *******************************/
/**
 * @enum L1_FRAME_TYPE
 */
typedef enum
{
	L1_NONE_FRAME = 0,
	L1_2KBPS_20MS_FRAME = 1,
	L1_2KBPS_100MS_FRAME = 2,
	L1_10KBPS_10MS_FRAME = 3,
	L1_10KBPS_20MS_FRAME = 4,
	L1_40KBPS_20MS_FRAME = 5,
	L1_40KBPS_10MS_FRAME = 6,
	L1_200KBPS_5MS_FRAME = 7,
	L1_1M2BPS_5MS_FRAME = 8
} L1_FRAME_TYPE;

/**
 * @struct PHY_ANT_CONFIG
 * @brief PhysicalLayer antenna config
 */
typedef struct
{
	/*** Ant Control ***/
	uint8_t ctrlWord;	 ///< Antenna control frame head 0xAA\n
						 /// default 0, reserved for further use
	uint8_t antMode;	 ///< high 4 bits specified beam mode.\n
						 /// low 4 bits specified power control
	uint8_t oaxis[2];	 ///< off-axis angle range is 0~60 \n
						 /// 0.1 degree each LSB
	uint8_t raxis[2];	 ///< round-axis angle range is 0~360, \n
						 /// 0.1 degree each LSB
	uint8_t antFreq[2];	 ///< 0~3500Mhz, step 1MHz
	uint8_t trSlect;	 ///< in single tr mode, 0~63 specified tr channel \n
						 /// in single subarray mode, 0~3 specified the subarray
						 /// ! Only in debug mode!
	uint8_t antAtt;		 ///< Antenna attenuation 0~31, 0.5dB each LSB, Only in debug mode
	uint8_t phase;		 ///< 0~63, 5.625 degree each LSB, Only in debug mode
	uint8_t rxtxMode;	 ///< Only for debug \n
						 /// default 0x00
	uint8_t calibrMode;	 ///< 0x00 Normal, 0x01 single tr calibration
	uint8_t antReserved; ///< reserved for further use

	/*** RF Control ***/
	uint8_t rfCtrl;		 ///< [7:4]RF enable: 0-On, 1-Off(Default); [3:0]Work mode: 0(default)
	uint8_t rfFreq[2];	 ///< 0~3500Mhz, step 1MHz
	uint8_t rfTxMgc;	 ///< RF MGC control: 0~31, 1dB each LSB
	uint8_t rf12CalMgc;	 ///< RF channel 1&2 calibration mgc\n
						 /// [7:4] Channle1 - max 15db, 1dB each LSB \n
						 /// [3:0] Channle2 - max 15db, 1dB each LSB
	uint8_t rf34CalMgc;	 ///< RF channel 3&4 calibration mgc\n
						 /// [7:4] Channle3 - max 15db, 1dB each LSB
						 /// [3:0] Channle4 - max 15db, 1dB each LSB
	uint8_t rcvMgc;		 ///< Receive channel 1-4 MGC: 0~31, 1dB each LSB
	uint8_t rfMonitor;	 ///< Receive monitor, 0-normal, 1-switch to monitor port
	uint8_t rfReserved0; ///< reserved for further use
	uint8_t rfReserved1; ///< reserved for further use
	uint8_t ch0Cal[2];
	uint8_t ch1Cal[2];
	uint8_t ch2Cal[2];
	uint8_t ch3Cal[2];
} PHY_ANT_CONFIG;

/**
 * @struct PHY_ANT_ANGLE
 * @brief Describe the PhysicalLayer antenna angle
 */
typedef struct
{
	uint16_t oaxis; ///< off-axis angle range is 0~60
					/// 0.1 degree each LSB
	uint16_t raxis; ///< round-axis angle range is 0~360
					/// 0.1 degree each LSB
} PHY_ANT_ANGLE;

/**
 * @enum PHY_TIME_WORD_TYPE
 */
typedef enum
{
	PHY_TIME_WORD_NONE = 0,
	PHY_TIME_WORD_POLL = 1,
	PHY_TIME_WORD_LISTEN_TIMEOUT = 2
} PHY_TIME_WORD_TYPE;

/**
 * @enum PHY_ANT_BEAM_WIDTH
 */
typedef enum
{
	PHY_ANT_BEAM_NONE = 0,
	PHY_ANT_BEAM_120 = 1,
	PHY_ANT_BEAM_60 = 2,
	PHY_ANT_BEAM_25 = 3,
	PHY_ANT_BEAM_16 = 4
} PHY_ANT_BEAM_WIDTH;

/**
 * @enum PHY_TOR_TYPE
 */
typedef enum
{
	PHY_TOR_SUSPEND = 0,
	PHY_TOR_TX = 1,
	PHY_TOR_RX = 2
} PHY_TOR_TYPE;

/**
 * @enum PHY_MODE
 */
typedef enum
{
	PHY_MODE_NONE = 0,
	PHY_MODE_LISTEN = 1,
	PHY_MODE_SCHEDULE = 2,
	PHY_MODE_PULL = 3
} PHY_MODE;

/**
 * @enum PHY_ANT_MODE
 */
typedef enum
{
	PHY_ANT_MODE_NONE = 0,
	PHY_ANT_MODE_STANDBY = 1,
	PHY_ANT_MODE_POWER_LOW = 2,
	PHY_ANT_MODE_POWER_FULL = 3,
} PHY_ANT_MODE;

/**
 * @struct PHY_RCD
 * @brief Physical Layer recode buffer
 */
typedef struct
{
	int32_t last;
	int32_t curr;
	int32_t next;
} PHY_RCD;

/**
 * @struct PHY_CONFIG
 * @brief struct holds all physical layer initialization parameters
 */
typedef struct
{
	uint32_t devId;			///< device ID
	uint32_t txBramId;		///< tx bram ID
	uint32_t rxBramId;		///< rx bram ID
	uint32_t antBramId;		///< antenna config bram ID
	uint32_t antInfoBramId; ///< antenna beam info bram ID
	uint32_t hwXadcId;		///< hardware xadc device ID
	uintptr_t baseAddr;		///< Physical layer controller base address
#ifndef EMULATION
	uint8_t (*get_clk_state)(void);		///< function handle returns hardware clock state
	uint8_t (*get_ad_lock_state)(void); ///< function handle returns adc lock state
	int8_t (*get_ad0_temp)(void);		///< function handle returns adc0 temperature state
	int8_t (*get_ad1_temp)(void);		///< function handle returns adc1 temperature state
#endif
} PHY_CONFIG;

/**
 * @struct PHY_INST
 * @brief Physical Layer operating instance
 */
typedef struct
{
	PHY_CONFIG phyCofig;	  ///< physical layer configuration parameters
	uintptr_t recvDataAddr;	  ///< receive data bram address
	uintptr_t sendDataAddr;	  ///< send data bram address
	uintptr_t antConfigAddr;  ///< antenna config data bram address
	uintptr_t antInfoAddr;	  ///< antenna beam info data bram address
	bool isPhyEn;			  ///< indicates if physical layer running
	bool isAcq;				  ///< indicates if last reception acquisition success
	bool isFrameSync;		  ///< indicates if last reception frame sync success
	bool isDecode;			  ///< indicates if last reception decode success
	bool isValid;			  ///< indicates if last reception frame data valid (crc check pass)
	TIME_WORD recvSlotTime;	  ///< last slot start time stamp
	TIME_WORD recvFsTime;	  ///< last frame sync time stamp
	PHY_RCD beamNo;			  ///< beam number record
	PHY_RCD beamWd;			  ///< beam width record
	PHY_RCD tor;			  ///< tx rx state record
	PHY_RCD frameType;		  ///< frame type record
	uint32_t sendDataOffset;  ///< antenna configuration bram offset (to implement ping-pong data flow)
	uint32_t antConfigOffset; ///< antenna configuration bram offset (to implement ping-pong data flow)
	PHY_ANT_CONFIG antConfig; ///< antenna configuration pointer
#ifndef EMULATION
	XAdcPs hwXadc; ///< hardware Xadc instance
#endif
	PHY_ANT_ANGLE antNrrwPattern[L1_NUM_ANT_NRRW_PATTERN]; ///< antenna beam scan pattern
	HWSTATE hwSate;										   ///< hardware state log
	PHYLOG phyLog;										   ///< physical state log
	uint32_t lastLogTime;								   /// physical state log time stamp
} PHY_INST;

/************************** Function Prototypes ******************************/

/**
 * @defgroup PhysicalLayer_Main
 * @{
 */
int32_t Phy_Init(PHY_INST **instPtr, PHY_CONFIG *phyConfig);
void Phy_Destroy(PHY_INST *instPtr);
void Phy_Start(PHY_INST *instPtr);
void Phy_Halt(PHY_INST *instPtr);

int32_t Phy_SetMode(PHY_INST *instPtr, PHY_MODE modeCod);
int32_t Phy_SetTimeWord(PHY_INST *instPtr, const TIME_WORD *tmWord, PHY_TIME_WORD_TYPE tmType);
int32_t Phy_SetupNextSlot(PHY_INST *instPtr, PHY_TOR_TYPE txrxMode, L1_FRAME_TYPE frameType, uint8_t *dataBuff);
void Phy_UpdateState(PHY_INST *instPtr);
void Phy_PeekRecvData(PHY_INST *instPtr, uint8_t *dataBuff);
void Phy_RetrieveRecvData(PHY_INST *instPtr, uint8_t *dataBuff);
void Phy_UpdateLogging(PHY_INST *instPtr);
void Phy_RefreshHwSate(PHY_INST *instPtr);
/** @} PhysicalLayer_Main*/

/**
 * @defgroup PhysicalLayer_Utility
 * @{
 */
bool Phy_IsFrameDetected(PHY_INST *instPtr);
bool Phy_IsFrameReceived(PHY_INST *instPtr);
bool Phy_IsFrameValid(PHY_INST *instPtr);
uint32_t Phy_GetFrameLen(L1_FRAME_TYPE frameType);
uint32_t Phy_GetHopLength(L1_FRAME_TYPE frameType);
uint32_t Phy_GetTimeComp(L1_FRAME_TYPE frameType);
L1_FRAME_TYPE Phy_GetLastRecvFrameType(PHY_INST *instPtr);
L1_FRAME_TYPE Phy_GetLastSendFrameType(PHY_INST *instPtr);
/** @} PhysicalLayer_Utility*/

/**
 * @defgroup PhysicalLayer_Receive_Estimations
 * @{
 */
uint8_t Phy_LastScanBeamNo(PHY_INST *instPtr);
double Phy_GetFreqEst(PHY_INST *instPtr);
double Phy_GetCoarseFreqEst(PHY_INST *instPtr);
double Phy_GetFineFreqEst(PHY_INST *instPtr);
void Phy_GetFrameSyncTimeStamp(PHY_INST *instPtr, TIME_WORD *frameSyncT);
void Phy_GetLastReceivedFrameSyncTimeStamp(PHY_INST *instPtr, TIME_WORD *frameSyncT);
void Phy_GetSlotStartTimeStamp(PHY_INST *instPtr, TIME_WORD *slotStart);
void Phy_GetLastReceivedSlotStartTimeStamp(PHY_INST *instPtr, TIME_WORD *slotStart);
/** @} PhysicalLayer_Receive_Estimations*/

/**
 * @defgroup PhysicalLayer_AntennaControl
 * @{
 */
void Phy_AntConfigInit(PHY_ANT_CONFIG *antConfig);
void Phy_AntConfigMode(PHY_INST *instPtr, PHY_ANT_MODE mode);
void Phy_SetBeamTable(PHY_INST *instPtr, PHY_ANT_ANGLE *table, uint32_t offset);
int32_t Phy_SetBeamWidth(PHY_INST *instPtr, PHY_ANT_BEAM_WIDTH beamWidth);
int32_t Phy_SetBeamNo(PHY_INST *instPtr, int32_t beamNo, PHY_ANT_BEAM_WIDTH beamWidth);
int32_t Phy_SetBeamAngle(PHY_INST *phyInstPtr, double offAx, double rndAx);
/** @} PhysicalLayer_AntennaControl*/

#endif // PHY_CTRL_H_

/** @} PhysicalLayer*/