///@brief Callback for the reception of good wireless headers
///
///This function then polls the PHY to determine if the entire packet passes checksum
///thereby triggering the transmission of the ACK and the transmission of the received
///data over Ethernet.
///@param packet Pointer to received Macframe
int phyRx_goodHeader_callback(Macframe* packet){
	
	unsigned char state = PHYRXSTATUS_INCOMPLETE;
	unsigned char srcNode;
	unsigned char shouldSend = 0;
	
	//Calculate the node ID from the packet's source MAC address
	srcNode = ADDR_TO_NODEID( (packet->header.srcAddr) );
	
	//If the packet is addressed to this node
	if( packet->header.destAddr == (NODEID_TO_ADDR(myID)) ) {
		
		switch(packet->header.pktType) {
				//If received packet is data
			case PKTTYPE_DATA:
				//At this point, we have pre-loaded the PHY transmitter with the ACK in hoping that
				//the packet passes checksum. Now we wait for the state of the received to packet
				//to move from PHYRXSTATUS_INCOMPLETE to either PHYRXSTATUS_GOOD or PHYRXSTATUS_BAD
				
				//Poll the PHY until the payload is declared good or bad
				state = warpmac_finishPhyRecv();
				
				if(state & PHYRXSTATUS_GOOD){
					//The auto-reponder will send the pre-programmed ACK automatically
					//User code only needs to update its stats, then check to see the PHY is finished transmitting
					
					//Toggle the top LEDs
					warpmac_incrementLEDHigh();
					
					//Update the right-hex display with the current sequence number
					warpmac_leftHex(0xF & (packet->header.seqNum));
					
					//Starts the DMA transfer of the payload into the EMAC
					warpmac_prepPktToNetwork((void *)warpphy_getBuffAddr(pktBuf_rx)+NUM_HEADER_BYTES, (packet->header.length));
					
					//Blocks until the PHY is finished sending and enables the receiver
					warpmac_finishPhyXmit();
					
					//Waits until the DMA transfer is complete, then starts the EMAC
					warpmac_startPktToNetwork((packet->header.length));
				}
				
				if(state & PHYRXSTATUS_BAD) {
					warpmac_incrementLEDLow();
				}
				
				break; //END PKTTYPE_DATA
				
			case PKTTYPE_ACK:
				//Clear the TIMEOUT and enable Ethernet
				if(warpmac_inTimeout()) {
					warpmac_incrementLEDHigh();
					
					//Clear the timeout timer, set when we transmitted the data packet
					warpmac_clearTimer(TIMEOUT_TIMER);
					
					//Clear the remaining transmit count to assure this packet won't be re-transmitted
					txMacframe.header.remainingTx = 0;
					
					//Start a backoff, to gaurantee a random time before attempting to transmit again
					warpmac_setTimer(BACKOFF_TIMER);
					
					//Re-enable EMAC polling immediately (for testing; using the post-ACK backoff is better for real use)
					//warpmac_enableDataFromNetwork();
				}
				else {
					//Got an unexpected ACK; ignore it
				}
				
				break; //END PKTTYPE_ACK
		}
	}
	else {
		state = warpmac_finishPhyRecv();
	}
	
	//Return 0, indicating we didn't clear the PHY status bits (WARPMAC will handle it)
	return 0;
}
///@brief Callback for the reception of good wireless headers
///
///This function then polls the PHY to determine if the entire packet passes checksum
///thereby triggering the transmission of the received data over Ethernet.
///@param packet Pointer to received Macframe
int phyRx_goodHeader_callback(Macframe* packet)
{
	u32 gains;
	gains = ofdm_txrx_mimo_ReadReg_Rx_Gains(0);
	warpmac_leftHex( (gains>>5) & 0x3);

	//xil_printf("GH %5d %2d %1d\n", ofdm_txrx_mimo_ReadReg_Rx_PktDet_midPktRSSI_antA(), gains&0x1F, (gains>>5)&0x3);

	void* txPktPtr;

	//Initialize the Rx pkt state variable
	unsigned char state = PHYRXSTATUS_INCOMPLETE;

	if(reportBERviaWarpnet) {
		//Send a copy of the just-received packet to the BER calculating app
		//BER packets are built from:
		// Ethernet header [0:15]
		// MAC/PHY header [0:23] generated above
		// Actual transmitted payload (randomly generated and recorded in the PHY) [0:length-1]
		coprocEthPktHeader.pktLength = sizeof(warpnetEthernetPktHeader) + sizeof(phyHeader) + (packet->header.length);
		coprocEthPktHeader.ethType = WARPNET_ETHTYPE_NODE2BER; 
		
		txPktPtr = (void *)warpphy_getBuffAddr(WARPNET_NODE2COPROC_PKTBUFFINDEX);
		memcpy(txPktPtr, &(coprocEthPktHeader), sizeof(warpnetEthernetPktHeader));
		txPktPtr += sizeof(warpnetEthernetPktHeader);
		memcpy(txPktPtr, (void*)&(packet->header), sizeof(phyHeader));
		txPktPtr += sizeof(phyHeader);
	}
	
	//Poll the PHY; blocks until the PHY declares the payload good or bad
	state = warpmac_finishPhyRecv();

	if(state & PHYRXSTATUS_GOOD)
	{
		//We're in dummy packet mode, so we shouldn't copy the received packet to Etherent
		
		//Toggle the top user LEDs
		warpmac_incrementLEDHigh();
		
		perStruct.numPkts_rx_good++;
	}

	if(state & PHYRXSTATUS_BAD)
	{
		//If the received packet has errors, drop it (i.e. don't send it via Ethernet)

		//Toggle the bottom user LEDs
		warpmac_incrementLEDLow();

		perStruct.numPkts_rx_goodHdrBadPyld++;
	}

	//Send the received packet for BER processing
	if(reportBERviaWarpnet) {
		memcpy(txPktPtr, (void *)(warpphy_getBuffAddr(pktBuf_rx)+sizeof(phyHeader)), packet->header.length);
		
		warpmac_prepPktToNetwork((void *)warpphy_getBuffAddr(WARPNET_NODE2COPROC_PKTBUFFINDEX), coprocEthPktHeader.pktLength);
		warpmac_startPktToNetwork(coprocEthPktHeader.pktLength);
	}

	//Return 0, indicating this function did not clear the PHY status bits; WARPMAC will handle this
	return 0;
}
///@brief Callback for the reception of good wireless headers
///
///This function then polls the PHY to determine if the entire packet passes checksum
///thereby triggering the transmission of the received data over Ethernet.
///@param packet Pointer to received Macframe
int phyRx_goodHeader_callback(Macframe* packet)
{

//WORKSHOP PSEUDOCODE:
//1) Instantiate an unsigned char variable to monitor the OFDM receiver's state. Default this state variable to "PHYRXSTATUS_INCOMPLETE"
//2) Check the 'destAddr' element in the 'header' struct of the 'packet' Macframe. Only proceed if this value matches 'myID'
//			Note: myID is a global that is assigned in main(), based on your node's DIP switch setting at boot
//3) Check the 'pktType' field of the header.
//  If 'PKTTYPE_DATA'
//		4) Poll the state of the state of the receiver using "warpmac_finishPhyRecv." Block until the state turns to either "PHYRXSTATUS_GOOD" or "PHYRXSTATUS_BAD"
//		If "PHYRXSTATUS_GOOD"
//			5a) Animate the top two LEDs to visualize this behavior using the "warpmac_incrementLEDHigh" function
//			6a) Copy the received "Macframe" to the Ethernet MAC (Emac) using "warpmac_prepPktToNetwork"
//					Note: The first argument of this function is the beginning of the packet that you want sent over the wire.
//					  	  This does NOT include all of the extra wireless MAC header information of the packet. The first byte
//					  	   of the payload is located at (void *)warpphy_getBuffAddr(pktBuf_rx)+NUM_HEADER_BYTES,
//					  	  where pktBuf_rx is an already defined global in this file (noMac.c) that specifies the location of
//					  	  the Macframe in the PHY.
//			7a) Wait for the ACK to finish sending with "warpmac_finishPhyXmit"
//					Note: Even though we did not explicitly transmit an ACK via software, we know that one is currently being sent
//						  since we configured the autoresponder to do so.
//			8a) Start the Emac using "warpmac_startPktToNetwork"
//				Note: The only argument to this function is the length (in bytes) of the packet to be sent. This length is stored in the
//				the 'length' field of the 'header' struct belonging to the 'packet' Macframe (i.e. packet->header.length).
//		If "PHYRXSTATUS_BAD"
//			5b) Animate the bottom two LEDs to visualize this behavior using the "warpmac_incrementLEDLow" function


/**********************USER CODE STARTS HERE***************************/
	unsigned char state = PHYRXSTATUS_INCOMPLETE;
	char shouldSend = 0;
	
	//If the packet is addressed to this node
	if( packet->header.destAddr == (NODEID_TO_ADDR(myID)) )
	{
		switch(packet->header.pktType){
			//If received packet is data
			case PKTTYPE_DATA:
				//At this point, we have pre-loaded the PHY transmitter with the ACK in hoping that
				// the packet passes checksum. Now we wait for the state of the received to packet
				// to move from PHYRXSTATUS_INCOMPLETE to either PHYRXSTATUS_GOOD or PHYRXSTATUS_BAD

				//Blocks until the PHY declares the payload good or bad
				state = warpmac_finishPhyRecv();

				if(state & PHYRXSTATUS_GOOD){
					//The auto-reponder will send the pre-programmed ACK automatically
					//User code only needs to update its own state, then check to see the PHY
					// is finished transmitting

					//Toggle the top LEDs
					warpmac_incrementLEDHigh();

					//Check if this is a new packet; only send it over Ethernet if it's new
					if(packet->header.seqNum != lastRxSeqNum) {
						shouldSend = 1;
						lastRxSeqNum = packet->header.seqNum;
					}
					
					//Starts the DMA transfer of the payload into the EMAC
					if(shouldSend) warpmac_prepPktToNetwork((void *)warpphy_getBuffAddr(pktBuf_rx)+NUM_HEADER_BYTES, (packet->header.length));

					//Blocks until the PHY is finished sending and enables the receiver
					warpmac_finishPhyXmit();

					//Waits until the DMA transfer is complete, then starts the EMAC
					if(shouldSend) warpmac_startPktToNetwork((packet->header.length));
				}

				if(state & PHYRXSTATUS_BAD){
					warpmac_incrementLEDLow();
				}

				break; //END PKTTYPE_DATA
			default:
				//Invalid packet type; ignore
				break;
		}
	}//END rx.destAddr == myID
	else {
		state = warpmac_finishPhyRecv();
	}
	/**********************USER CODE ENDS HERE***************************/

	//Return 0, indicating we didn't clear the PHY status bits (WARPMAC will handle it)
	return 0;
}
///@brief Callback for the reception of good wireless headers
///
///This function then polls the PHY to determine if the entire packet passes checksum
///thereby triggering the transmission of the received data over Ethernet.
///@param packet Pointer to received Macframe
int phyRx_goodHeader_callback(Macframe* packet){

//WORKSHOP PSEUDOCODE:
//1) Instantiate an unsigned char variable to monitor the OFDM receiver's state. Default this state variable to "PHYRXSTATUS_INCOMPLETE"
//2) Instantiate a new Macframe to represent the acknowledgment packet you send if the payload of received packet is error-free
//3) Check the 'destAddr' element in the 'header' struct of the 'packet' Macframe. Only proceed if this value matches 'myID'
//			Note: myID is a global that is assigned in main(), based on your node's DIP switch setting at boot
//4) Check the 'pktType' field of the header.
//	If 'PKTTYPE_DATA'
//		5) Fill in the Macframe you created at the top of this function. You must fill in the following fields:
//			- 'length' should be 0 (i.e. there is no payload present in an ACK packet)
//			- 'pktType' should be 'ACKPACKET' in order to differentiate this packet from data frames
//			- 'fullRate' should be 'HDR_FULLRATE_QPSK' (the ACK has no full-rate payload, but this field msut still have a valid value)
//			- 'codeRate' should be 'HDR_CODE_RATE_34' (the ACK has no coded payload, but this field msut still have a valid value)
//			- 'srcAddr' should be set to your node's ID (myID)
//			- 'destAddr' should be set to the 'srcAddr' of the received packet
//		6) Copy the ACK into the 'pktBuf_tx_ACK' PHY buffer using "warpmac_prepPhyForXmit"
//		7) Poll the state of the state of the receiver using "warpmac_finishPhyRecv." Block until the state turns to either "PHYRXSTATUS_GOOD" or "PHYRXSTATUS_BAD"
//		If "GOODPACKET"
//			9a) Send the ACK using 'warpmac_startPhyXmit'
//			10a) Animate the top two LEDs to visualize this behavior using the "warpmac_incrementLEDHigh" function
//		    11a) Using the received packet header's sequence number, check if this is a duplicate packet that you have already transmitted via Ethernet. If not:
//				  Copy the received "Macframe" to the Ethernet MAC (Emac) using "warpmac_prepPktToNetwork"
//					Note: The first argument of this function is the beginning of the packet that you want sent over the wire.
//					  	  This does NOT include all of the extra wireless MAC header information of the packet. The first byte
//					  	   of the payload is located at (void *)warpphy_getBuffAddr(pktBuf_rx)+NUM_HEADER_BYTES,
//					  	  where pktBuf_rx is an already defined global in this file (noMac.c) that specifies the location of
//					  	  the Macframe in the PHY.
//			12a) Wait for the ACK to finish sending with "warpmac_finishPhyXmit"
//			13a) Start the Emac using "warpmac_startPktToNetwork"
//				Note: The only argument to this function is the length (in bytes) of the packet to be sent. This length is stored in the
//				the 'length' field of the 'header' struct belonging to the 'packet' Macframe (i.e. packet->header.length).
//		If "BADPACKET"
//			9b) Animate the bottom two LEDs to visualize this behavior using the "warpmac_incrementLEDLow" function


/**********************USER CODE STARTS HERE***************************/
	unsigned char state = PHYRXSTATUS_INCOMPLETE;
	Macframe ackPacket;
	char shouldSend = 0;

	//If the packet is addressed to this node
	if( packet->header.destAddr == (NODEID_TO_ADDR(myID)) )
	{
		switch(packet->header.pktType) {
			//If received packet is data
			case PKTTYPE_DATA:

				//Fill in the ACK header
				ackPacket.header.length = 0;
				ackPacket.header.pktType = PKTTYPE_ACK;
				ackPacket.header.fullRate = HDR_FULLRATE_QPSK;
				ackPacket.header.codeRate = HDR_CODE_RATE_34;
				ackPacket.header.srcAddr = NODEID_TO_ADDR(myID);
				ackPacket.header.destAddr = packet->header.srcAddr;

				//Copy the header over to packet pktBuf_tx_ACK
				warpmac_prepPhyForXmit(&ackPacket, pktBuf_tx_ACK);

				//Blocks until the PHY declares the payload good or bad
				state = warpmac_finishPhyRecv();

				if(state & PHYRXSTATUS_GOOD) {
					warpmac_startPhyXmit(pktBuf_tx_ACK);

					//Toggle the top LEDs
					warpmac_incrementLEDHigh();

					//Check if this is a new packet; only send it over Ethernet if it's new
					if(packet->header.seqNum != lastRxSeqNum) {
						shouldSend = 1;
						lastRxSeqNum = packet->header.seqNum;
					}
					
					//Starts the DMA transfer of the payload into the EMAC
					if(shouldSend) warpmac_prepPktToNetwork((void *)warpphy_getBuffAddr(pktBuf_rx)+NUM_HEADER_BYTES, (packet->header.length));

					//Blocks until the PHY is finished sending and enables the receiver
					warpmac_finishPhyXmit();

					//Waits until the DMA transfer is complete, then starts the EMAC
					if(shouldSend) warpmac_startPktToNetwork((packet->header.length));
				}

				if(state & PHYRXSTATUS_BAD) {
					warpmac_incrementLEDLow();
				}

				break; //END PKTTYPE_DATA
			default:
				//Invalid packet type; ignore this reception
				break;
		}
	}//END rx.destAddr == myID
	else {
		state = warpmac_finishPhyRecv();
	}
	/**********************USER CODE ENDS HERE***************************/

	//Return 0, indicating we didn't clear the PHY status bits (WARPMAC will handle it)
	return 0;
}