Ejemplo n.º 1
0
int usb_close(usb_dev_handle *dev)
{
   WinUsb_Free(dev->fd);
   CloseHandle(dev->hnd);
   free(dev);
   return 0;
}
VOID CloseDevice(IN OUT PDEVICE_DATA DeviceData) {
    if (FALSE == DeviceData->HandlesOpen)
        return;

    WinUsb_Free(DeviceData->WinusbHandle);
    CloseHandle(DeviceData->DeviceHandle);
    DeviceData->HandlesOpen = FALSE;
}
bool AdbWinUsbInterfaceObject::CloseHandle() {
  if (NULL != winusb_handle_) {
    WinUsb_Free(winusb_handle_);
    winusb_handle_ = NULL;
  }
  if (INVALID_HANDLE_VALUE != usb_device_handle_) {
    ::CloseHandle(usb_device_handle_);
    usb_device_handle_ = INVALID_HANDLE_VALUE;
  }

  return AdbInterfaceObject::CloseHandle();
}
/* This will attempt to free up all resources associated with an open
 * USB descriptor.  This also deallocates the provided pointer.
 */
void __close_and_dealloc_usb_interface(__usb_interface_t *usb) {
    if(NULL == usb) {
        return;
    }

    if(NULL != usb->winUSBHandle) {
        WinUsb_Free(usb->winUSBHandle);
    }
    if(NULL != usb->dev) {
        CloseHandle(usb->dev);
    }

    HeapFree(GetProcessHeap(), 0, usb);
}
Ejemplo n.º 5
0
void QUsbDevice::close()
{
    if (!mConnected)
        return;

    QBaseUsbDevice::close();

    if (mDevHandle != INVALID_HANDLE_VALUE)
        CloseHandle(mDevHandle);
    if (mUsbHandle != INVALID_HANDLE_VALUE)
        WinUsb_Free(mUsbHandle);

    mDevHandle = INVALID_HANDLE_VALUE;
    mUsbHandle = INVALID_HANDLE_VALUE;

    mConnected = false;
}
Ejemplo n.º 6
0
VOID
CloseDevice(
    _Inout_ PDEVICE_DATA DeviceData
    )
/*++

Routine description:

    Perform required cleanup when the device is no longer needed.

    If OpenDevice failed, do nothing.

Arguments:

    DeviceData - Struct filled in by OpenDevice

Return value:

    None

--*/
{
    if (FALSE == DeviceData->HandlesOpen) {

        //
        // Called on an uninitialized DeviceData
        //
        return;
    }

    WinUsb_Free(DeviceData->WinusbHandle);
    CloseHandle(DeviceData->DeviceHandle);
    DeviceData->HandlesOpen = FALSE;

    return;
}
Ejemplo n.º 7
0
BOOL WiiMouse_DrvUtil_GetInterfaceHandles(WiiMouse_HandleInfo_t *handleInfo)
{
    BOOL retval = FALSE;
    UCHAR interfaceIndex = 0;
    UCHAR pipeIndex = 0;
    USB_INTERFACE_DESCRIPTOR usbInterfaceDesc;
    WINUSB_PIPE_INFORMATION pipeInfo;

    while( WinUsb_QueryInterfaceSettings(handleInfo->winUsbHandle, interfaceIndex, &usbInterfaceDesc) )
    {
        if( _IsValidInterface(&usbInterfaceDesc) )
        {
            break;
        }

        interfaceIndex++;
    }

    if( GetLastError() == ERROR_INVALID_HANDLE )
    {
        WiiMouse_AddMsg(DERR,"Error, WinUsb_QueryInterfaceSettings invalid handle\n");
        return FALSE;
    }

    if( !WinUsb_GetAssociatedInterface(handleInfo->winUsbHandle, interfaceIndex, &handleInfo->interfaceHandle) )
    {
        DWORD err = GetLastError();

        if( err != ERROR_ALREADY_EXISTS )
        {
            WiiMouse_AddMsg(DERR,"Error, WinUsb_GetAssociatedInterface failed: %d\n", err);
            return FALSE;
        }
        else
        {
            handleInfo->interfaceHandle = handleInfo->winUsbHandle;
            handleInfo->interfaceId = 0;
        }
    }
    handleInfo->interfaceId = interfaceIndex;

    for( pipeIndex = 0; pipeIndex < usbInterfaceDesc.bNumEndpoints; pipeIndex++ )
    {
        if( !WinUsb_QueryPipe(handleInfo->winUsbHandle, interfaceIndex, pipeIndex, &pipeInfo) )
        {
            WiiMouse_AddMsg(DERR,"Error, WinUsb_QueryPipe failed: %d\n", GetLastError());
            retval = FALSE;
            break;
        }
        else
        {
            _SetEndpoint(handleInfo, &pipeInfo);
        }
    }

   /* if( !_ValidateEndpoints(handleInfo) )
    {
         WiiMouse_AddMsg(DERR,"Error, endpoint validation failed\n");
         retval = FALSE;
    }*/
    
    if( !retval )
    {
        WinUsb_Free(handleInfo->interfaceHandle);
    }


    return retval;
}
Ejemplo n.º 8
0
/*! \brief Close the USB communication port.
	\returns XRV_OK if the port was closed successfully
	\note Linux:\n
	If a kernel driver was detached when communication with the device started,
	attach it again. No guarantee is given that udev will pick up on it though.
*/
XsResultValue UsbInterface::closeUsb(void)
{
	//lint --e{534}
#ifdef LOG_RX_TX
	if (d->rx_log != NULL)
		fclose(d->rx_log);
	if (d->tx_log != NULL)
		fclose(d->tx_log);
	d->rx_log = NULL;
	d->tx_log = NULL;
#endif
	if (!isOpen())
		return d->m_lastResult = XRV_NOPORTOPEN;

	d->m_lastResult = XRV_OK;
#ifdef USE_WINUSB
	if (d->m_threadHandle != INVALID_HANDLE_VALUE)
	{
		while (d->m_running)
		{
			::SetEvent(d->m_quitEvent);
			XsTime::msleep(10);
		}
		::CloseHandle(d->m_threadHandle);
	}

	flushData();
	if(d->m_usbHandle[0]) {
		WinUsb_Free(d->m_usbHandle[0]);
		d->m_usbHandle[0] = NULL;
	}
	if(d->m_usbHandle[1]) {
		WinUsb_Free(d->m_usbHandle[1]);
		d->m_usbHandle[1] = NULL;
	}
	if (d->m_deviceHandle) {
		CloseHandle(d->m_deviceHandle);
		d->m_deviceHandle = NULL;
	}
#else
	flushData();
	libusb_device *dev = libusb_get_device(d->m_deviceHandle);
	for (int i = 0; i < d->m_interfaceCount; i++) {
		int result = LIBUSB_ERROR_OTHER;
		while (result != LIBUSB_SUCCESS) {
			result = libusb_release_interface(d->m_deviceHandle, i);
			if (result == LIBUSB_SUCCESS) {
				libusb_attach_kernel_driver(d->m_deviceHandle, i);
			}
		}
	}

	libusb_close(d->m_deviceHandle);
	d->m_deviceHandle = NULL;

	libusb_unref_device(dev);
	d->m_interface = -1;
	d->m_dataInEndPoint = -1;
	d->m_dataOutEndPoint = -1;
#endif
	d->m_endTime = 0;

	return d->m_lastResult;
}
/* This is a convenience method that attempts to traverse the set of
 * discoverable USB devices having the given VID and PID and updates the
 * static data structures that track them.  For any device that is found,
 * the device path, VID and PID will be cached in __enumerated_devices but
 * the devices will not be left open (though it may be necessary to open
 * them briefly to get the VID and PID, which is a WinUSB requirement).
 */
int __probeUSBDevices(int vendorID, int productID) {
    HANDLE dev = NULL;
    char devicePath[DEVICE_PATH_SIZE];
    BOOL rc;
    int flag;
    WINUSB_INTERFACE_HANDLE usbHandle;
    struct USBDeviceDescriptor desc;
    int i;
    int matched;
    int valid;
    BOOL noMoreDevices = FALSE;
    __device_instance_t *instance = NULL;

    /* This __getDevicePath uses a single interface GUID to match the given VID and
     * PID.  If multiple GUIDs were needed (e.g. to match .inf files from other
     * vendors) then this function could be put into a loop to iterate over all
     * known GUIDs.  This would need to be careful with the index, since the
     * index will start at zero again for each device interface class.
     *
     * Note that the .inf file specifies both a class GUID and an interface GUID.
     * These should be different from each other, but the value for each of
     * these across all .inf files should match.
     *
     * It is a little unfortunate that other device classes would need to be
     * hard-coded in here to be searched.  Users will have to have the latest
     * build of this DLL to avoid having sets of supported devices disappear.
     */
    for(i = 0; i < MAX_USB_DEVICES && FALSE == noMoreDevices; i++) {
        rc = __getDevicePath((LPGUID)&GUID_DEVINTERFACE_OCEANOPTICS_USB,
                devicePath, sizeof(devicePath), i, &noMoreDevices);

        if(FALSE == rc) {
            break;      /* May not be any more devices */
        }

        /* Avoid opening any devices at paths that are already known */
        instance = __lookup_device_instance_by_location(devicePath);
        if(NULL != instance) {
            instance->mark = 1; /* Make sure this is not purged this time */
            continue;           /* Leave this one alone otherwise */
        }

        /* Create a file for this device path.  This is a necessary evil
         * to read out the device descriptor (note that Linux and MacOSX don't
         * require this).  If it is found that this is causing interference
         * with open devices, then perhaps the call can be changed to request
         * read-only access.
         */
        dev = CreateFile((LPCWSTR)devicePath, (GENERIC_WRITE | GENERIC_READ),
            (FILE_SHARE_WRITE | FILE_SHARE_READ), NULL, OPEN_EXISTING,
            (FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED), NULL);

        if(INVALID_HANDLE_VALUE == dev) {
            continue;   /* Skip to the next one and try again */
        }

        rc = WinUsb_Initialize(dev, &usbHandle);
        if(FALSE == rc) {
            CloseHandle(dev);
            dev = NULL;
            continue;   /* Skip to the next one and try again */
        }

        /* Now that usbHandle has been initialized, determine whether the
         * device matches the requested VID and PID.
         */
        flag = __getDeviceDescriptor(usbHandle, &desc);

        /* This function is only here to do discovery so once the device
         * descriptor has been read everything can be freed up again.
         */
        WinUsb_Free(usbHandle);
        CloseHandle(dev);
        usbHandle = NULL;
        dev = NULL;

        if(0 != flag) {
            /* The attempt to get the descriptor above failed */
            continue;   /* Skip to the next one and try again */
        }


        if((desc.idVendor != vendorID) || (desc.idProduct != productID)) {
            continue;   /* No match, so skip to the next one and try again */
        }

        /* At this point, we must be dealing with a newly discovered USB
         * device that matches the given VID and PID.  It must now be
         * cached for use with the open function.  Note that instance was
         * checked above so it must be NULL here.
         */
        instance = __add_device_instance(devicePath, vendorID, productID);
        if(NULL == instance) {
            /* Could not add the device -- this should not be possible,
             * but fail gracefully regardless.
             */
            return -1;
        }
        instance->mark = 1;     /* Preserve this since it was just seen */
    }

    /* Purge any devices that are cached but that no longer exist. */
    __purge_unmarked_device_instances(vendorID, productID);

    /* Count up how many of this type of device are known */
    for(    i = 0, matched = 0, valid = 0;
            i < MAX_USB_DEVICES && valid < __enumerated_device_count;
            i++) {
        if(0 != __enumerated_devices[i].valid) {
            valid++;
            if(__enumerated_devices[i].vendorID == vendorID
                        && __enumerated_devices[i].productID == productID) {
                matched++;
            }
        }
    }

    /* At this point, the device cache should have the latest information
     * on this VID/PID combination.  Return the number of devices of this
     * type that were found.
     */
    return matched;
}
void *
USBOpen(unsigned long deviceID, int *errorCode) {
    HANDLE dev = NULL;
    WINUSB_INTERFACE_HANDLE usbHandle = NULL;
    BOOL rc = FALSE;
    __usb_interface_t *retval;
    __device_instance_t *instance;
    struct USBDeviceDescriptor desc;
    int flag;

    /* Set a default error code in case a premature return is required */
    SET_ERROR_CODE(NO_DEVICE_FOUND);

    /* Try to look up the deviceID provided by the caller.  If this does
     * not exist, then there is nothing else to do.
     */
    instance = __lookup_device_instance_by_ID(deviceID);
    if(NULL == instance) {
        /* The device ID was not found.  The caller must only provide IDs that
         * have previously been provided by the USBProbeDevices() function
         * (which is wrapped by getDeviceIDs()).
         */
        return 0;
    }

    if(NULL != instance->handle) {
        /* If there is already a device handle then the device has been opened.
         * It is illegal to try to open a device twice without first closing it.
         */
        return 0;
    }

    rc = __getUSBHandle(instance->devicePath, &dev, &usbHandle);

    if(FALSE == rc) {
        /* This is an internal error */
        return 0;
    }

    if(NULL == dev || NULL == usbHandle) {
        /* This is an internal error */
        return 0;
    }

    /* Just to be entirely pedantic, verify that the VID and PID are exactly
     * what they were supposed to be.
     */
    flag = __getDeviceDescriptor(usbHandle, &desc);
    if(0 != flag) {
        WinUsb_Free(usbHandle);
        CloseHandle(dev);
        return 0;
    }

    if((desc.idVendor != instance->vendorID) || (desc.idProduct != instance->productID)) {
        WinUsb_Free(usbHandle);
        CloseHandle(dev);
        return 0;
    }

    /* The device has survived scrutiny, so get ready to return it. */

    retval = (__usb_interface_t *)HeapAlloc(GetProcessHeap(),
                        HEAP_ZERO_MEMORY, sizeof(__usb_interface_t));

    if(NULL == retval) {
        WinUsb_Free(usbHandle);
        CloseHandle(dev);
        /* Internal error -- could not allocate memory */
        return 0;
    }

    retval->dev = dev;
    retval->winUSBHandle = usbHandle;
    retval->deviceID = instance->deviceID;
    instance->handle = retval;

    SET_ERROR_CODE(OPEN_OK);

    return (void *)retval;
}
Ejemplo n.º 11
0
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
//// MAIN
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
int _tmain(int argc, _TCHAR* argv[])
{
  GUID guidDeviceInterface = CWinUSBComm::m_WinUSBCommInterfaceGUID; //in the INF file

  BOOL bResult = TRUE;

  PIPE_ID PipeID;

  HANDLE hDeviceHandle = INVALID_HANDLE_VALUE;
  WINUSB_INTERFACE_HANDLE hWinUSBHandle = INVALID_HANDLE_VALUE;

  UCHAR DeviceSpeed;
  ULONG cbSize = 0;

  BYTE * pbyDataToDevice = NULL;
  BYTE * pbyDataFromDevice = NULL;

  SetConsoleTitle(_T("WinUSBComm Test"));

  bResult = GetDeviceHandle(guidDeviceInterface, &hDeviceHandle);
  if(!bResult)
  {
    goto done;
  }

  bResult = GetWinUSBHandle(hDeviceHandle, &hWinUSBHandle);
  if(!bResult)
  {
    goto done;
  }

  bResult = GetUSBDeviceSpeed(hWinUSBHandle, &DeviceSpeed);
  if(!bResult)
  {
    goto done;
  }

  bResult = QueryDeviceEndpoints(hWinUSBHandle, &PipeID);
  if(!bResult)
  {
    goto done;
  }

  BOOL bRepeat = FALSE;

  BYTE byVersion = winusbcommversion1;

  bResult = GetDataFromDefaultEndpoint(hWinUSBHandle, winusbcomm2commandGetVersion, (BYTE *)&byVersion, sizeof(byVersion));
  
  EWinUSBCommVersion eVersion = ( byVersion <= winusbcommversion1 ) ? winusbcommversion1 : (EWinUSBCommVersion)byVersion;

  BYTE byGetCommBufferSizeCmd = ( winusbcommversion1 == eVersion ) ? winusbctrlGETBUFFSIZE : winusbcomm2commandGetBufferSize;
  BYTE byResetCmd = ( winusbcommversion1 == eVersion ) ? winusbctrlRESET : winusbcomm2commandReset;
  BYTE byGetReturnSizeCmd = ( winusbcommversion1 == eVersion ) ? winusbctrlGETDATASIZE : winusbcomm2commandGetReturnSize;

  DWORD dwMaxBufferSize = 0;
  bResult = GetDataFromDefaultEndpoint(hWinUSBHandle, byGetCommBufferSizeCmd, (BYTE *)&dwMaxBufferSize, sizeof(dwMaxBufferSize));
  if(!bResult)
  {
    goto done;
  }           

  pbyDataToDevice = new BYTE[dwMaxBufferSize];
  for ( DWORD I = 0; I < dwMaxBufferSize; I++ )
  {
    pbyDataToDevice[I] = (BYTE) I;
  }
  pbyDataFromDevice = new BYTE[dwMaxBufferSize];

  LARGE_INTEGER countStart;
  DWORD dwNumDataTransered = 0;
  DWORD dwNumLoops = 100;
  QueryPerformanceCounter(&countStart);

  if ( winusbcommversion1 == eVersion )
  {
    // send some data over control EP
    BYTE abyCtrlEPTestData[4] = { 4, 3, '2', '1' };
    bResult = SendDatatoDefaultEndpoint(hWinUSBHandle, winusbctrlEXAMPLEDATA4B, abyCtrlEPTestData, 4);
    if(!bResult)
    {
      goto done;
    }
  }
  do
  {
    // put device to receiving state
    bResult = SendDatatoDefaultEndpoint(hWinUSBHandle, byResetCmd);
    if(!bResult)
    {
      goto done;
    }

    if ( winusbcommversion1 != eVersion )
    {
      // notify device how much data will be sent next
      bResult = SendDatatoDefaultEndpoint(hWinUSBHandle, winusbcomm2commandFollowingPacketSize, (BYTE *)&dwMaxBufferSize, 4);
      if(!bResult)
      {
        goto done;
      }
    }

    // send the data
    bResult = WriteToBulkEndpoint(hWinUSBHandle, &PipeID.PipeOutId, &cbSize, pbyDataToDevice, dwMaxBufferSize);
    if(!bResult)
    {
      goto done;
    }

    dwNumDataTransered += dwMaxBufferSize;

    if ( winusbcommversion1 == eVersion )
    {
      // notify device that all is sent
      bResult = SendDatatoDefaultEndpoint(hWinUSBHandle, winusbctrlTXDONE);
      if(!bResult)
      {
        goto done;
      }

      // poll status and wait until idle
      BYTE byCommStatus = winusbcommPROCESSING;
      while ( winusbcommPROCESSING == byCommStatus )
      {
        bResult = GetDataFromDefaultEndpoint(hWinUSBHandle, winusbctrlGETSTATUS, &byCommStatus, sizeof(byCommStatus));
        if(!bResult)
        {
          goto done;
        }
        dwNumDataTransered += 1;
        // timeout here if needed
      }

      // check if idle
      if ( winusbcommIDLE != byCommStatus )
      {
        goto done;
      }
    }

    // get how much data is to read from device
    DWORD dwResponseByteCount = 0;
    do
    {
      bResult = GetDataFromDefaultEndpoint(hWinUSBHandle, byGetReturnSizeCmd, (BYTE *)&dwResponseByteCount, sizeof(dwResponseByteCount));
      if(!bResult)
      {
        goto done;
      }
      // timeout here if needed
    } while ( !dwResponseByteCount );
    dwNumDataTransered += sizeof(dwResponseByteCount);
    
    // response byte count must match sent count; application XORs the data and sends it back
    if ( dwMaxBufferSize != dwResponseByteCount )
    {
      goto done;
    }

    // read data back
    bResult = ReadFromBulkEndpoint(hWinUSBHandle, &PipeID.PipeInId, cbSize, pbyDataFromDevice, dwResponseByteCount);
    if(!bResult)
    {
      goto done;
    }

    dwNumDataTransered += dwResponseByteCount;

// At first I had data XORed in the device and sent back. I was later interested in transfer speed.
//     BOOL bMatch = TRUE;
//     for ( DWORD I = 0; I < dwResponseByteCount; I++ )
//     {
//       if ( pbyDataToDevice[I] != (pbyDataFromDevice[I]))// ^ 0xFF) )
//       {
//         bMatch = FALSE;
//         break;
//       }
//     }
// 
//     printf("Data %s\n", bMatch ? "matched" : "didn't match");
  } while ( --dwNumLoops );

  LARGE_INTEGER countEnd;
  QueryPerformanceCounter(&countEnd);

  LARGE_INTEGER f;
  QueryPerformanceFrequency( &f );

  LARGE_INTEGER elapsedCount;
  elapsedCount.QuadPart = countEnd.QuadPart - countStart.QuadPart;

  DOUBLE elapsed = (DOUBLE)elapsedCount.QuadPart / (DOUBLE)f.QuadPart;
  DOUBLE rate = (DOUBLE)dwNumDataTransered / elapsed;

  rate /= 1024;
  printf("Data speed: %f kbps = %f kBps\n", rate * 8, rate);
  system("PAUSE");
done:
  if ( INVALID_HANDLE_VALUE != hDeviceHandle )
  {
    CloseHandle(hDeviceHandle);
  }
  if ( INVALID_HANDLE_VALUE != hWinUSBHandle )
  {
    WinUsb_Free(hWinUSBHandle);
  }
  if ( pbyDataToDevice ) delete[] pbyDataToDevice;
  if ( pbyDataFromDevice ) delete[] pbyDataFromDevice;
}
Ejemplo n.º 12
0
void NiashLibUsbExit (const int iHandle)
{
	assert(iHandle==1);
	WinUsb_Free(s_hWinUSB);
	CloseHandle(s_hDevice);
}
Ejemplo n.º 13
0
void main()
{ 

	UCHAR buf[2];

	THREAD_PARAM thread_param;

	DWORD dwThreadId;

    GUID guidDeviceInterface = USB_RS232_DEVICE_INTERFACE; //in the INF file

    BOOL bResult = TRUE;

    PIPE_ID PipeID;

    HANDLE hDeviceHandle = INVALID_HANDLE_VALUE;
    WINUSB_INTERFACE_HANDLE hWinUSBHandle = INVALID_HANDLE_VALUE;
    
    UCHAR DeviceSpeed;
    ULONG cbSize = 0;


    bResult = GetDeviceHandle(guidDeviceInterface, &hDeviceHandle);
    if(!bResult) {
        goto done;
    }

    bResult = GetWinUSBHandle(hDeviceHandle, &hWinUSBHandle);
    if(!bResult) {
        goto done;
    }

    bResult = GetUSBDeviceSpeed(hWinUSBHandle, &DeviceSpeed);
    if(!bResult) {
        goto done;
    }

    bResult = QueryDeviceEndpoints(hWinUSBHandle, &PipeID);
    if(!bResult) {
        goto done;
    }

//    bResult = SendDatatoDefaultEndpoint(hWinUSBHandle);
//    if(!bResult) {
//        goto done;
//    }



	thread_param.hWinUSBHandle = hWinUSBHandle;
	thread_param.PipeInId = PipeID.PipeInId;


	if (!CreateThread (NULL, 
		0, 
		(LPTHREAD_START_ROUTINE)&comReadThread,
		(LPVOID)&thread_param,
		0,
		&dwThreadId)) {
	
		printf ("Fail to Create Read Thread\n");
		goto done;
	}


	printf ("\n===============================================================\n");


	buf[1] = '\n';

	while(1) {
		buf[0] = _getch();
		
		if (buf[0] == 27) { // Escape key
			goto done;
		}


		if (buf[0] == '\r') {
			WriteToBulkEndpoint(hWinUSBHandle, &PipeID.PipeOutId, &cbSize, buf, 2);
		} else {
			WriteToBulkEndpoint(hWinUSBHandle, &PipeID.PipeOutId, &cbSize, buf, 1);
		}
		
		
	} // End of while loop
    

done:
    CloseHandle(hDeviceHandle);
    WinUsb_Free(hWinUSBHandle);

    
} // End of main()