/*****************************************************************************/
/**
 * @file scan.c
 * @author FanHao (hao_fan_bit_ee@163.com)
 * @brief DF Linklayer scan implementation file.
 * @version 0.1
 * @date 2023-05-06
 *
 * @copyright Copyright(c) 2024 Beijing Institute of Technology.\n
 * Lab of Communication and Network
 *
 ******************************************************************************/
/**
 * @addtogroup LinkLayer
 * @{
 */

/**
 * @addtogroup LinkLayer_Scan
 * @{
 */

/***************************** Include Files *********************************/
#include <string.h>
#include "link_layer.h"
#include "link_layer_types.h"
#include "msg_def.h"
#include "node_list.h"
#include "error.h"
#include "common.h"
#include "../phy_layer/phy_layer.h"

/************************** Constant Definitions *****************************/
#define ADV_LISTEN_TIMEOUT 40
#define CFM_LISTEN_TIMEOUT 5
#define ADV_FRAME_SLOTS 4
#define CFM_FRAME_SLOTS 5
/***************** Macros (In-line Functions) Definitions *********************/

/**************************** Type Definitions *******************************/

/************************** Variable Definitions *****************************/
// Pair by regex
// Regex: ((\{\.oaxis = [0-9]+[ ,]+\.raxis = [0-9]+[ ]*\}, ){2})
PHY_ANT_ANGLE antNrrwPattern_0[L1_NUM_ANT_NRRW_PATTERN] =
{
	{.oaxis = 0  , .raxis = 0   },
	{.oaxis = 139, .raxis = 2225},
	{.oaxis = 152, .raxis = 850 },
	{.oaxis = 138, .raxis = 3155},
	{.oaxis = 159, .raxis = 1680},
	{.oaxis = 168, .raxis = 285 },
	{.oaxis = 195, .raxis = 2630},
	{.oaxis = 211, .raxis = 1204},
	{.oaxis = 225, .raxis = 3429},
	{.oaxis = 249, .raxis = 2022},
	{.oaxis = 272, .raxis = 629 },
	{.oaxis = 265, .raxis = 2934},
	{.oaxis = 277, .raxis = 1499},
	{.oaxis = 289, .raxis = 124 },
	{.oaxis = 300, .raxis = 2349},
	{.oaxis = 311, .raxis = 959 },
	{.oaxis = 321, .raxis = 3199},
	{.oaxis = 331, .raxis = 1824},
	{.oaxis = 341, .raxis = 389 },
	{.oaxis = 351, .raxis = 2674},
	{.oaxis = 360, .raxis = 1268},
	{.oaxis = 364, .raxis = 3483},
	{.oaxis = 378, .raxis = 2118},
	{.oaxis = 387, .raxis = 733 },
	{.oaxis = 416, .raxis = 3028},
	{.oaxis = 404, .raxis = 1623},
	{.oaxis = 433, .raxis = 248 },
	{.oaxis = 421, .raxis = 2473},
	{.oaxis = 429, .raxis = 1098},
	{.oaxis = 437, .raxis = 3303},
	{.oaxis = 445, .raxis = 1948},
	{.oaxis = 443, .raxis = 543 },
	{.oaxis = 450, .raxis = 2828},
	{.oaxis = 448, .raxis = 1422},
	{.oaxis = 455, .raxis = 47  },
	{.oaxis = 453, .raxis = 2272},
	{.oaxis = 450, .raxis = 897 }
};

PHY_ANT_ANGLE antNrrwPattern_1[L1_NUM_ANT_NRRW_PATTERN] =
{
	{.oaxis = 0  , .raxis = 0   },
	{.oaxis = 139, .raxis = 1155},
	{.oaxis = 152, .raxis = 3380},
	{.oaxis = 138, .raxis = 2085},
	{.oaxis = 159, .raxis = 610 },
	{.oaxis = 168, .raxis = 2815},
	{.oaxis = 195, .raxis = 1560},
	{.oaxis = 211, .raxis = 134 },
	{.oaxis = 225, .raxis = 2359},
	{.oaxis = 249, .raxis = 952 },
	{.oaxis = 272, .raxis = 3159},
	{.oaxis = 265, .raxis = 1864},
	{.oaxis = 277, .raxis = 429 },
	{.oaxis = 289, .raxis = 2654},
	{.oaxis = 300, .raxis = 1279},
	{.oaxis = 311, .raxis = 3489},
	{.oaxis = 321, .raxis = 2129},
	{.oaxis = 331, .raxis = 754 },
	{.oaxis = 341, .raxis = 2919},
	{.oaxis = 351, .raxis = 1604},
	{.oaxis = 360, .raxis = 198 },
	{.oaxis = 364, .raxis = 2413},
	{.oaxis = 378, .raxis = 1048},
	{.oaxis = 387, .raxis = 3263},
	{.oaxis = 416, .raxis = 1958},
	{.oaxis = 404, .raxis = 553 },
	{.oaxis = 433, .raxis = 2778},
	{.oaxis = 421, .raxis = 1403},
	{.oaxis = 429, .raxis = 28  },
	{.oaxis = 437, .raxis = 2233},
	{.oaxis = 445, .raxis = 878 },
	{.oaxis = 443, .raxis = 3073},
	{.oaxis = 450, .raxis = 1758},
	{.oaxis = 448, .raxis = 352 },
	{.oaxis = 455, .raxis = 2577},
	{.oaxis = 453, .raxis = 1202},
	{.oaxis = 450, .raxis = 3427},
};
/************************** Function Prototypes ******************************/
static void LockStateUpdate(L2_SCAN_FSM *scanFsmPtr, bool state);
static void AdvRecvStateUpdate(L2_SCAN_FSM *scanFsmPtr, bool state);
static void StageUpdate(L2_SCAN_FSM *scanFsmPtr, SCAN_STAGE newStage);
static void PendCfmAck(L2_SCAN_FSM *scanFsmPtr);

static int32_t Scan_InitScanHandler(L2_INST *instPtr);
static int32_t Scan_AdvHandler(L2_INST *instPtr);
static int32_t Scan_CfmHandler(L2_INST *instPtr);

static int32_t ScanMsg_Packing(L2_INST *instPtr, L2_FRAME_TYPE type, uint8_t dstId);

/**
 * @brief   Update Init-Scan lock state.
 */
static inline void LockStateUpdate(L2_SCAN_FSM *scanFsmPtr, bool state)
{
	ASSERT(scanFsmPtr != NULL);
	DBG_INFO("Update BeamLockState from [%" PRId8 "] to [%" PRId8 "].\n",
			 scanFsmPtr->isLocked, state);
	scanFsmPtr->isLocked = state;
	return;
}

/**
 * @brief   Update Base-info Advertisement state.
 */
static void AdvRecvStateUpdate(L2_SCAN_FSM *scanFsmPtr, bool state)
{
	ASSERT(scanFsmPtr != NULL);
	DBG_INFO("Update AdvRecvState from [%" PRId8 "] to [%" PRId8 "].\n",
			 scanFsmPtr->isAdvRecvd, state);
	scanFsmPtr->isAdvRecvd = state;
	return;
}

/**
 * @brief   Update 2-Way Acquisition ack state.
 */
static void PendCfmAck(L2_SCAN_FSM *scanFsmPtr)
{
	ASSERT(scanFsmPtr != NULL);
	DBG_INFO("Pending Cfm-Ack...\n");
	scanFsmPtr->isAckPending = true;
	return;
}

/*****************************************************************************/
/**
 * @brief   Update current Scan-Net stage
 *
 * @param   scanFsmPtr  A pointer to scan net fsm.
 *          newStage    New state.
 *
 * @return  NONE.
 *
 ******************************************************************************/
static void StageUpdate(L2_SCAN_FSM *scanFsmPtr, SCAN_STAGE newStage)
{
	ASSERT(newStage >= L2_SCAN_NONE_STAGE && newStage <= L2_SCAN_CFM_STAGE);
	DBG_INFO("ScanNet current stage: %" PRIu8 " -> ScanNet new stage: %" PRIu8 " \n",
			 scanFsmPtr->scanStage, newStage);
	scanFsmPtr->scanStage = newStage;
}

/*****************************************************************************/
/**
 * @brief   Member node scan net InitScan stage handler.
 *
 * @param   instPtr  A pointer to l2 instance
 *
 * @return used slot (5ms slot).
 *
 ******************************************************************************/
static int32_t Scan_InitScanHandler(L2_INST *instPtr)
{
	ASSERT(instPtr != NULL);
	PHY_INST *phyRef = instPtr->config.phyInstPtr;
	L2_SCAN_FSM *scanFsmPtr = instPtr->scanFSM;
	DBG_INFO("** Net-Setup - InitScan Procedure (Attempts: %" PRIu8 ")**\n", scanFsmPtr->scanCnt);

	if (scanFsmPtr->scanCnt == 0)
	{
		// Update scan beam table
		L2_Scan_RefreashScanTable(instPtr);
	}
	else if (Phy_IsFrameDetected(phyRef))
	{
		// last scan beam number
		scanFsmPtr->beamNo = Phy_LastScanBeamNo(phyRef);
		// Update scan beam table
		L2_Scan_RefreashScanTable(instPtr);
	}

	if (scanFsmPtr->isLocked == true)
	{
		scanFsmPtr->beamNo = Phy_LastScanBeamNo(phyRef);
		Phy_SetBeamNo(phyRef, scanFsmPtr->beamNo, PHY_ANT_BEAM_16);
		L2_SetupNextSlot(instPtr, L2_TOR_RX, L2_ADV_FRAME);
		StageUpdate(scanFsmPtr, L2_SCAN_ADV_STAGE);
		instPtr->log.lastBeamWidth = PHY_ANT_BEAM_16;
	} /* Otherwise remain L2_SCAN_INIT_STAGE */
	else
	{
		/* Antenna steering (reserved, automatically accomplished by physical layer) */
		Phy_SetBeamNo(phyRef, scanFsmPtr->beamNo, PHY_ANT_BEAM_16);
		L2_SetupNextSlot(instPtr, L2_TOR_RX, L2_SCAN_FRAME);
		scanFsmPtr->scanCnt++;
		instPtr->log.lastBeamWidth = PHY_ANT_BEAM_16;
	}
	return SUCCESS;
}

/*****************************************************************************/
/**
 * @brief   Member node scan net BmAdvt stage handler.
 *
 * @param   scanFsmPtr  A pointer to scan net fsm.
 *          mainState    A pointer to main node state.
 *
 * @return used slot (5ms slot).
 *
 ******************************************************************************/
static int32_t Scan_AdvHandler(L2_INST *instPtr)
{
	ASSERT(instPtr != NULL);
	L2_SCAN_FSM *scanFsmPtr = instPtr->scanFSM;
	PHY_INST *phyRef = instPtr->config.phyInstPtr;
	TMC_INST *tmcRef = instPtr->config.tmcInstPtr;
	DBG_INFO("** Net-Setup - Advertisement Procedure (Timeout: %" PRIu8 ") **\n", scanFsmPtr->advTimeout);

	// if received a valid bm frame.
	if (scanFsmPtr->isAdvRecvd == true)
	{
		// last scan beam number
		scanFsmPtr->beamNo = Phy_LastScanBeamNo(phyRef);
		// reset listen counter.
		scanFsmPtr->advTimeout = 0;

		// Update scan stage
		StageUpdate(scanFsmPtr, L2_SCAN_CFM_STAGE);

		// start a confirm frame reception if in the target slot
		if ((TimeCtrl_GetIntCnt(tmcRef) + 1) % CFM_FRAME_SLOTS == 0)
		{
			// using pull mode to receive confirm frame
			// since first time sync procedure is accomplished in ADV stage.
			Phy_SetBeamWidth(phyRef, PHY_ANT_BEAM_16);
			Phy_SetBeamNo(phyRef, scanFsmPtr->beamNo, PHY_ANT_BEAM_16);
			Phy_SetMode(phyRef, PHY_MODE_PULL);
			L2_SetupNextSlot(instPtr, L2_TOR_RX, L2_CFM_FRAME);
			scanFsmPtr->cfmTimeout++; // increase counter.
			instPtr->log.lastBeamWidth = PHY_ANT_BEAM_16;
		}
		// otherwise skip...
		return SUCCESS;
	}
	// no valid bm frame was received.
	else
	{
		/* if time out reached, go back to init scan stage. */
		if (scanFsmPtr->advTimeout > ADV_LISTEN_TIMEOUT)
		{
			/* Antenna steering (reserved, automatically accomplished by physical layer) */
			Phy_SetBeamNo(phyRef, scanFsmPtr->beamNo, PHY_ANT_BEAM_16);
			L2_SetupNextSlot(instPtr, L2_TOR_RX, L2_SCAN_FRAME);
			DBG_WARNING("Adv timeout, restart net scan from L2_SCAN_INIT_STAGE.\n");
			L2_Scan_Reset(scanFsmPtr);
			instPtr->log.lastBeamWidth = PHY_ANT_BEAM_16;
		}
		else
		{
			/* Antenna steering (reserved, automatically accomplished by physical layer) */
			Phy_SetBeamNo(phyRef, scanFsmPtr->beamNo, PHY_ANT_BEAM_16);
			L2_SetupNextSlot(instPtr, L2_TOR_RX, L2_ADV_FRAME);
			scanFsmPtr->advTimeout++;
			instPtr->log.lastBeamWidth = PHY_ANT_BEAM_16;
		}
		return SUCCESS;
	}
}

/*****************************************************************************/
/**
 * @brief   Scan net 2Way-Acq stage handler.
 *
 * @param   instPtr	a pointer to linklayer layer instance
 *
 * @return used slot (5ms slot).
 *
 ******************************************************************************/
static int32_t Scan_CfmHandler(L2_INST *instPtr)
{
	ASSERT(instPtr != NULL);
	L2_SCAN_FSM *scanFsmPtr = instPtr->scanFSM;
	PHY_INST *phyRef = instPtr->config.phyInstPtr;
	DBG_INFO("** Net-Setup - Confirm Procedure (Timeout: %" PRIu8 ") **\n", scanFsmPtr->cfmTimeout);

	// 2 way acq failed, back to init stage.
	if (scanFsmPtr->cfmTimeout >= CFM_LISTEN_TIMEOUT)
	{
		DBG_WARNING("Cmf timeout, restart net scan from L2_SCAN_INIT_STAGE.\n");
		L2_Scan_Reset(scanFsmPtr);
		return SUCCESS;
	}
	if (L2_GetNextSlotNum(instPtr) % CFM_FRAME_SLOTS == 0)
	{
		// using pull mode to receive confirm frame
		// since first time sync procedure is accomplished in ADV stage.
		Phy_SetBeamWidth(phyRef, PHY_ANT_BEAM_16);
		Phy_SetBeamNo(phyRef, scanFsmPtr->beamNo, PHY_ANT_BEAM_16);
		Phy_SetMode(phyRef, PHY_MODE_PULL);
		L2_SetupNextSlot(instPtr, L2_TOR_RX, L2_CFM_FRAME);
		scanFsmPtr->cfmTimeout++; // increase counter.
		instPtr->log.lastBeamWidth = PHY_ANT_BEAM_16;
	}
	return SUCCESS;
}

/*****************************************************************************/
/**
 * @brief   Packing Scan message to a bit array.
 *
 * @param   bitarr	pointer to bit array buffer.
 * @param   msgType	message type.
 *
 * @return	EPARAM
 *          SUCCESS
 *
 ******************************************************************************/
static int32_t ScanMsg_Packing(L2_INST *instPtr, L2_FRAME_TYPE type, uint8_t dstId)
{
	ASSERT(instPtr != NULL);
	int32_t Status;
	uint32_t dataChunk;
	uint8_t *buff = instPtr->sendPktData;
	if (type < L2_ADV_FRAME || type > L2_CFM_FRAME)
	{
		DBG_ERROR("Unexpected frame type: %" PRId8 ".\n", type);
		return EPARAM;
	}

	// Common section of link layer package
	dataChunk = L2_GetNextFrameNum(instPtr);
	L2_FrameInsertChunk(buff, L2_MSG_FRAME_NUM, L2_MSG_FRAME_NUM_LEN, &dataChunk);
	dataChunk = L2_GetNextSlotNum(instPtr);
	L2_FrameInsertChunk(buff, L2_MSG_SLOT_NUM, L2_MSG_SLOT_NUM_LEN, &dataChunk);
	dataChunk = L2_GetNodeId(instPtr);
	L2_FrameInsertChunk(buff, L2_MSG_SRC_ID, L2_MSG_SRC_ID_LEN, &dataChunk);
	dataChunk = dstId;
	L2_FrameInsertChunk(buff, L2_MSG_DST_ID, L2_MSG_DST_ID_LEN, &dataChunk);
	switch (type)
	{
	case L2_ADV_FRAME:
	{
		dataChunk = L2_ADV_FRAME;
		L2_FrameInsertChunk(buff, L2_MSG_TYPE, L2_MSG_TYPE_LEN, &dataChunk);

		SysMonitor_GetSysinfo(&(instPtr->sysInfo));
		// insert position and speed info
		L2_FrameInsertChunk(buff, L2_MSG_ADV_SRC_POSX, L2_MSG_ADV_SRC_POSX_LEN, &(instPtr->sysInfo.posX));
		L2_FrameInsertChunk(buff, L2_MSG_ADV_SRC_POSY, L2_MSG_ADV_SRC_POSY_LEN, &(instPtr->sysInfo.posY));
		L2_FrameInsertChunk(buff, L2_MSG_ADV_SRC_POSZ, L2_MSG_ADV_SRC_POSZ_LEN, &(instPtr->sysInfo.posZ));

		// Insert net start time
		L2_FrameInsertChunk(buff, L2_MSG_ADV_SRC_NETSTART_TIME, L2_MSG_ADV_SRC_NETSTART_TIME_LEN, &(instPtr->netStartTime));

		// Append CRC
		Status = L2_CrcAppend(buff, L2_ADV_PACK_LEN - L2_MSG_ADV_SVC_CRC_LEN, L2_MSG_ADV_SVC_CRC, L2_CRC16_1021);
		if (Status != SUCCESS)
		{
			DBG_ERROR("Fail to append CRC, error code: %" PRId32 ".\n", Status);
			return Status;
		}
		break;
	}
	case L2_CFM_FRAME:
	{
		dataChunk = L2_CFM_FRAME;
		L2_FrameInsertChunk(buff, L2_MSG_TYPE, L2_MSG_TYPE_LEN, &dataChunk);

		SysMonitor_GetSysinfo(&(instPtr->sysInfo));
		// insert position and speed info
		L2_FrameInsertChunk(buff, L2_MSG_CFM_SRC_POSX, L2_MSG_CFM_SRC_POSX_LEN, &(instPtr->sysInfo.posX));
		L2_FrameInsertChunk(buff, L2_MSG_CFM_SRC_POSY, L2_MSG_CFM_SRC_POSY_LEN, &(instPtr->sysInfo.posY));
		L2_FrameInsertChunk(buff, L2_MSG_CFM_SRC_POSZ, L2_MSG_CFM_SRC_POSZ_LEN, &(instPtr->sysInfo.posZ));
		L2_FrameInsertChunk(buff, L2_MSG_CFM_SRC_SPEEDX, L2_MSG_CFM_SRC_SPEEDX_LEN, &(instPtr->sysInfo.vX));
		L2_FrameInsertChunk(buff, L2_MSG_CFM_SRC_SPEEDY, L2_MSG_CFM_SRC_SPEEDY_LEN, &(instPtr->sysInfo.vY));
		L2_FrameInsertChunk(buff, L2_MSG_CFM_SRC_SPEEDZ, L2_MSG_CFM_SRC_SPEEDZ_LEN, &(instPtr->sysInfo.vZ));

		// Packing extra payload
		uint32_t dataId;
		if (L2_GetNodeType(instPtr) == L2_NODE_HEAD)
		{
			SysMonitor_GetSendPayload(buff + L2_MSG_CFM_PAYLOAD, &dataId, PAYLOAD_LEN_FLJ_TX);
		}
		else
		{
			SysMonitor_GetSendPayload(buff + L2_MSG_CFM_PAYLOAD, &dataId, PAYLOAD_LEN_LJ_TX);
		}

		L2_FrameInsertChunk(buff, L2_MSG_CFM_PAYLOAD_ID, L2_MSG_CFM_PAYLOAD_ID_LEN, &dataId);
		if (dataId == DATA_ID_NONE)
		{
			memset(buff + L2_MSG_CFM_PAYLOAD, 0xAA, L2_MSG_CFM_PAYLOAD_LEN);
		}

		// Append CRC
		Status = L2_CrcAppend(buff, L2_CMF_PACK_LEN - L2_MSG_CFM_CRC_LEN, L2_MSG_CFM_CRC, L2_CRC16_1021);
		if (Status != SUCCESS)
		{
			DBG_ERROR("Fail to append CRC, error code: %" PRId32 ".\n", Status);
			return Status;
		}

		// Logging...
		memcpy(instPtr->log.txLog.data, buff, L2_CMF_PACK_LEN);
		instPtr->log.txLog.dataId = dataId;
		break;
	}
	default:
	{
		DBG_ERROR("Unexpected frame type: %" PRId8 ".\n", type);
		return EPARAM;
	}
	}
	return SUCCESS;
}

/*****************************************************************************/
/**
 * @brief   Scan net packet handler.
 *
 * @param   instPtr	a pointer to linklayer layer instance
 * @param   msg A pointer to frame data buffer.
 *
 * @return
 *
 ******************************************************************************/
int32_t L2_Scan_PktHandler(L2_INST *instPtr, uint8_t *msg)
{
	ASSERT(instPtr != NULL);
	ASSERT(msg != NULL);
	int32_t Status;
	L2_SCAN_FSM *scanFsmPtr = instPtr->scanFSM;
	L2_FRAME_TYPE frameType = L2_NONE_FRAME;
	L2_FrameGetChunk(msg, L2_MSG_TYPE, L2_MSG_TYPE_LEN, &frameType);
	switch (frameType)
	{
	case L2_SCAN_FRAME:
	case L2_ADV_FRAME:
	{
		if (L2_GetLastOptFrameType(instPtr) == L2_SCAN_FRAME)
		{
			LockStateUpdate(scanFsmPtr, true);
			StageUpdate(scanFsmPtr, L2_SCAN_ADV_STAGE);
		}
		if (L2_GetNodeType(instPtr) == L2_NODE_HEAD)
		{
			DBG_ERROR("Unexpected call from head node, only member Node can handle L2_SCAN_FRAME and L2_ADV_FRAME.\n");
			Status = EUNEXP;
			break;
		}
		uint8_t nodeId;
		L2_FrameGetChunk(msg, L2_MSG_SRC_ID, L2_MSG_SRC_ID_LEN, &nodeId);
		NODE_ENTRY *node;
		node = L2_GetNodeById(instPtr->nodeList, nodeId);
		if (node == NULL)
		{
			node = L2_AppendNode(instPtr->nodeList, nodeId, L2_NODE_MEMBER);
			if (node == NULL)
			{
				DBG_ERROR("Failed to append new node [id: %" PRId8 "]", nodeId);
				Status = ENOMEM;
				break;
			}
		}
		// Update node info.
		float nodePos;
		L2_FrameGetChunk(msg, L2_MSG_ADV_SRC_POSX, L2_MSG_ADV_SRC_POSX_LEN, &nodePos);
		node->nodeInfo.pos.x = (double)nodePos;
		L2_FrameGetChunk(msg, L2_MSG_ADV_SRC_POSY, L2_MSG_ADV_SRC_POSY_LEN, &nodePos);
		node->nodeInfo.pos.y = (double)nodePos;
		L2_FrameGetChunk(msg, L2_MSG_ADV_SRC_POSZ, L2_MSG_ADV_SRC_POSZ_LEN, &nodePos);
		node->nodeInfo.pos.z = (double)nodePos;
		node->nodeInfo.beamNo = Phy_LastScanBeamNo(instPtr->config.phyInstPtr);

		// Reset node ttl
		node->ttlCnt = 0;

		uint32_t netstartTime;
		// Update net start time.
		L2_FrameGetChunk(msg, L2_MSG_ADV_SRC_NETSTART_TIME, L2_MSG_ADV_SRC_NETSTART_TIME_LEN, &netstartTime);
		L2_EVENT netSetupDoneEvent = {
			.event = L2_EV_NET_ADV_UPDATE,
			.msg = &netstartTime};
		AssertL2Event(instPtr, &netSetupDoneEvent);

		// Calculate time deviation
		uint32_t frameNum, slotNum = 0;
		L2_FrameGetChunk(msg, L2_MSG_FRAME_NUM, L2_MSG_FRAME_NUM_LEN, &frameNum);
		L2_FrameGetChunk(msg, L2_MSG_SLOT_NUM, L2_MSG_SLOT_NUM_LEN, &slotNum);
		Status = L2_GetTimeDeviation(instPtr, frameNum, slotNum, true, &(instPtr->log.timeDev));
		if (Status != SUCCESS)
		{
			DBG_ERROR("Failed to compute time deviation.\n")
			break;
		}

		// Time sync.
		L2_TimeAdjust(instPtr, &(instPtr->log.timeDev));

		// trigger flag
		AdvRecvStateUpdate(scanFsmPtr, true);
		Status = SUCCESS;
		break;
	}
	case L2_CFM_FRAME:
	{
		uint8_t nodeId;
		L2_FrameGetChunk(msg, L2_MSG_SRC_ID, L2_MSG_SRC_ID_LEN, &nodeId);
		NODE_ENTRY *node;
		node = L2_GetNodeById(instPtr->nodeList, nodeId);
		if (node == NULL)
		{
			node = L2_AppendNode(instPtr->nodeList, nodeId, L2_NODE_MEMBER);
			if (node == NULL)
			{
				DBG_ERROR("Failed to append new node [id: %" PRId8 "]", nodeId);
				Status = ENOMEM;
				break;
			}
		}
		// Update node info.
		float nodePos;
		L2_FrameGetChunk(msg, L2_MSG_CFM_SRC_POSX, L2_MSG_CFM_SRC_POSX_LEN, &nodePos);
		node->nodeInfo.pos.x = (double)nodePos;
		L2_FrameGetChunk(msg, L2_MSG_CFM_SRC_POSY, L2_MSG_CFM_SRC_POSY_LEN, &nodePos);
		node->nodeInfo.pos.y = (double)nodePos;
		L2_FrameGetChunk(msg, L2_MSG_CFM_SRC_POSZ, L2_MSG_CFM_SRC_POSZ_LEN, &nodePos);
		node->nodeInfo.pos.z = (double)nodePos;
		float nodeSpeed;
		L2_FrameGetChunk(msg, L2_MSG_CFM_SRC_SPEEDX, L2_MSG_CFM_SRC_SPEEDX_LEN, &nodeSpeed);
		node->nodeInfo.speed.x = (double)nodePos;
		L2_FrameGetChunk(msg, L2_MSG_CFM_SRC_SPEEDY, L2_MSG_CFM_SRC_SPEEDY_LEN, &nodeSpeed);
		node->nodeInfo.speed.y = (double)nodePos;
		L2_FrameGetChunk(msg, L2_MSG_CFM_SRC_SPEEDZ, L2_MSG_CFM_SRC_SPEEDZ_LEN, &nodeSpeed);
		node->nodeInfo.speed.z = (double)nodePos;

		// Reset node ttl
		node->ttlCnt = 0;

		// Calculate time deviation
		uint32_t frameNum, slotNum = 0;
		L2_FrameGetChunk(msg, L2_MSG_FRAME_NUM, L2_MSG_FRAME_NUM_LEN, &frameNum);
		L2_FrameGetChunk(msg, L2_MSG_SLOT_NUM, L2_MSG_SLOT_NUM_LEN, &slotNum);
		Status = L2_GetTimeDeviation(instPtr, frameNum, slotNum, true, &(instPtr->log.timeDev));
		if (Status != SUCCESS)
		{
			DBG_ERROR("Failed to compute time deviation.\n")
			break;
		}

		if (L2_GetNodeType(instPtr) != L2_NODE_HEAD)
		{
			// check if net setup finished.
			if (L2_isCxn2Net(instPtr) == false)
			{
				// Assert Net-Setup Done.
				L2_EVENT l2Event;
				l2Event.event = L2_EV_NET_SETUP_DONE;
				l2Event.msg = NULL;
				AssertL2Event(instPtr, &l2Event);

				// Assert update routine event...
				L2_RTNE_CONFIG newRtneConfig = {0};
				L2_EVENT rtneUpEvent =
					{
						.event = L2_ROUTINE_UPDATE,
						.msg = &newRtneConfig
					};
				newRtneConfig.rtneTable = initTable;
				newRtneConfig.rtnePrd = ARRAY_SIZE(initTable);
				AssertL2Event(instPtr, &rtneUpEvent);
			}
			PendCfmAck(instPtr->scanFSM);
			// Time sync.
			L2_TimeAdjust(instPtr, &(instPtr->log.timeDev));
		}
		else
		{
			if (L2_GetMainState(instPtr) == L2_INIT_STATE
				&& L2_GetNodeListLen(instPtr->nodeList) >= instPtr->config.netScale - 1)
			{
				// Assert Net-Setup Done.
				L2_EVENT l2Event;
				L2_NODE_STATE newState = L2_NORMAL_STATE;
				l2Event.event = L2_EV_MAIN_STATE_UPDATE;
				l2Event.msg = &newState;
				AssertL2Event(instPtr, &l2Event);
			}
		}

		// Get data payload
		uint32_t dataId;
		L2_FrameGetChunk(msg, L2_MSG_CFM_PAYLOAD_ID, L2_MSG_CFM_PAYLOAD_ID_LEN, &dataId);

		if (L2_GetNodeType(instPtr) == L2_NODE_HEAD)
		{
			SysMonitor_UpdateRecvPayload(msg + L2_MSG_CFM_PAYLOAD, dataId, PAYLOAD_LEN_FLJ_RX);
		}
		else
		{
			SysMonitor_UpdateRecvPayload(msg + L2_MSG_CFM_PAYLOAD, dataId, PAYLOAD_LEN_LJ_RX);
		}

		// Logging...
		memcpy(instPtr->log.rxLog.data, msg, L2_CMF_PACK_LEN);
		instPtr->log.rxLog.dataId = dataId;

		Status = SUCCESS;
		break;
	}
	default:
		DBG_ERROR("Unsupported frame type: %" PRId8 ".\n", frameType);
		Status = EUNEXP;
		break;
	}
	return Status;
}

/*****************************************************************************/
/**
 * @brief   Initialize scan FSM.
 *
 * @param   instPtr
 *
 * @return
 *
 ******************************************************************************/
int32_t L2_Scan_Init(L2_SCAN_FSM **scanFSMPtr)
{
	ASSERT(scanFSMPtr != NULL);
	*scanFSMPtr = (L2_SCAN_FSM *)malloc(sizeof(L2_SCAN_FSM));
	if (*scanFSMPtr == NULL)
	{
		DBG_ERROR("Failed to allocate memory for scanFsmPtr.\n");
		return ENOMEM;
	}
	L2_Scan_Reset(*scanFSMPtr);
	(*scanFSMPtr)->beamNo = 0;
	(*scanFSMPtr)->tableNo = 0;
	return SUCCESS;
}

/*****************************************************************************/
/**
 * @brief  Reset ScanNet FSM
 *
 * @param   scanFsmPtr a pointer to scan net  finite state machine
 *
 * @return  NONE
 *
 ******************************************************************************/
void L2_Scan_Reset(L2_SCAN_FSM *scanFSMPtr)
{
	ASSERT(scanFSMPtr != NULL);
	scanFSMPtr->isLocked = false;
	scanFSMPtr->isAdvRecvd = false;
	scanFSMPtr->isAckPending = false;
	scanFSMPtr->scanCnt = 0;
	scanFSMPtr->advTimeout = 0;
	scanFSMPtr->cfmTimeout = 0;
	scanFSMPtr->scanStage = L2_SCAN_NONE_STAGE;
}

/*****************************************************************************/
/**
 * @brief  Destroy ScanNet FSM, free memory
 *
 * @param   scanFsmPtr a pointer to scan net  finite state machine
 *
 * @return  NONE
 *
 ******************************************************************************/
void L2_Scan_Destroy(L2_SCAN_FSM *scanFSMPtr)
{
	free(scanFSMPtr);
}

/*****************************************************************************/
/**
 * @brief  Refresh scan beam table.
 *
 * @param   instPtr	a pointer to linklayer layer instance
 *
 * @return  NONE
 *
 ******************************************************************************/
void L2_Scan_RefreashScanTable(L2_INST *instPtr)
{
	ASSERT(instPtr != NULL);
	L2_SCAN_FSM *scanFsmPtr = instPtr->scanFSM;
	PHY_INST *phyRef = instPtr->config.phyInstPtr;
	if (scanFsmPtr->tableNo == 0)
	{
		Phy_SetBeamTable(phyRef, antNrrwPattern_0, scanFsmPtr->beamNo);
		scanFsmPtr->tableNo = 1;
	}
	else
	{
		Phy_SetBeamTable(phyRef, antNrrwPattern_1, scanFsmPtr->beamNo);
		scanFsmPtr->tableNo = 0;
	}
}

/*****************************************************************************/
/**
 * @brief   Execute a member node scan net procedure.
 *
 * @param   instPtr	a pointer to linklayer layer instance
 *
 * @return  used slot (5ms slot).
 *
 ******************************************************************************/
int32_t L2_Scan_Proc(L2_INST *instPtr)
{
	L2_SCAN_FSM *scanFSM = instPtr->scanFSM;
	if (L2_GetNodeType(instPtr) == L2_NODE_HEAD)
	{
		DBG_ERROR("Only member node needs to execute L2_Scan_Proc. \n");
		return FAILURE;
	}
	int32_t Status;
	DBG_INFO("-------- ScanNet Process --------\n");
	switch (scanFSM->scanStage)
	{
	case L2_SCAN_NONE_STAGE:
		/* Start Scan. */
		StageUpdate(scanFSM, L2_SCAN_INIT_STAGE);
		Status = Scan_InitScanHandler(instPtr);
		break;
	case L2_SCAN_INIT_STAGE:
		Status = Scan_InitScanHandler(instPtr);
		break;
	case L2_SCAN_ADV_STAGE:
		Status = Scan_AdvHandler(instPtr);
		break;
	case L2_SCAN_CFM_STAGE:
		Status = Scan_CfmHandler(instPtr);
		break;
	default:
		DBG_ERROR("Unexpected scan net stage: %" PRId8 ".\n", scanFSM->scanStage);
		Status = FAILURE;
		break;
	}
	return Status;
}

/*****************************************************************************/

/**
 * @brief   Execute a scan net Routine procedure.
 *
 * @param   rtneEntry  Routine configuration
 *
 * @return  used slot (5ms slot).
 *
 ******************************************************************************/
int32_t L2_Scan_Routine(L2_INST *instPtr, const L2_RTNE_TABLE_ENTRY *rtneEntry)
{
	ASSERT(instPtr != NULL);
	L2_TOR_TYPE torState;
	int32_t Status;
	const NODE_ENTRY *commNode;
	PHY_INST *phyRef = instPtr->config.phyInstPtr;
	DBG_INFO("-------- Scan Routine --------\n");

	if (rtneEntry->slotSeq != 0)
	{
		return SUCCESS; // skip
	}

	if (L2_GetNodeType(instPtr) != L2_NODE_HEAD)
	{
		if (rtneEntry->dst == L2_GetNodeId(instPtr) || rtneEntry->dst == L2_BROADCAST_ID)
		{
			torState = L2_TOR_RX;
			commNode = L2_GetNodeById(instPtr->nodeList, rtneEntry->src);
		}
		else if (rtneEntry->src == L2_GetNodeId(instPtr) || rtneEntry->src == L2_BROADCAST_ID)
		{
			torState = L2_TOR_TX;
			commNode = L2_GetNodeById(instPtr->nodeList, rtneEntry->dst);
		}
		else
		{
			torState = L2_TOR_SUSPEND;
		}

		// Setup antenna beam
		Phy_SetBeamWidth(phyRef, PHY_ANT_BEAM_16);
		instPtr->log.lastBeamWidth = PHY_ANT_BEAM_16;
		if (commNode != NULL)
		{
			Phy_SetBeamNo(phyRef, commNode->nodeInfo.beamNo, PHY_ANT_BEAM_16);
		}
	}
	else
	{
		if (rtneEntry->dst == L2_GetNodeId(instPtr))
		{
			torState = L2_TOR_RX;
		}
		else if (rtneEntry->src == L2_GetNodeId(instPtr))
		{
			torState = L2_TOR_TX;
		}
		else
		{
			torState = L2_TOR_SUSPEND;
		}
		// Setup antenna beam
		Phy_SetBeamWidth(phyRef, PHY_ANT_BEAM_120);
		instPtr->log.lastBeamWidth = PHY_ANT_BEAM_120;
	}

	switch (rtneEntry->slotType)
	{
	case L2_SLOT_SCAN:
		if (L2_GetNodeType(instPtr) != L2_NODE_HEAD && torState == L2_TOR_TX)
		{
			DBG_ERROR("Only head node can send init-scan Frame.\n");
			Status = FAILURE;
			goto routine_err;
		}
		L2_SetupNextSlot(instPtr, torState, L2_SCAN_FRAME);
		break;

	case L2_SLOT_ADVERTISE:
		if (torState == L2_TOR_TX)
		{
			if (L2_GetNodeType(instPtr) != L2_NODE_HEAD)
			{
				DBG_ERROR("Only head node can send ADV Frame.\n");
				Status = FAILURE;
				goto routine_err;
			}
			memset(instPtr->sendPktData, 0xAA, L2_PACK_LEN_MAX);
			if (ScanMsg_Packing(instPtr, L2_ADV_FRAME, rtneEntry->dst) != SUCCESS)
			{
				Status = FAILURE;
				goto routine_err;
			}
		}
		/* Antenna setting (reserved.) */
		L2_SetupNextSlot(instPtr, torState, L2_ADV_FRAME);
		break;

	case L2_SLOT_CONFIRM:
		if (torState == L2_TOR_TX)
		{
			if (L2_GetNodeType(instPtr) != L2_NODE_HEAD)
			{
				if (instPtr->scanFSM->isAckPending == false)
				{
					DBG_INFO("Member node has no pending CFM-Ack frame.\n");
					break;
				}
			}
			memset(instPtr->sendPktData, 0xAA, L2_PACK_LEN_MAX);
			if (ScanMsg_Packing(instPtr, L2_CFM_FRAME, rtneEntry->dst) != SUCCESS)
			{
				Status = FAILURE;
				goto routine_err;
			}
		}
		/* Antenna setting (reserved.) */
		L2_SetupNextSlot(instPtr, torState, L2_CFM_FRAME);
		break;
	default:
		DBG_ERROR("Cannot start a routine for slot type [%" PRId8 "] properly.\n", rtneEntry->slotType);
		Status = FAILURE;
		goto routine_err;
	}
	return SUCCESS;
routine_err:
	return Status;
}

/** @} LinkLayer_Scan*/
/** @} LinkLayer*/
