//****************************************************************************
//
// The main application entry function.
//
// \param None.
//
// This function forms the main entry point of the example application. It
// initializes the USB bulk device, prompts the user for an ASCII string,
// sends this string to the device, reads the response from the device (which
// will be the same string with the character order reversed if using the
// sample device provided by Luminary Micro) and displays the returned
// string.
//
// \return Set the exit code to 0 of no errors cause the application to end
// or a non-zero value otherwise.
//
//****************************************************************************
int main(int argc, char *argv[])
{
    BOOL bResult;
    BOOL bDriverInstalled;
    BOOL bEcho;
    char szBuffer[MAX_ENTRY_LEN];
    ULONG ulWritten;
    ULONG ulRead;
    ULONG ulLength;
    DWORD dwError;
    LMUSB_HANDLE hUSB;

    //
    // Are we operating in echo mode or not? The "-e" parameter tells the
    // app to echo everything it receives back to the device unchanged.
    //
    bEcho = ((argc > 1) && (argv[1][1] == 'e')) ? TRUE : FALSE;

    //
    // Print a cheerful welcome.
    //
    printf("\nLuminary Micro Bulk USB Device Example\n");
    printf("--------------------------------------\n\n");
    printf("Version %s\n\n", BLDVER);
    if(!bEcho)
    {
        printf("This is a partner application to the usb_dev_bulk example\n");
        printf("shipped with StellarisWare software releases for USB-enabled\n");
        printf("boards. Strings entered here are sent to the board which\n");
        printf("inverts the case of the characters in the string and returns\n");
        printf("them to the host.\n\n");
    }
    else
    {
        printf("If run with the \"-e\" command line switch, this application\n");
        printf("echoes all data received on the bulk IN endpoint to the bulk\n");
        printf("OUT endpoint.  This feature may be helpful during development\n");
        printf("and debug of your own USB devices.  Note that this will not\n");
        printf("do anything exciting if run with the usb_dev_bulk example\n");
        printf("device attached since it expects the host to initiate transfers.\n\n");
    }

    //
    // Find our USB device and prepare it for communication.
    //
    hUSB = InitializeDevice(BULK_VID, BULK_PID,
                            (LPGUID)&(GUID_DEVINTERFACE_LUMINARY_BULK),
                            &bDriverInstalled);

    if(hUSB)
    {
        //
        // Are we operating in echo mode or not? The "-e" parameter tells the
        // app to echo everything it receives back to the device unchanged.
        //
        if(bEcho)
        {
            //
            // Yes - we are in echo mode.
            //
            printf("Running in echo mode. Press Ctrl+C to exit.\n\n"
                "Throughput:      0Kbps Packets:           0");

            while(1)
            {
                //
                // Read a packet of data from the device.
                //
                dwError = ReadUSBPacket(hUSB, szBuffer, ECHO_PACKET_SIZE, &ulRead,
                                        INFINITE, NULL);

                if(dwError != ERROR_SUCCESS)
                {
                    //
                    // We failed to read from the device.
                    //
                    printf("\n\nError %d (%S) reading from bulk IN pipe.\n", dwError,
                           GetSystemErrorString(dwError));
                    break;
                }
                else
                {
                    //
                    // Update our byte and packet counters.
                    //
                    g_ulByteCount += ulRead;
                    g_ulPacketCount++;

                    //
                    // Write the data back out to the device.
                    //
                    bResult = WriteUSBPacket(hUSB, szBuffer, ulRead, &ulWritten);
                    if(!bResult)
                    {
                        //
                        // We failed to write the data for some reason.
                        //
                        dwError = GetLastError();
                        printf("\n\nError %d (%S) writing to bulk OUT pipe.\n", dwError,
                               GetSystemErrorString(dwError));
                        break;
                    }

                    //
                    // Display the throughput.
                    //
                    UpdateThroughput();
                }
            }
        }
        else
        {
            //
            // We are running in normal mode.  Keep sending and receiving
            // strings until the user indicates that it is time to exit.
            //
            while(1)
            {

                //
                // The device was found and successfully configured. Now get a string from
                // the user...
                //
                do
                {
                    printf("\nEnter a string (EXIT to exit): ");
                    fgets(szBuffer, MAX_ENTRY_LEN, stdin);
                    printf("\n");

                    //
                    // How many characters were entered (including the trailing '\n')?
                    //
                    ulLength = (ULONG)strlen(szBuffer);

                    if(ulLength <= 1)
                    {
                        //
                        // The string is either nothing at all or a single '\n' so reprompt the user.
                        //
                        printf("\nPlease enter some text.\n");
                        ulLength = 0;
                    }
                    else
                    {
                        //
                        // Get rid of the trailing '\n' if there is one there.
                        //
                        if(szBuffer[ulLength - 1] == '\n')
                        {
                            szBuffer[ulLength - 1] = '\0';
                            ulLength--;
                        }
                    }
                }
                while(ulLength == 0);

                //
                // Are we being asked to exit the application?
                //
                if(!(strcmp("EXIT", szBuffer)))
                {
                    //
                    // Yes - drop out and exit.
                    //
                    printf("Exiting on user request.\n");
                    break;
                }

                //
                // Write the user's string to the device.
                //
                bResult = WriteUSBPacket(hUSB, szBuffer, ulLength, &ulWritten);
                if(!bResult)
                {
                    //
                    // We failed to write the data for some reason.
                    //
                    dwError = GetLastError();
                    printf("Error %d (%S) writing to bulk OUT pipe.\n", dwError,
                           GetSystemErrorString(dwError));
                }
                else
                {
                    //
                    // We wrote data successfully so now read it back.
                    //
                    printf("Wrote %d bytes to the device. Expected %d\n",
                           ulWritten, ulLength);

                    //
                    // We expect the same number of bytes as we just sent.
                    //
                    dwError = ReadUSBPacket(hUSB, szBuffer, ulWritten, &ulRead,
                                            INFINITE, NULL);

                    if(dwError != ERROR_SUCCESS)
                    {
                        //
                        // We failed to read from the device.
                        //
                        printf("Error %d (%S) reading from bulk IN pipe.\n", dwError,
                               GetSystemErrorString(dwError));
                    }
                    else
                    {
                        //
                        // Add a string terminator to the returned data (this
                        // should already be there but, just in case...)
                        //
                        szBuffer[ulRead] = '\0';

                        printf("Read %d bytes from device. Expected %d\n",
                               ulRead, ulWritten);
                        printf("\nReturned string: \"%s\"\n", szBuffer);
                    }
                }
            }
        }
    }
    else
    {
        //
        // An error was reported while trying to connect to the device.
        //
        dwError = GetLastError();

        printf("\nUnable to initialize the Luminary Bulk USB Device.\n");
        printf("Error code is %d (%S)\n\n", dwError, GetSystemErrorString(dwError));
        printf("Please make sure you have a Luminary Stellaris USB-enabled\n");
        printf("evaluation or development kit running the usb_dev_bulk example\n");
        printf("application connected to this system via the \"USB OTG\" or\n");
        printf("\"USB DEVICE\" connectors. Once the device is connected, run\n");
        printf("this application again.\n\n");

        printf("\nPress \"Enter\" to exit: ");
        fgets(szBuffer, MAX_STRING_LEN, stdin);
        printf("\n");
        return(2);
    }

    TerminateDevice(hUSB);

    return(0);
}
VOID CALLBACK TimerCallBack( 
    HWND hwnd,        // handle to window for timer messages 
    UINT message,     // WM_TIMER message 
    UINT idTimer,     // timer identifier 
    DWORD dwTime)     // current system time 
{
	unsigned int i = 0;
	int bResult, dwError;
	unsigned int ulWritten, ulRead;
	unsigned int x_pos, y_pos;
	int x_velocity, y_velocity;

	
	TxBuffer[0] = 'D';
	TxBuffer[1] = 'R';
	TxBuffer[2] = 'E';
	TxBuffer[3] = 'Q';

	
	bResult = WriteUSBPacket(hUSB, (unsigned char *)TxBuffer, DREQ_NUM, (unsigned long *)&ulWritten);
	if(!bResult)
	{
		//
		// We failed to write the data for some reason.
		//
		dwError = GetLastError();
		printf("Error %d (%S) writing to bulk OUT pipe.\n", dwError,
		GetSystemErrorString(dwError));
	}
	else
	{
                    //
                    // We wrote data successfully so now read it back.
                    //
		printf("Wrote %d bytes to the device: 0x%x, 0x%x, 0x%x, 0x%x.\n", ulWritten, TxBuffer[0], TxBuffer[1], TxBuffer[2], TxBuffer[3]);

                    //
                    // We expect the same number of bytes as we just sent.
                    //
			dwError = ReadUSBPacket(hUSB, (unsigned char *)RxBuffer, FRM_SIZE, (unsigned long *)&ulRead, INFINITE, NULL);

                    if(dwError != ERROR_SUCCESS)
                    {
                        //
                        // We failed to read from the device.
                        //
                        printf("Error %d (%S) reading from bulk IN pipe.\n", dwError,
                               GetSystemErrorString(dwError));
                    }
                    else
                    {
					
							x_pos = RxBuffer[0]|(RxBuffer[1]<<8)|(RxBuffer[2]<<16)|(RxBuffer[3]<<24);
							y_pos = RxBuffer[4]|(RxBuffer[5]<<8)|(RxBuffer[6]<<16)|(RxBuffer[7]<<24);
							x_velocity = RxBuffer[8]|(RxBuffer[9]<<8)|(RxBuffer[10]<<16)|(RxBuffer[11]<<24);
							y_velocity = RxBuffer[12]|(RxBuffer[13]<<8)|(RxBuffer[14]<<16)|(RxBuffer[15]<<24);
						
						printf("x_pos=%d, y_pos=%d, x_velocity=%d, y_velocity=%d.\n",x_pos, y_pos, x_velocity, y_velocity);
                    }
	}
}