/** \file utilities.c ********************************************************
 * 
 *             Project: Maxim Plug-in Peripheral Modules
 *            Filename: utilities.c
 *         Description: This module contains a collection of general utility
 *                      functions which are not specific to any particular
 *                      module.
 * 
 *    Revision History:
 *\n       4-13-12 Rev 1.0 Seth Messimer   Initial Release
 *\n       7-20-12 Rev 1.4 Nathan Young    Additional functions
 * 
 *  --------------------------------------------------------------------
 * 
 *    This code follows the following naming conventions.
 * 
 * 	  char                   chPmodValue
 * 	  char (array)           sPmodString[16]
 * 	  float                  fPmodValue
 * 	  int                    nPmodValue
 * 	  int (array)            anPmodValue[16]
 * 	  u16                    uPmodValue
 * 	  u8                     uchPmodValue
 * 	  u8 (array)             auchPmodBuffer[16]
 * 	  unsigned int           unPmodValue
 * 	  int *                  punPmodValue
 * 
 * ------------------------------------------------------------------------- */
/*
 * Copyright (C) 2012 Maxim Integrated Products, All Rights Reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included
 * in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY,  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 * IN NO EVENT SHALL MAXIM INTEGRATED PRODUCTS BE LIABLE FOR ANY CLAIM, DAMAGES
 * OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 *
 * Except as contained in this notice, the name of Maxim Integrated Products
 * shall not be used except as stated in the Maxim Integrated Products
 * Branding Policy.
 *
 * The mere transfer of this software does not imply any licenses
 * of trade secrets, proprietary technology, copyrights, patents,
 * trademarks, maskwork rights, or any other form of intellectual
 * property whatsoever. Maxim Integrated Products retains all ownership rights.
 *
 ***************************************************************************/

#include "utilities.h"
#include "MAXREFDES14.h"

void print_asterisks(int nQuantity)
/**
* \brief       Print nQuantity of asterisks to the default Hyperterminal UART
*
* \param[in]   nQuantity    - number of asterisks to print
*
* \retval      None
*/
{
	int i=0;
	for(i=0;i<nQuantity;i++)
		printf("*");
}

int SpiRW( u32 unPeripheralAddressSPI, unsigned int unCPHA, unsigned int unCPOL,
		u8* auchWriteBuf, u8* auchReadBuf, int unNumBytes, u8 uchCsActiveHigh )
/**
* \brief       Perform a SPI read or write.
* \par         Details
*              This function provides a combination SPI Read and Write to the chosen SPI port in the design
*              CPHA and CPOL can be set to 0 or 1
*              Pointers are provided to u8 buffers containing the data to be written and received
*              Data in the auchWriteBuf will be clocked out (MSB first) onto the MOSI pin
*              Data from the MISO pin will be placed into the auchReadBuf
*              uchCsActiveHigh==TRUE allows SS configurations to be used
*              uchCsActiveHigh==FALSE allows SS# configurations to be used
*
* \param[in]   unPeripheralAddressSPI         - @help
* \param[in]   unCPHA             - phase of SCK (edge to trigger on). 0=Leading edge, 1=Trailing edge
* \param[in]   unCPOL             - polarity of SCK. 0=Active high, 1=Active low  
* \param[in]   auchWriteBuf       - pointer to write data buffer
* \param[in]   auchReadBuf        - pointer to read data buffer
* \param[in]   unNumBytes         - number of bytes to transfer
* \param[in]   uchCsActiveHigh    - polarity of slave select 0=active low, 1=active high
*
* \retval      Always returns 0
*/
{
	int i;
	unsigned int unControlData = 0x00000186;

	//If CPHA or CPOL = 1, we need to set the corresponding bits in the control register
	unControlData = unControlData | (unCPHA << 4);
	unControlData = unControlData | (unCPOL << 3);

	//Write config data to SPICR.  We need the inhibit bit=1.
	XSpi_WriteReg(unPeripheralAddressSPI, 0x60, unControlData);

	//Deassert CS to 1 to ensure SPI slave is inactive
	if( uchCsActiveHigh )
		XSpi_WriteReg(unPeripheralAddressSPI, 0x70, 0xFFFFFFFE);
	else
		XSpi_WriteReg(unPeripheralAddressSPI, 0x70, 0xFFFFFFFF);

	for( i = 0; i < unNumBytes; i++)
	{
		if( auchWriteBuf != 0 )
		{
			//Write data to SPIDTR.  This is the data that will be transferred to the SPI slave.
			XSpi_WriteReg(unPeripheralAddressSPI, 0x68, auchWriteBuf[ i ]);
			//Debug//printf( "Write %02x; ", auchWriteBuf[i]);
		}
		else
		{
			//Write data to SPIDTR.  This is the data that will be transferred to the SPI slave.
			XSpi_WriteReg(unPeripheralAddressSPI, 0x68, 0x00);
		}

		//Write config data to SPICR.  We need the inhibit bit=1.
		XSpi_WriteReg(unPeripheralAddressSPI, 0x60, unControlData);

		//Assert CS for our PMOD part
		if( uchCsActiveHigh )
			XSpi_WriteReg(unPeripheralAddressSPI, 0x70, 0xFFFFFFFF);
		else
			XSpi_WriteReg(unPeripheralAddressSPI, 0x70, 0xFFFFFFFE);

		//Un-inhibit our SPI master to transfer the data
		XSpi_WriteReg(unPeripheralAddressSPI, 0x60, unControlData & 0xFFFFFEFF);

		//Wait for transaction to complete.  Check to see if Tx_Empty flag is set before proceeding.
		while( !(XSpi_ReadReg( unPeripheralAddressSPI, 0x64 ) & 0x00000004) )
			;

		//Inhibit SPI master to prevent further action
		XSpi_WriteReg(unPeripheralAddressSPI, 0x60, unControlData);

		//Read received data
		if( (auchReadBuf != 0) )
		{
			auchReadBuf[ i ] = XSpi_ReadReg(unPeripheralAddressSPI, 0x6C);
			//Debug//printf( "Read %02x\r\n", auchReadBuf[i]);
		}
	}
	if( uchCsActiveHigh )
		XSpi_WriteReg(unPeripheralAddressSPI, 0x70, 0xFFFFFFFE);
	else
		XSpi_WriteReg(unPeripheralAddressSPI, 0x70, 0xFFFFFFFF);
	return 0;
}

void delay(int nStopValue)
/**
* \brief       Loop for nStopValue iterations to provide a delay.
* \par         Details
*              It is commonly used with the constant 'ABOUT_ONE_SECOND' defined in maximPMOD.h for 
*              setting approximate delays
*
* \param[in]   nStopValue    - number of iterations to loop
*
* \retval      None
*/
{
	int i=0;
	int a=0;

	for(i=0;i<nStopValue;i++)
	{
		a=i;
	}
}

void led_knight_rider(XGpio *pLED_GPIO, int nNumberOfTimes)
/**
* \brief       Blink a row of LEDs nNumberOfTimes times.
* \par         Details
*              The Digilent NEXYS-3 board has 8 green LEDs located above the toggle switches.
*              This function blinks them back/forth (a bit like the KITT car from Knight Rider)
*
* \param[in]   *pLED_GPIO    - address of the GPIO peripheral driving the LEDs in MicroBlaze memory map
*
* \retval      None
*/
{
	int i=0;
	int j=0;
	u8 uchLedStatus=0;

	// Blink the LEDs back and forth nNumberOfTimes
	for(i=0;i<nNumberOfTimes;i++)
	{
		for(j=0;j<8;j++)  // Scroll the LEDs up
		{
			uchLedStatus = 1 << j;
			XGpio_DiscreteWrite(pLED_GPIO, 1, uchLedStatus);
			delay(ABOUT_ONE_SECOND / 15);
		}

		for(j=0;j<8;j++)  // Scroll the LEDs up
		{
			uchLedStatus = 8 >> j;
				XGpio_DiscreteWrite(pLED_GPIO, 1, uchLedStatus);
				delay(ABOUT_ONE_SECOND / 15);
		}
	}
}

void max_configure_PMOD_port(u8 uchPmodPortA, u8 uchPmodPortB, u8 uchPmodPortC, u8 uchPmodPortD)
/**
* \brief       Configure driving peripherals on each Pmod port.
* \par         Details
*              The Maxim HDL hardware design for the Nexys 3 includes a multiplexer on each PMOD port to allow I2C, 
*              SPI, GPIO, and UART functionality to be selected on each port.
*              The standard configuration is (PortA = I2C, PortB = SPI, PortC = GPIO, PortD = UART)
*              This function is used to set the standard configuration in the main() function, as well as to 
*              optionally change the port config.  The 2-bit number used to define the port configuration is
*              encoded as follows:
* \n           00=UART, 01=SPI, 10=GPIO and 11=I2C
*
* \param[in]   uchPmodPortA    -  2-bit number to define configuration for Pmod port A 
* \param[in]   uchPmodPortB    -  2-bit number to define configuration for Pmod port B 
* \param[in]   uchPmodPortC    -  2-bit number to define configuration for Pmod port C 
* \param[in]   uchPmodPortD    -  2-bit number to define configuration for Pmod port D 
*
* \retval      TRUE if operation succeeded
*/
{
	XGpio xGpioPmodPortMuxIO;
	u8 uchPmodPortSelectBits=0;
	// The PMOD ports are configured with an 8 bit word sent to GPIO2
	// Bits 1:0 are for port #A
	// Bits 3:2 are for port #B
	// Bits 5:4 are for port #C
	// Bits 7:6 are for Port #D

	 //S = 2'b00   	=> UART active 	(PMOD_PORT_TYPE_UART)
	 //S=  2'b01   	=> SPI active 	(PMOD_PORT_TYPE_SPI)
	 //S = 2'b10  	=> GPIO active	(PMOD_PORT_TYPE_GPIO)
	 //S = 2'b11	=> I2C active 	(PMOD_PORT_TYPE_I2C)

	uchPmodPortSelectBits = (uchPmodPortD << 6) + (uchPmodPortC << 4) + (uchPmodPortB << 2) + uchPmodPortA;

	XGpio_Initialize(&xGpioPmodPortMuxIO, XPAR_AXI_GPIO_2_DEVICE_ID);
	XGpio_SetDataDirection(&xGpioPmodPortMuxIO, 1, 0x00);  // Set the GPIO2 direction to outputs
	XGpio_DiscreteWrite(&xGpioPmodPortMuxIO, 1, uchPmodPortSelectBits);
}

int check_if_i2c_device_is_present()
/**
* \brief       Test for SDA and SCL pullups.
* \par         Details
*              This function places the PMOD A port into GPIO mode briefly in order to sample the SDA and SCL lines
*              If they are high, then this implies that a pull-up is present, and hence a PMOD board is likely present
*
* \param       None   
*
* \retval      TRUE if pull-ups present, FALSE if pullups not present
*/
{
	XGpio xGpioPmodPortA;
	unsigned int unGpioPortData = 0;
	int nReturnVal=FALSE;

	// Configure Port A to be GPIO
	max_configure_PMOD_port(PMOD_PORT_TYPE_GPIO,PMOD_PORT_TYPE_SPI,PMOD_PORT_TYPE_GPIO,PMOD_PORT_TYPE_UART);

	// Set SCL and SDA to be inputs
	XGpio_Initialize(&xGpioPmodPortA, XPAR_AXI_GPIO_0_DEVICE_ID);
	XGpio_SetDataDirection(&xGpioPmodPortA, 1, 0x0C);  // Set the all pins to outputs, except pins SDA (pin3) and SCL (pin2)
	unGpioPortData = XGpio_DiscreteRead(&xGpioPmodPortA, 1);
	if(((unGpioPortData >> 2) & 0x03)==0x03)
	{
		printf("I2C Device is present\r\n");
		nReturnVal=TRUE;
	}
	else
	{
		nReturnVal=FALSE;
		print_asterisks(74);
		printf("******WARNING: Could not find pull-ups on SDA nor SCL ********************\r\n");
		printf("******Attempts to read/write may hang CPU ********************************\r\n");
		printf("******Recommend to go back to main menu and double-check I2C device.******\r\n");
		print_asterisks(74);
		delay(ABOUT_ONE_SECOND * 3);
	}

	delay(ABOUT_ONE_SECOND / 10);
	// Set the ports back to the standard configuration
	max_configure_PMOD_port(PMOD_PORT_TYPE_I2C,PMOD_PORT_TYPE_SPI,PMOD_PORT_TYPE_GPIO,PMOD_PORT_TYPE_UART);
	delay(ABOUT_ONE_SECOND / 10);

return(nReturnVal);
}

int number_raised_to_power(int nBase, int nExponent)
/**
* \brief       Raise nBase to the nExponent power (operates with integers only).
* \par         Details
*              Many Microblaze applications will not have math.h included due to limited memory space.
*              This is a simple functions to implement (nBase ^ nExponent)
*              Some Maxim devices (such as MAX44009) return values in mantissa + (power of 2) exponent format.
*
* \param[in]   nBase             - base
* \param[in]   nExponent         - exponent
*
* \retval      Base^Exponent
*/
{
	int i=0;
	int nValue=0;
	if(nExponent==0)
		nValue=1;
	else
	{
		nValue = nBase;
		for(i=1;i<nExponent;i++)
		{
			nValue = nValue * nBase;
		}
	}
	return(nValue);
}

int receive_byte_with_timeout(u32 unUartAddress, int nTimeoutInTenthsOfSeconds, u8 *uchRxData)
/**
* \brief       Receive a byte from the UART located at *pUartAddress
*
* \param[in]   unUartAddress                - address of the UART peripheral in MicroBlaze memory map @help
* \param[in]   nTimeoutInTenthsOfSeconds    - amount of time to allow before TIMEOUT
* \param[out]  *uchRxData                   - received data is stored at uchRxData
*
* \retval      TRUE if operation succeeded
*/
{
	int j=0;
	int nReturnVal = TRUE;
	u8 uchInput = 0;

	// Check if there is a character in the UART Rx buffer
	// Continue checking every 10th of a second for nTimeoutInSeconds
	while(XUartLite_IsReceiveEmpty(unUartAddress) && (j < nTimeoutInTenthsOfSeconds))
	{
		j++;
		delay(ABOUT_ONE_SECOND/10);
	}

	if(XUartLite_IsReceiveEmpty(unUartAddress))
			nReturnVal = FALSE;
	else
	{
		uchInput = XUartLite_RecvByte(unUartAddress);
		// Check if it is an escape sequence
		if(uchInput==27)  // Escape sequence (likely an arrow key)
		{
			if(XUartLite_IsReceiveEmpty(unUartAddress))
				nReturnVal = FALSE;
			else
			{
				uchInput = XUartLite_RecvByte(unUartAddress);
				if(uchInput==91)  // Left bracket (part #2 of the 3 part escape sequence)
				{
					if(XUartLite_IsReceiveEmpty(unUartAddress))
						nReturnVal = FALSE;
					else
					{
						uchInput = XUartLite_RecvByte(unUartAddress);
						if(uchInput==75)
							uchInput = 244;  // We have defined KEYPRESS_END as 244
					}
				}
			}

		}
		*uchRxData = uchInput;
		nReturnVal = TRUE;
	}
	return(nReturnVal);
}

int GetLine( char* sInputString, unsigned int unMaxSize )
/**
* \brief       Retrieve a line of characters from the default Hyperterminal UART (DEFAULT_HYPERTERMINAL_UART).
* \par         Details
*              Maximum number of characters can be specified.  Function will timeout after 10 seconds.
*
* \param[in]   sInputString       - pointer to buffer for input string
* \param[in]   unMaxSize          - maximum number of characters to input
*
* \retval      TRUE if operation succeeded
*/
{
	u8 uchInputChar = 0;
	unsigned int unInputStringIndex = 0;

	receive_byte_with_timeout(DEFAULT_HYPERTERMINAL_UART_ADDRESS, 10, &uchInputChar);
	while( (uchInputChar != '\r') && (uchInputChar != '\n') && (unInputStringIndex < unMaxSize-1) )
	{
		sInputString[ unInputStringIndex ] = (char)uchInputChar;
		unInputStringIndex++;
		receive_byte_with_timeout(DEFAULT_HYPERTERMINAL_UART_ADDRESS, 10, &uchInputChar);
	}
	sInputString[ unInputStringIndex ] = '\0';

	return (unInputStringIndex < unMaxSize) ? unInputStringIndex : -1;
}

void printf_temp(float fTemp, u8 uchPrintCelsius, u8 uchAddCarriageReturn)
/**
* \brief       Print temperature as xx.x as degrees F or C
* \par         Details
*              This function prints the temperature with .1 degree resolution in either degrees
* \n           Celsius (uchPrintCelsius==TRUE) -or- Fahrenheit (uchPrintCelsius==FALSE)
*
* \param[in]   fTemp                   - temperature to print in celsius
* \param[in]   uchPrintCelsius         - true = print as celsius, false = print as fahrenheit
* \param[in]   uchAddCarriageReturn    - true = add a carriage return
*
* \retval      None
*/
{
	if(uchPrintCelsius==TRUE)
		printf("%.1f deg C",fTemp);
	else
		printf("%.1f deg F",((fTemp*1.8f)+32.0f));
	if(uchAddCarriageReturn==TRUE)
		printf("\r\n");
}

u8 getUartByte(u32 nUartAddress)
/**
* \brief       Get a byte from either the full UART in the Zynq PS, or a Xilinx UartLite
*
* \param[in]  unUartAddress.  32 bit UART address
*
* \retval      Returns the next byte from the Uart Rx FIFO
*/
{
	u8 uchInput;

	uchInput = XUartLite_RecvByte(nUartAddress);
	return(uchInput);
}

int htoi(char *sStr)
{
    int nRet=0;
    u8 uchEnd=0;
    u8 uchCount;
    for(uchCount=0;uchCount<100;uchCount++)
    {
        switch(sStr[uchCount])
        {
            case '0': nRet=nRet<<4; nRet=nRet+0; break;
            case '1': nRet=nRet<<4; nRet=nRet+1; break;
            case '2': nRet=nRet<<4; nRet=nRet+2; break;
            case '3': nRet=nRet<<4; nRet=nRet+3; break;
            case '4': nRet=nRet<<4; nRet=nRet+4; break;
            case '5': nRet=nRet<<4; nRet=nRet+5; break;
            case '6': nRet=nRet<<4; nRet=nRet+6; break;
            case '7': nRet=nRet<<4; nRet=nRet+7; break;
            case '8': nRet=nRet<<4; nRet=nRet+8; break;
            case '9': nRet=nRet<<4; nRet=nRet+9; break;
            case 'a': nRet=nRet<<4; nRet=nRet+10; break;
            case 'b': nRet=nRet<<4; nRet=nRet+11; break;
            case 'c': nRet=nRet<<4; nRet=nRet+12; break;
            case 'd': nRet=nRet<<4; nRet=nRet+13; break;
            case 'e': nRet=nRet<<4; nRet=nRet+14; break;
            case 'f': nRet=nRet<<4; nRet=nRet+15; break;
            case 'A': nRet=nRet<<4; nRet=nRet+10; break;
            case 'B': nRet=nRet<<4; nRet=nRet+11; break;
            case 'C': nRet=nRet<<4; nRet=nRet+12; break;
            case 'D': nRet=nRet<<4; nRet=nRet+13; break;
            case 'E': nRet=nRet<<4; nRet=nRet+14; break;
            case 'F': nRet=nRet<<4; nRet=nRet+15; break;
            default: uchEnd=1; break;
        }
        if(uchEnd)
        {
            break;
        }
    }
    return nRet;
}
