/*
 *              Copyright (C) 2005, BroadOn Communications Corp.
 *
 * These coded instructions, statements, and computer programs contain
 * unpublished  proprietary information of BroadOn Communications Corp.,
 * and  are protected by Federal copyright law. They may not be disclosed
 * to  third  parties or copied or duplicated in any form, in whole or in
 * part, without the prior written consent of BroadOn Communications Corp.
 *
 */

#include "stdafx.h"
#include <windows.h>
#include <conio.h>
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <time.h>
#include <setupapi.h>
#include <basetyps.h>
#include <io.h>
#include <fcntl.h>
#include "usbdi.h"
#include <initguid.h>
#include "dwusb.h"

static HANDLE hUsbWrite, hUsbRead;
static unsigned char usbRdBuf[MAX_PKT_SIZE + 16];
static unsigned char usbWrBuf[MAX_PKT_SIZE + 16];
char usbBuf[1024], dbgBuf[1024];
int shellGet4 = 0;
static int dbgBufLen = 0;


// {9C37855E-3D67-487a-B70E-EB4EA357A969} for BBRDB
DEFINE_GUID(GUID_CLASS_BBRDB, 
0x9c37855e, 0x3d67, 0x487a, 0xb7, 0xe, 0xeb, 0x4e, 0xa3, 0x57, 0xa9, 0x69);

// {B881AF97-51A7-4bc1-9BC5-736E7497B93E}
DEFINE_GUID(GUID_CLASS_IQUE_NC, 
0xb881af97, 0x51a7, 0x4bc1, 0x9b, 0xc5, 0x73, 0x6e, 0x74, 0x97, 0xb9, 0x3e);

HANDLE OpenOneDevice (HDEVINFO HardwareDeviceInfo, 
		    PSP_INTERFACE_DEVICE_DATA  DeviceInfoData, char *devName)
{
	PSP_INTERFACE_DEVICE_DETAIL_DATA     functionClassDeviceData = NULL;
    ULONG                                predictedLength = 0;
    ULONG                                requiredLength = 0;
	HANDLE								 hOut = INVALID_HANDLE_VALUE;

	SetupDiGetInterfaceDeviceDetail (
            HardwareDeviceInfo,
            DeviceInfoData,
            NULL, // probing so no output buffer yet
            0, // probing so output buffer length of zero
            &requiredLength,
            NULL); // not interested in the specific dev-node


    predictedLength = requiredLength;

    functionClassDeviceData = (PSP_INTERFACE_DEVICE_DETAIL_DATA) malloc (predictedLength);
    functionClassDeviceData->cbSize = sizeof (SP_INTERFACE_DEVICE_DETAIL_DATA);

    if (! SetupDiGetInterfaceDeviceDetail (
               HardwareDeviceInfo,
               DeviceInfoData,
               functionClassDeviceData,
               predictedLength,
               &requiredLength,
               NULL)) {
		free( functionClassDeviceData );
        return INVALID_HANDLE_VALUE;
    }

	strcpy( devName,functionClassDeviceData->DevicePath) ;
    hOut = CreateFile (
                  functionClassDeviceData->DevicePath,
                  GENERIC_READ | GENERIC_WRITE,
                  FILE_SHARE_READ | FILE_SHARE_WRITE,
                  NULL, // no SECURITY_ATTRIBUTES structure
                  OPEN_EXISTING, // No special create flags
                  0, // No special attributes
                  NULL); // No template file

    if (INVALID_HANDLE_VALUE == hOut) {
		sprintf(usbBuf, "<Download PC> Error: FAILED to open %s", devName);
		dbgPrintf(usbBuf);
    }
	free( functionClassDeviceData );

	return hOut;
}


HANDLE OpenUsbDevice( LPGUID  pGuid, char *outNameBuf)
{
   ULONG NumberDevices;
   HANDLE hOut = INVALID_HANDLE_VALUE;
   HDEVINFO                 hardwareDeviceInfo;
   SP_INTERFACE_DEVICE_DATA deviceInfoData;
   ULONG                    i;
   BOOLEAN                  done;
   PUSB_DEVICE_DESCRIPTOR   usbDeviceInst;
   PUSB_DEVICE_DESCRIPTOR	*UsbDevices = &usbDeviceInst;

   *UsbDevices = NULL;
   NumberDevices = 0;

   hardwareDeviceInfo = SetupDiGetClassDevs (
                           pGuid,
                           NULL, // Define no enumerator (global)
                           NULL, // Define no
                           (DIGCF_PRESENT | // Only Devices present
                            DIGCF_INTERFACEDEVICE));

   NumberDevices = 4;
   done = FALSE;
   deviceInfoData.cbSize = sizeof (SP_INTERFACE_DEVICE_DATA);

   i=0;
   while (!done) {
      NumberDevices *= 2;

      if (*UsbDevices) {
         *UsbDevices = (PUSB_DEVICE_DESCRIPTOR)
               realloc(*UsbDevices, (NumberDevices * sizeof (USB_DEVICE_DESCRIPTOR)));
      } else {
         *UsbDevices = (PUSB_DEVICE_DESCRIPTOR) calloc (NumberDevices, sizeof (USB_DEVICE_DESCRIPTOR));
      }

      if (NULL == *UsbDevices) {  
		 SetupDiDestroyDeviceInfoList (hardwareDeviceInfo);
         return INVALID_HANDLE_VALUE;
      }

      usbDeviceInst = *UsbDevices + i;
      for (; i < NumberDevices; i++) {
		 if (SetupDiEnumDeviceInterfaces (hardwareDeviceInfo,
                                         0, // We don't care about specific PDOs
										 pGuid,
                                         i,
                                         &deviceInfoData)) {

            hOut = OpenOneDevice (hardwareDeviceInfo, &deviceInfoData, outNameBuf);
			if ( hOut != INVALID_HANDLE_VALUE ) {
               done = TRUE;
               break;
			}
         } else {
            if (ERROR_NO_MORE_ITEMS == GetLastError()) {
               done = TRUE;
               break;
            }
         }	
	  }
   }

   NumberDevices = i;
   SetupDiDestroyDeviceInfoList (hardwareDeviceInfo);
   free ( *UsbDevices );

   return hOut;
}


BOOL GetUsbDeviceFileName( LPGUID  pGuid, char *outNameBuf)
{
	HANDLE hDev = OpenUsbDevice(pGuid, outNameBuf );
	if ( hDev != INVALID_HANDLE_VALUE )
	{
		CloseHandle( hDev );
		return TRUE;
	}
	return FALSE;
}

BOOL isUsbConnected() 
{
	char usbDevName[512];

	if ( !GetUsbDeviceFileName((LPGUID) &GUID_CLASS_IQUE_NC, usbDevName)) {
		if ( !GetUsbDeviceFileName((LPGUID) &GUID_CLASS_BBRDB, usbDevName)) {
			return  false;
		}
	}

	return true;
}

HANDLE  open_usb_pipe(int which)
{
	int success = 1;
	HANDLE h;
	char pipename[8], usbDevName[512];

	if ( !GetUsbDeviceFileName((LPGUID) &GUID_CLASS_IQUE_NC, usbDevName)) {
		if ( !GetUsbDeviceFileName((LPGUID) &GUID_CLASS_BBRDB, usbDevName)) {
			return  INVALID_HANDLE_VALUE;
		}
	}

	strcat(usbDevName, "\\");
	sprintf(pipename, "PIPE%02d", which);
    strcat (usbDevName, pipename);

	h = CreateFile(usbDevName,
		GENERIC_WRITE | GENERIC_READ,
		FILE_SHARE_WRITE | FILE_SHARE_READ,
		NULL,
		OPEN_EXISTING,
		0, 
		NULL);

	if (h == INVALID_HANDLE_VALUE) {
		sprintf(usbBuf, "<Download PC> Eorror: Failed to open (%s) = %d", usbDevName, GetLastError());
		dbgPrintf(usbBuf);
		success = 0;
	} 

	return h;
}

int
shellInit()
{
	hUsbWrite = open_usb_pipe(SC_OUT_PIPE);
    hUsbRead =  open_usb_pipe(SC_IN_PIPE);
	USBStreamHeader *pHd;
	unsigned long wlen, rlen, rlen1;
	int len;

	if (hUsbWrite == INVALID_HANDLE_VALUE || hUsbRead == INVALID_HANDLE_VALUE) {
		dbgPrintf("<Download PC> Fatal Error: cannot open USB device");
		return -1;
	}

    pHd = (USBStreamHeader *) usbWrBuf;
	/* Send packet via ctrl channel to put NC in ready state*/
	pHd->magic = 0xbacf;
	pHd->check = 0;
	pHd->length = 4;
	pHd->protonum = USB_DEV_MUX_CTRL_ID;
	memset(usbWrBuf+8, 0, 12);
	WriteFile(hUsbWrite, usbWrBuf, sizeof(USBStreamHeader)+4, &wlen, NULL);

retry:
	/* Response from ctrl channel */
	ReadFile(hUsbRead, usbRdBuf, 64, &rlen, NULL);
	pHd = (USBStreamHeader *) usbRdBuf;
	if (rlen < sizeof(USBStreamHeader)){
		sprintf(usbBuf, "<Download PC> Error: NC repond ctrl packet size is invalid");
		dbgPrintf(usbBuf);
		return -2;
	}

	len = pHd->length + sizeof(USBStreamHeader) - rlen;
	if (len > 0) {
		ReadFile(hUsbRead, usbRdBuf+rlen, len, &rlen1, NULL);
		rlen += rlen1;
	}  /* Read all data */

	if (pHd->protonum != 0) {
		sprintf(usbBuf, "<Download PC> INFO: recv data from bitstream [%d]", pHd->protonum);
		dbgPrintf(usbBuf);
		goto retry;
	} else if (pHd->protonum == 4) shellGet4 = 1;

	if (pHd->protonum != 0 || pHd->length != 4|| pHd->magic != 0xbacf) {
		dbgPrintf("<Download PC> Error: NC repond ctrl packet is invalid");
		return -3;
	}

	if ( *((int *) (usbRdBuf + sizeof(USBStreamHeader))) != 1) {
		sprintf(usbBuf, "<Download PC> Error: %d %d out of sync", *((int *) (usbRdBuf + sizeof(USBStreamHeader))), sizeof(USBStreamHeader));
		dbgPrintf(usbBuf);
		return -4;
	}

    return 0;
}

int
shellClose()
{
	CloseHandle(hUsbWrite);
	CloseHandle(hUsbRead);

	return 0;
}

int
hostSend(void *p, int n)
{
    USBStreamHeader *pHd;
    unsigned long wLen;

    pHd = (USBStreamHeader *) usbWrBuf;
    
    if (n > MAX_PKT_SIZE) return -1;

    memset(pHd, 0, sizeof(USBStreamHeader));
    pHd->protonum = USB_DEV_MUX_SHELL_ID;
    pHd->magic = 0xbacf;
    pHd->length = n;
    
    memcpy(usbWrBuf+sizeof(USBStreamHeader), p, n);
    WriteFile(hUsbWrite, usbWrBuf, sizeof(USBStreamHeader)+n, &wLen, NULL);
    
    return wLen;
}

int 
hostRecv(void *p, int n)
{
	unsigned long rLen, rLen1;
	int len, i, ch;
	USBStreamHeader *pHd;

    pHd = (USBStreamHeader *) usbRdBuf;

	while (1) {
		ReadFile(hUsbRead, usbRdBuf, USB_MAX_PKT_SIZE, &rLen, NULL);

		if (rLen < sizeof(USBStreamHeader)) {
			dbgPrintf("<DownloadPC> Error: Usb recv data is less than packet header size");
			return SHELL_RCV_SMALL_PCKET;
		}

		if (pHd->magic != USB_MUX_STREAM_MAGIC) {
			printf("<DownloadPC> Error: Usb bus out of sync");
			return SHELL_RCV_OUT_OF_SYNC;
		}

		if (pHd->length <= 0) {
			printf("<DownloadPC> Error: USB invalid recv packet length");
			return SHELL_RCV_INVALID_LEN;
		}

		len = pHd->length + sizeof(USBStreamHeader) - rLen;
		if (len > 0) {
			ReadFile(hUsbRead, usbRdBuf+rLen, len, &rLen1, NULL);
			rLen += rLen1;
		}  /* Read all data */

		if (pHd->protonum == USB_DEV_MUX_SHELL_ID) {
			len = rLen - sizeof(USBStreamHeader);
			if (len > n) {
				dbgPrintf("<DownloadPC> Error: reply buffer is not big enough");
				return SHELL_RCV_BUFFER_ERR;
			}
			break;
		} else if (pHd->protonum == USB_DEV_MUX_PRINTF_ID) {
			for (i=0; i<pHd->length; i++) {
				ch = usbRdBuf[i+sizeof(USBStreamHeader)];
				if (ch == '\r' || ch == '\n') {
					if (dbgBufLen>0) {
						dbgBuf[dbgBufLen] = 0;
						dbgBufLen = 0;
						dbgPrintf(dbgBuf);
					} else continue;
				} else dbgBuf[dbgBufLen++] = ch;
			}
		} else {
			sprintf(usbBuf, "<Download PC> Warning: recv data from bitstream [%d]", pHd->protonum);
			dbgPrintf(usbBuf);
		}
	}

	memcpy(p, usbRdBuf+sizeof(USBStreamHeader), len);
	return len;
}
