/** \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 "xparameters.h"	/* EDK generated parameters */
#include "stdio.h"
#include "utilities.h"
#include "MAXREFDES14.h"

#define UART_BASEADDR		XPAR_XUARTPS_0_BASEADDR

#define OLED_VBAT 0x20
#define OLED_VDD 0x10;
#define OLED_RESET_B 0x08
#define OLED_DATA_COMMAND_B 0x04
#define OLED_SDIN 0x02
#define OLED_SCLK 0x01

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 and Zedboard have 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);
		}
	}
}

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);
}

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("*");
}

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;

	// Check if the UART base address is the full UART located within the Zynq chip,
	// if not, assume it is an HDL instantiated AXI-UartLite
	if(nUartAddress==XPAR_PS7_UART_1_BASEADDR)
		read(1, (char*)&uchInput, 1);	// Get a byte from stdin
//MTS No XUartLite hardware or driver.
//MTS	else
//MTS		uchInput = XUartLite_RecvByte(nUartAddress);
	return(uchInput);
}

void suchEndUartByte(u32 unUartAddress, u8 uchByte)
/**
* \brief       SuchEnd a byte to the UART.  Either directs to the full UART in the Zynq PS, or a Xilinx UartLite
*
* \param[in]   unUartAddress.  32 bit UART address
* \param[in]   uchByte.  The byte to be sent to the UART
*
* \retval      None
*/
{
	if(unUartAddress==DEFAULT_HYPERTERMINAL_UART_ADDRESS)
	{
		printf("%c",uchByte);
		fflush(stdout);
	}
//MTS No XUartLite hardware or driver.
//MTS	else
//MTS		XUartLite_SuchEndByte(unUartAddress, uchByte);
}

u8 checkUartEmpty(u32 unUartAddress)
/**
* \brief       Check if either Uart is empty.  Either directs to the full UART in the Zynq PS, or a Xilinx UartLite
*
* \param[in]   unUartAddress.  32 bit UART address
*
* \retval      True if empty (false if not)
*/
{
	u8 uchReturnVal=TRUE;
	u32 unUartStatusRegisterAddress;
	u32 unStatusRegisterValue;
	if(unUartAddress==XPAR_PS7_UART_1_BASEADDR)
	{
		unUartStatusRegisterAddress = unUartAddress + 0x0000002C;
		unStatusRegisterValue = Xil_In32(unUartStatusRegisterAddress);

		// Register UART BASE ADDR + 0x2C.  Bit 1 is a (1) when Rx FIFO is empty
		if((unStatusRegisterValue & 0x00000002)==0x00000002)
			uchReturnVal=TRUE;
		else
			uchReturnVal=FALSE;
	}
	else
	{
//MTS No XUartLite hardware or driver.
//MTS		if(XUartLite_IsReceiveEmpty(unUartAddress)==TRUE)
//MTS			uchReturnVal=TRUE;
//MTS		else
			uchReturnVal=FALSE;
	}

	return(uchReturnVal);

}


void initializeOLED(u8 *pFont)
/**
* \brief       Initializes the OLED display
* \par         Details
*              This function initializes the OLED display and the global data structure that holds the OLED display buffer and font.
*
* \param[in]   *pFont          - pointer to an u8 array containing the ASCII display font
* \retval      None
*/
{
	// First, initialize the global structure that represents the OLED device

	//GPIO that manages the bit-banged SPI interface to the OLED
	//XGpio_Initialize(&g_structureOLED.xgpioPort, XPAR_AXI_GPIO_OLED_DEVICE_ID);
	XGpio_Initialize(&g_structureOLED.xgpioPort, XPAR_AXI_GPIO_OLED_DEVICE_ID);
	XGpio_SetDataDirection(&g_structureOLED.xgpioPort, 1, 0x00);	// Set the OLED peripheral to outputs
	XGpio_DiscreteWrite(&g_structureOLED.xgpioPort, 1, 0x00);		// Set all values to zero
	delay(100);

	// Set the font in the OLED structure
	g_structureOLED.font = pFont;

	// Init the global variable that represents the OLED bit-bang pins
	g_structureOLED.portStatus = 0x00;

	// Init and clear the display buffer and the invertered/flipped buffer
	clearOLEDBuffer(g_structureOLED.writeBuffer);
	clearOLEDBuffer(g_structureOLED.flippedBuffer);

	// Now, Initialize the OLED display (hardware)

	// Disable VBAT power supply to the OLED integrated switcher
	// Note:  These bits control the Gate voltage on a P-Channel MOSFET
	g_structureOLED.portStatus |= OLED_VBAT;
	XGpio_DiscreteWrite(&g_structureOLED.xgpioPort, 1, g_structureOLED.portStatus);		// Set all values to zero
	delay(ABOUT_ONE_SECOND/5);

	//Enable VDD power supply to digital logic within OLED
	g_structureOLED.portStatus |= OLED_VDD;
	XGpio_DiscreteWrite(&g_structureOLED.xgpioPort, 1, g_structureOLED.portStatus);		// Set all values to zero
	delay(ABOUT_ONE_SECOND/5);

	// Disable reset
	g_structureOLED.portStatus |= OLED_RESET_B;
	XGpio_DiscreteWrite(&g_structureOLED.xgpioPort, 1, g_structureOLED.portStatus);		// Set all values to zero
	delay(ABOUT_ONE_SECOND/5);

	// Set Display Off
	suchEndOLEDSPI(0xAE);
	delay(100);

	// Set Display Clock Divide Ratio.  Oscillator Frequency
	suchEndOLEDSPI(0xD5);
	delay(100);
	suchEndOLEDSPI(0x80);
	delay(100);

	// Set Multiplex Ratio
	suchEndOLEDSPI(0xA8);
	delay(100);
	suchEndOLEDSPI(0x1F);
	delay(100);

	// Set Display Offset
	suchEndOLEDSPI(0xD3);
	delay(100);
	suchEndOLEDSPI(0x00);
	delay(100);

	// Set Display Start Line
	suchEndOLEDSPI(0x40);
	delay(100);

	// Set Charge Pump
	suchEndOLEDSPI(0x8D);
	delay(100);
	suchEndOLEDSPI(0x14);
	delay(100);

	// Set Segment Re-Map
	suchEndOLEDSPI(0xA1);
	delay(100);

	// Set COM Output Scan Direction
	suchEndOLEDSPI(0xC8);
	delay(100);

	// Set Com Pins Hardware Configuration
	suchEndOLEDSPI(0xDA);
	delay(100);
	suchEndOLEDSPI(0x02);
	delay(100);

	// Set Contrast Control
	suchEndOLEDSPI(0x81);
	delay(100);
	suchEndOLEDSPI(0x8F);
	delay(100);

	// Set Pre-Charge Period
	suchEndOLEDSPI(0xD9);
	delay(100);
	suchEndOLEDSPI(0xF1);
	delay(100);

	// Set VCOMH Deselect Level
	suchEndOLEDSPI(0xDB);
	delay(100);
	suchEndOLEDSPI(0x40);
	delay(100);

	// Set Entire Display On
	suchEndOLEDSPI(0xA4);
	delay(100);

	// Set Normal/Inverse Display
	suchEndOLEDSPI(0xA6);
	delay(100);

	// Enable the VBAT power supply (which is used for the OLED)
	g_structureOLED.portStatus &= ~OLED_VBAT;
	XGpio_DiscreteWrite(&g_structureOLED.xgpioPort, 1, g_structureOLED.portStatus);		// Set all values to zero
	delay(ABOUT_ONE_SECOND/2);	// Long delay for internal OLED switcher to stabilize

	// Set Display On
	suchEndOLEDSPI(0xAF);
	delay(100);
}


void suchEndOLEDSPI(u8 uchDataToWrite)
/**
* \brief       Bit bang routine for Zedboard SPI OLED interface
* \par         Details
*              This function suchEnds an (unsigned) byte (msb first) to the OLED SPI port
*
* \param[in]   uchDataToWrite          - u8 value to be written to OLED SPI
* \retval      None
*/
{
	int i;

	for(i=7;i>=0;i--)
	{
		// Set the OLED_SDIN bit
		if(((uchDataToWrite >> i) & 0x01)==0x01)
			g_structureOLED.portStatus |= OLED_SDIN;
		else
			g_structureOLED.portStatus &= ~OLED_SDIN;
		XGpio_DiscreteWrite(&g_structureOLED.xgpioPort, 1, g_structureOLED.portStatus);
		delay(100);

		// Clock in the data via a rising edge of SCLK
		g_structureOLED.portStatus |= OLED_SCLK;
		XGpio_DiscreteWrite(&g_structureOLED.xgpioPort, 1, g_structureOLED.portStatus);
		delay(100);
		g_structureOLED.portStatus &= ~OLED_SCLK;
		XGpio_DiscreteWrite(&g_structureOLED.xgpioPort, 1, g_structureOLED.portStatus);
		delay(100);
	}
}


void clearOLEDBuffer(u8 *pauchBuffer)
/**
* \brief       Clears the OLED display buffer
* \par         Details
*              This function clears the display buffer by setting all pixels to zero.
*
* \param[in]   *pauchBuffer          - pointer to an u8 array used for the OLED pixel buffer
* \retval      None
*/
{
	int i;

	for(i=0;i<512;i++)
		pauchBuffer[i] = 0x00;

}

void displayOLEDBuffer(u8 *pauchBuffer)
/**
* \brief       Copies the display buffer into the OLED display
* \par         Details
*              This function writes the the display buffer into the OLED display using the page mode setting.
* \n           Note:  The Zedboard OLED display contains a Solomon SSD1306 display controller.
*
* \param[in]   *pauchBuffer          - pointer to an u8 array used for the OLED pixel buffer
* \retval      None
*/
{
	int column=0;
	int page=0;
	u8 *p;
	u8 uchPixelValue=0;

	// Set the display mode to page based transfers
	suchEndOLEDSPI(0x20);
	delay(100);
	suchEndOLEDSPI(0x02);
	delay(100);

	// Set the page pointer lower nibble to 0x0
	suchEndOLEDSPI(0x00);
	delay(100);

	// Set the page pointer upper nibble to 0x0
	suchEndOLEDSPI(0x10);
	delay(100);

	// Write 4 pages worth of data
	// Note that the SSD1306 controller can handle 128x64 displays, but the OLED
	// used on zedboard is only 128x32.  Data is provided to the display as (4) pages of 128 bytes each.
	p = pauchBuffer;
	for(page=0;page<4;page++)
	{
		// Enable Command Mode (shut off data mode)
		g_structureOLED.portStatus &= ~OLED_DATA_COMMAND_B;
		XGpio_DiscreteWrite(&g_structureOLED.xgpioPort, 1, g_structureOLED.portStatus);		// Set all values to zero
		delay(100);	// Long delay for internal OLED switcher to stabilize

		// Set the page command by issuing 0xB0 (page0), 0xB1 (page1) etc.
		suchEndOLEDSPI((0xB0+page));

		// Enable the Data mode (shut off command mode)
		g_structureOLED.portStatus |= OLED_DATA_COMMAND_B;
		XGpio_DiscreteWrite(&g_structureOLED.xgpioPort, 1, g_structureOLED.portStatus);		// Set all values to zero
		delay(100);	// Long delay for internal OLED switcher to stabilize

		for(column=0;column<128;column++)
		{
			uchPixelValue = *p;
			suchEndOLEDSPI(uchPixelValue); // change this to zero
			p++;
		}
	}

	// Enable Command Mode (shut off data mode)
	g_structureOLED.portStatus &= ~OLED_DATA_COMMAND_B;
	XGpio_DiscreteWrite(&g_structureOLED.xgpioPort, 1, g_structureOLED.portStatus);		// Set all values to zero
	delay(100);	// Long delay for internal OLED switcher to stabilize
}

void putCharOLED(int x, int y, char chCharacter)
/**
* \brief       Places a single ASCII character into the OLED display buffer
* \par         Details
*              This function copies an ASCII character from the font table into the OLED display buffer (configured as a 16x4 character display).
*
* \param[in]   x          - The x position of the character location
* \param[in]   y          - The y position of the character location
* \param[in]   chCharacter          - ASCII character to be printed (ex:  0x41 = 'A')
* \retval      None
*/
{
	int i;
	int nDisplayBufferIndex=0;
	int nFontIndex=0;

	// Create the index location for the character into the display memory
	nDisplayBufferIndex = (x * 8) + (y * 16 * 8);

	// Make sure the character has a valid value, else ignore
	if(chCharacter >=0 && chCharacter<128)
	{
		nFontIndex = chCharacter * 8;

		for(i=nDisplayBufferIndex;i<nDisplayBufferIndex+8;i++)
		{
			g_structureOLED.writeBuffer[i] = g_structureOLED.font[nFontIndex];
			nFontIndex++;
		}
	}
}

void printfToBufferOLED(int x, int y,char *chString)
/**
* \brief       Printf-like function to copy an ASCII string into the OLED display buffer
* \par         Details
*              This function copies a pre-formatted ASCII string into the OLED display buffer, but does not take any action to display the buffer
*
* \param[in]   x          - The starting position of string within the 16x4 character display
* \param[in]   y          - The starting position of string within the 16x4 character display
* \param[in]   *chString          - pointer to an null terminated character string.  Should be generated with sprintf (or similar).
* \retval      None
*/
{
	int nStringLength;
	int nInitialDisplayLocation;
	int nRemainingDisplayLength;
	int i;
	int xIndex=0;
	int yIndex=0;
	nStringLength = strlen(chString);

	// Will the string fit on the display?  If not, truncate the length
	nInitialDisplayLocation = y*16 + x;
	nRemainingDisplayLength = 64 - nInitialDisplayLocation;
	if(nStringLength > nRemainingDisplayLength)
		nStringLength = nRemainingDisplayLength;

	xIndex = x;
	yIndex = y;
	for(i=0;i<nStringLength;i++)
	{
		putCharOLED(xIndex,yIndex,chString[i]);
		xIndex++;
		if(xIndex==16)
		{
			xIndex=0;
			yIndex++;
		}
	}
}

void printfToOLED(int x, int y,char *chString)
/**
* \brief       Printf-like function to copy an ASCII string into the OLED display buffer
* \par         Details
*              This function copies a pre-formatted ASCII string into the OLED display buffer,
*              flips/rotates the display pixels, and then suchEnds the buffer to the OLED display
*
* \param[in]   x          - The starting position of string within the 16x4 character display
* \param[in]   y          - The starting position of string within the 16x4 character display
* \param[in]   *chString          - pointer to an null terminated character string.  Should be generated with sprintf (or similar).
* \retval      None
*/
{
	printfToBufferOLED(x,y,chString);
	flipAndCopyDisplayBuffer(g_structureOLED.writeBuffer, g_structureOLED.flippedBuffer);
	displayOLEDBuffer(g_structureOLED.flippedBuffer);
}


void flipAndCopyDisplayBuffer(u8 *pauchSourceBuffer, u8 *pauchDestinationBuffer)
/**
* \brief       Copies the pixels from the source display buffer, into the destination buffer, flipping their location 180 degrees.
* \par         Details
*              The (0,0) pixel location on the OLED display is in the bottom right corner.
*              This function flips the display so that the (0,0) is in the top left corner and (131,31) is in the bottom right.
*
* \param[in]   *pauchSourceBuffer          - pointer to an u8 buffer used as the source display buffer
* \param[in]   *pauchDestinationBuffer     - pointer to an u8 buffer used as the destination display buffer
* \retval      None
*/
{
	int i,x,y;
	u8 uchTempWord1;
	u8 uchTempWord2;
	u8 uchTempWord3;

	for(y=0;y<4;y++)
	{
		for(x=0;x<128;x++)
		{
			uchTempWord1 = pauchSourceBuffer[511-((y*128)+x)];
			uchTempWord3 = 0;
			for(i=0;i<8;i++)
			{
				uchTempWord2 = (uchTempWord1 >> (7-i)) & 0x01;  // shift the bit to the bit0 location and mask off
				uchTempWord2 = uchTempWord2 << i;				// shift the bit back to the desired location.
				uchTempWord3 += uchTempWord2;
			}
			pauchDestinationBuffer[((y*128)+x)] = uchTempWord3;
		}
	}
}

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;
}
