Giter VIP home page Giter VIP logo

winusbnet's Introduction

WinUSBNet

WinUSBNet is a .NET class library that provides easy access to the WinUSB API from C#, VB.NET and other .NET languages. WinUSB is a user mode API available for Windows XP, Vista and 7 (XP will require an update), allowing low level access to USB devices such as control transfers and reading from and writing to endpoints.

Please note that there is at least one different project with the same name (at codeplex), this libary is not related.

Download

Download latest release

Status

The library is stable. If you find any bugs or problems please report them using the issue tracker or add a pull request if you have fixed something yourself.

Features

  • MIT licensed with C# source code available (free for both personal and commercial use)
  • CLS compliant library (usable from all .NET languages such as C#, VB.NET and C++.NET)
  • Synchronous and asynchronous data transfers
  • Support for 32-bit and 64-bit Windows versions
  • Notification events for device attachment and removal
  • Support for multiple interfaces and endpoints
  • Intellisense documentation

Related documentation

winusbnet's People

Contributors

adadurov avatar kerol2r20 avatar madwizard-thomas avatar tewarid avatar tibel avatar vbaderks avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

winusbnet's Issues

Connection Problems on 32bit Systems

Hi,

I'm using WinUSBNet version 2.0.1. On an old Win7 32-bit machine, I encountered a problem where I lose my connection after some time. I logged USB communication, but my device was still connected and shown in Device Manager.

I downgraded to version 2.0.0 and encountered the same problem. Then, I downgraded further to version 1.0.3, and everything was working perfectly.

I compared version 1.0.3 to version 2.0.0, but there were no significant changes that could explain this behavior.

After trying different machines, I discovered that this issue seems to be related to 32-bit machines.

I'm not encountering any exceptions or errors that could provide further details.

Do you have any idea what causes the problem?

ControlIn commands must return length of data received

ControlIn USB commands must return the number of bytes that were actually
received.

In typical USB applications its common to have bulk transfers where you don't
know the length of the data that you're going to receive - so you set up a
buffer with the maximum possible bytes and execute a ControlIn(..., buffer)
command. After the command you check to see how many bytes were actually
received.

Original issue reported on code.google.com by [email protected] on 24 Feb 2015 at 12:19

SetupDiEnumDeviceInterfaces always return false.

What steps will reproduce the problem?
1.call the method USBDeviceInfo[] u = 
USBDevice.GetDevices("4d36e965-e325-11ce-bfc1-08002be10318");
2.
3.

What is the expected output? What do you see instead?
a array contains at least one element
no element

What version of the product are you using? On what operating system?
last version
win7

Please provide any additional information below.
no

Original issue reported on code.google.com by [email protected] on 15 Aug 2011 at 4:26

No USb Devices populated when using GetDevice #

Hello, May I know if I still need WInUSB drivers so that my USB devices can be visible when using GetDevice()? How do I install them? How do I get this Library to work? I'm drawing a blank.

How to install WinUSB driver through customized inf file on Windows 10?

I need to communicate with a simple custom device directly through USB. I have full specifications for communication protocol. Unfortunately, the device vendor did not provide WinUSB driver for the device.

According to https://msdn.microsoft.com/en-us/library/ff540283.aspx#inf I should be able to install WinUSB driver automatically on Windows 10 using the inf template.

But installation fails with:

The third-party INF does not contain digital signature information.
As I understand, it is looking for a signed .cat file. But in this case I have no any files to sign nor .cat file. I just want to install Windows own WinUSB driver for the device, and clearly Windows drivers should be signed by Microsoft.

How do I proceed to install the .inf file?

USBPipe.BeginRead Asynchronous Callback not called if data packet size = 64Bytes

I have a Full-Speed WinUSB Device with MaxPacketSize set to 64Bytes. I have set up an interrupt pipe via Endpoint 1. I noted when the device returns 64 bytes on Endpoint 1 the callback is never called, if it is any other size it will return. For now I'm working around it by having the device send an extra "dummy" byte if the length is 64. I've confirmed this issue with a USB trace to verify data was sent.

static USBPipe Pipe;
Pipe = SelectedUnit.Interfaces.FirstOrDefault().InPipe;
Pipe.BeginRead(dataInBuffer, 0, 64, new AsyncCallback(_usb_ipt_data_rc), null);

Alternate Setting is always zero

GetInterfaceInfo method uses WinUsb_QueryInterfaceSettings function with zeroed 
AlternateInterfaceNumber. By the USB standard each interface can have alternate 
one, so zeroing this setting is wrong. For example, my device using Atmel SAM3x 
microcontroller and USB Device Vendor Class implementation by Atmel Software 
Foundation. In their implementation they using interface 0 alternate setting 0 
for ep0 control transfer only, and user's BULK, ISOCHRONOUS and INTERRUPT 
endpoints - in interface 0 alternate setting 1.

I am very new in C#, so I don't understand for now how to add support for 
alternate setting without major modification of library interface. It is easy 
just to put 1 instead of 0, but it is not flexible enough.

Original issue reported on code.google.com by [email protected] on 11 Aug 2014 at 6:20

Exception Listing USB Hub Devices

In another issue in the list I saw that using "{A5DCBF10-6530-11D2-901F-00C04FB951ED}" as the GUID lists all devices, however it only listed composite devices when I googled, whereas I need a hub.

I tried the equivelent hub GUID "{F18A0E88-C30C-11D0-8815-00A0C906BED8}" and it threw the exception below:

image

For reference I do have 2 hubs plugged in, and both hubs have a device plugged into them.

Marshalling issues: GetDescriptor() Language ID is ushort, not byte

I was inspecting your code while comparing some marshalling clauses I had 
written for my own (older) WinUSB stuff I had written for some internal thing.  
I noticed for GetDescriptor() the marshal clause was representing the language 
ID as a byte, but it's actually an unsigned short (UInt16):

http://msdn.microsoft.com/en-us/library/windows/hardware/ff540257(v=vs.85).aspx

I'm not a customer of the project so it doesn't affect me but I thought you'd 
like to know.

Original issue reported on code.google.com by [email protected] on 28 Apr 2012 at 1:42

Problems with USB3.0 Ports

Communication is working fine under windows 10 with older PC with USB 2.0 Ports only with 2 different pcs.
With newer PCs (USB 3.0 Ports) communication gets stuck after about 10 readpipe commands, readpipe times out although mikrocontroller still has data in TX FIFOs. Next readpipe goes fine if done by hand after a few seconds, but endlessly fails if done in a while loop. Same for RAW mode. Do you have any idea what i could do to get communication working?

source bug fix

DeviceNotifyHook.cs--->>

        internal void OnHandleDestroyed(object sender, EventArgs e)
        {
            try
            {
                // Window was destroyed, release hook.
                ReleaseHandle();
-               if (_notifyHandle != null)
+               if (_notifyHandle != IntPtr.Zero)







        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                // clean managed resources

                // do not clean the notifier here. the notifier owns and will dispose this object.
            }
            if (_notifyHandle != IntPtr.Zero)
            {
                API.DeviceManagement.StopDeviceDeviceNotifications(_notifyHandle);
+               _notifyHandle = IntPtr.Zero;

Original issue reported on code.google.com by [email protected] on 13 Jun 2014 at 7:40

DeviceNotifyHook should not need Windows Forms control

I tried to use the attachment and detachment events in a console application, but I was unable to do so. I'm not sure if I missed something, but I found only the USBNotifier class, which needs a Windows Forms control as a parameter in its constructor. Is there any other way to accomplish device attachment/removal detection?

Get the Pipe In buffer

Hi
I need to read the buffer length of the Pipe In to realize how many data are waiting to read. In the other hand I have send a command to my USB device, I would like to know when the replied packet is ready to read.

Asynchronous communication sample

I could use the library to implement synchronous data transfers using the pipes. I also would like to use the asynch data transfer feature, but I could find that in the wiki.

Could you help me to find the right documentation and/or code samples?

Using WinUSB.sys as function driver, Digital Signature on Cat file is not being recognized..

I am using WinUSB as a function driver in one of our project (little old). The following is the folder structure.

driver
|--drivername.inf
|--drivername.cat
|--amd64
------ |--WdfCoInstaller01005.dll
------ |--Winusbcoinstaller.dll
|--i386
------ |--WdfCoInstaller01005.dll
------ |--Winusbcoinstaller.dll

The INF file looks like this.

`[Version]
Signature = "$Windows NT$"
Class =makdevice
ClassGuid={ad769fbf-c592-4b8c-940a-6e3782a545e8}
Provider = %ProviderName%
DriverVer=02/27/2018,6.00.2064
CatalogFile=%MFGFILENAME%.cat

; ========== Manufacturer/Models sections ===========

[Manufacturer]
%ProviderName% = makInc,NTx86,NTamd64

[makInc.NTx86]
%USB\MyDevice.DeviceDesc% =USB_Install, USB\VID_1448&PID_4AC0&REV_0001

[makInc.NTamd64]
%USB\MyDevice.DeviceDesc% =USB_Install, USB\VID_1448&PID_4AC0&REV_0001

; =================== Installation ===================

[ClassInstall32]
AddReg=SampleClass_RegistryAdd

[SampleClass_RegistryAdd]
HKR,,,,%ClassName%

;[1]
[USB_Install]
Include=winusb.inf
Needs=WINUSB.NT

;[2]
[USB_Install.Services]
Include=winusb.inf
AddService=WinUSB,0x00000002,WinUSB_ServiceInstall

;[3]
[WinUSB_ServiceInstall]
DisplayName = %WinUSB_SvcDesc%
ServiceType = 1
StartType = 3
ErrorControl = 1
ServiceBinary = %12%\WinUSB.sys

;[4]
[USB_Install.Wdf]
KmdfService=WINUSB, WinUsb_Install

[WinUSB_Install]
KmdfLibraryVersion=1.5

;[5]
[USB_Install.HW]
AddReg=Dev_AddReg

[Dev_AddReg]
HKR,,DeviceInterfaceGUIDs,0x10000,"{55630179-b622-4834-8ff7-9916b1446884}"

;[6]
[USB_Install.CoInstallers]
AddReg=CoInstallers_AddReg
CopyFiles=CoInstallers_CopyFiles

[CoInstallers_AddReg]
HKR,,CoInstallers32,0x00010000,"WdfCoInstaller01005.dll,WdfCoInstaller","WinUSBCoInstaller.dll"

[CoInstallers_CopyFiles]
WinUSBCoInstaller.dll
WdfCoInstaller01005.dll

[DestinationDirs]
CoInstallers_CopyFiles=11

; ================= Source Media Section =====================
;[7]

[SourceDisksNames]
1 = %DISK_NAME%,,,\i386
2 = %DISK_NAME%,,,\amd64

[SourceDisksFiles.x86]
WinUSBCoInstaller.dll=1
WdfCoInstaller01005.dll=1

[SourceDisksFiles.NTamd64]
WinUSBCoInstaller.dll=2
WdfCoInstaller01005.dll=2

; =================== Strings ===================

[Strings]
MFGFILENAME="mak"
ProviderName="mak Inc"
ClassName="mak device"
USB\MyDevice.DeviceDesc="mak"
WinUSB_SvcDesc="mak"
DISK_NAME="Drivers"
`

I have generated the mak.cat file using Inf2Cat utility, then digitally signed using a Digicert EV Code signing certificate. And using these files an Installshield setup has been generated for the driver. But while installing the driver, the digital signature of the driver is not being recognized.
And the following error is being shown.
windows can't verify the publisher of this driver software

The digital signature of the .cat file seems valid. (I can right click the file and see the same in the properties)
The following is the DIFX options provided in install-shield to generate the driver installer.

Please help.. I have tried lot of forums.. Could not find any solution so far.. Please guide..

Cannot install/Automatic install

Due to lack of a better forum for questions like this:

I followed the MSDN guide to install WinUSB (on WinXP SP3) up to the point 
where it states "Open Device Manager to install the driver".

If I do that, and point the device manager to the location of my INF file, the 
device manager tells me "the specified location does not contain information 
about your hardware". What am I doing wrong here?

Also, is there any way to perform this step programmatically (in an installer)?

I've come across this project: http://winusbnet.codeplex.com/
It contains an installer for this exact purpose that seems to work. Sadly, 
there isn't any documentation about it (none that I could find, that is). I 
wanted to check the source code to know what the installer does but I cannot 
find it anywhere.

Is this project in any way connected to the codeplex project (same name)? Is it 
possible that WinUSB-Drivers installed using the codeplex project's installer 
are accessible with this library?

thx in advance for any pointers

Original issue reported on code.google.com by [email protected] on 30 Oct 2012 at 2:44

Failed to retrieve device descriptor.

MadWizard.WinUSBNet.USBException
HResult=0x80131500
Message=Failed to retrieve device descriptor.
Source=WinUSBNet
StackTrace:
at MadWizard.WinUSBNet.USBDevice.GetDeviceDescriptor(String devicePath)
at MadWizard.WinUSBNet.USBDevice..ctor(String devicePathName)
at MadWizard.WinUSBNet.USBDevice..ctor(USBDeviceInfo deviceInfo)
at WinUsbPrintTest.FrmMain.BtnCon_Click(Object sender, EventArgs e) in F:\WinUsbPrintTest\FrmMain.cs:line 33
at System.Windows.Forms.Control.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.ButtonBase.WndProc(Message& m)
at System.Windows.Forms.Button.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, WM msg, IntPtr wparam, IntPtr lparam)

内部异常 1:
APIException: Failed to initialize WinUSB handle. Device might not be connected.

内部异常 2:
Win32Exception: 内存资源不足,无法处理此命令。

Throw Exception When getting HID device

my os is WIN 10 64,
string[] hardwareIDs = GetMultiStringProperty(deviceInfoSet, deviceInfoData, SPDRP.SPDRP_HARDWAREID);
this hardwareIDS has no "USB" , LIKE: "HID\VID_046D&PID_C52B&REV_2407&MI_01&Col03"

            //Regex regex = new Regex("^USB\\\\VID_([0-9A-F]{4})&PID_([0-9A-F]{4})", RegexOptions.IgnoreCase); // this reg cause the exception
            Regex regex = new Regex("VID_([0-9A-F]{4})&PID_([0-9A-F]{4})", RegexOptions.IgnoreCase);
            bool foundVidPid = false;
            foreach (string hardwareID in hardwareIDs)
            {
                Match match = regex.Match(hardwareID);
                if (match.Success)
                {
                    details.VID = ushort.Parse(match.Groups[1].Value, System.Globalization.NumberStyles.AllowHexSpecifier);
                    details.PID = ushort.Parse(match.Groups[2].Value, System.Globalization.NumberStyles.AllowHexSpecifier);
                    foundVidPid = true;
                    break;
                }
            }

            if (!foundVidPid)
                throw new APIException("Failed to find VID and PID for USB device. No hardware ID could be parsed.");

            return details;

UWP compatibility

Is there any way to convert the API so that it can be used with UWP apps? I would like to use this on Windows 10 IoT Core with a UWP app and it looks like most of it can be used, but there are references to the Unwrapped and ThreadPool that aren't available. I'm not sure what the UWP equivalent of Unwrapped would be.

Can't instantiate USBDevice when the device doesn't provide the language ids descriptor

The CH372 processor (and the compatible ones CH375 and CH376, when configured in device mode) has an "internal firmware mode" in which the chip itself takes care of all the control transfers on endpoint 0. In this mode the processor doesn't provide any string descriptor at all, not even the language IDs descriptor: a request for this descriptor will always fail.

This makes it impossible to use WinUSBNet to access such a device. That's because the USBDevice constructor calls its GetDeviceDescriptor method, which will in turn call wuDevice.GetSupportedLanguageIDs(); this is going to throw, and thus GetDeviceDescriptor throws and the entire instantiation fails.

The following alternative implementation of USBDevice.GetDeviceDescriptor fixes the problem. If any string descriptor related operation fails the device object is still created without any string information whatsoever (it could be improved by wrapping a try around each string descriptor request, up to you):

private static USBDeviceDescriptor GetDeviceDescriptor(string devicePath)
{
    using (API.WinUSBDevice wuDevice = new API.WinUSBDevice())
    {
        API.USB_DEVICE_DESCRIPTOR deviceDesc;

        try {
            wuDevice.OpenDevice(devicePath);
            deviceDesc = wuDevice.GetDeviceDescriptor();
        }
        catch (API.APIException e) {
            throw new USBException("Failed to retrieve device descriptor.", e);
        }

        try {
            // Get first supported language ID
            ushort[] langIDs = wuDevice.GetSupportedLanguageIDs();
            ushort langID = 0;
            if (langIDs.Length > 0)
                langID = langIDs[0];

            string manufacturer = null, product = null, serialNumber = null;
            byte idx = 0;
            idx = deviceDesc.iManufacturer;
            if (idx > 0)
                manufacturer = wuDevice.GetStringDescriptor(idx, langID);

            idx = deviceDesc.iProduct;
            if (idx > 0)
                product = wuDevice.GetStringDescriptor(idx, langID);

            idx = deviceDesc.iSerialNumber;
            if (idx > 0)
                serialNumber = wuDevice.GetStringDescriptor(idx, langID);

            return new USBDeviceDescriptor(devicePath, deviceDesc, manufacturer, product, serialNumber);
        }
        catch (API.APIException) {
            return new USBDeviceDescriptor(devicePath, deviceDesc, null, null, null);
        }
    }
}

Add interfaces and hide the implementation

Could you please make all the currently publicly visible classes just 
interfaces, so that they can be mocked easily?

This would involve:
 - Make the currently visible classes internal and rename them
 - Make new public interfaces with the same names as the current public classes
 - Make the now internal classes implement the interfaces.

That way you can expose only interfaces that are implemented by your internal 
classes. And those interfaces are then easily testable, by mocking framworks 
like, Moq.

Original issue reported on code.google.com by [email protected] on 25 Aug 2012 at 7:03

Trezor Hardwarewallet Error Code 8 on WinUsb_Initialize

I am attempting to integrate with a cryptocurrency hardwarewallet called Trezor (https://trezor.io/). I have integrated via Hid, and USB across multiple platforms. It works on Android, UWP, and Windows (via LibUsbDotNet). The repo is here: https://github.com/MelbourneDeveloper/Trezor.Net. But, for some reason, when I try to use WinUsb, I get an error code of 8 (ERROR_NOT_ENOUGH_MEMORY). This is nothing wrong with your library, but I was wondering if you've got any ideas why this might occur...

At first I thought my code was just wrong, but the exact same problem is happening with your library here:

success = WinUsb_Initialize(_deviceHandle, ref _winUsbHandle);

Here is a long discussion on it:
https://stackoverflow.com/questions/53689682/windows-api-usb-io-winusb-dll

I would be so grateful if you could point me in the right direction.

I'm on windows 10. Could this be an issue? Several devices have the same issue.

Got an exception when invoke WinUsb_Initialize

I get usbDeviceInfo with guid {4D1E55B2-F16F-11CF-88CB-001111000030}.
But if I use the usbDeviceInfo to initialize an UsbDevice, I get the exception message in WinUsbDevice.InitializeDevice().
The message is "Failed to initialize WinUSB handle. Device might not be connected.", but the usb device is always connecting.

Write method of Pipe class with offset slices data written to device

What steps will reproduce the problem?
1. Use the Write method of Pipe with Offset
2. Data is chopped

The fix is to remove this block of code:
            if (offset != 0)
            {
                // Not the complete buffer, slice buffer
                byte[] newBuffer = new byte[length];
                Array.Copy(buffer, offset, newBuffer, 0, length);
                buffer = newBuffer;
            }

OR adjust the offset and length in the call to WritePipe of InternalDevice.

Original issue reported on code.google.com by [email protected] on 27 Mar 2012 at 12:41

Different DevicePath strings of the same device

What steps will reproduce the problem?

1.I am Scanning for WinUSB devices:
var winUsbDevices= 
USBDevice.GetDevices("{b14e250b-fbaf-473e-8580-3ea87b83f51e}");

2. If there are any, their DevicePath string will look like this:
"\\\\?\\usb#vid_0547&pid_1002#7&b578ddb&0&2#{b14e250b-fbaf-473e-8580-3ea87b83f51
e}"

Note the vid and pid: they are in lower case.

3. Now, I am registering for USB device plug detection:

 var plugDetector = new USBNotifier(hiddenControl, new Guid("{b14e250b-fbaf-473e-8580-3ea87b83f51e}"));
            plugDetector.Arrival += (sender2, e2) => {

            };

If the event is fired, e2.DevicePath returns a string:

"\\\\?\\USB#VID_0547&PID_1002#7&b578ddb&0&2#{b14e250b-fbaf-473e-8580-3ea87b83f51
e}"

vid and pid are now in uppercase!.. If I compare those strings, I get false 
results.

What version of the product are you using? On what operating system?
Latest WinUSBnet. On Windows 7 64 bit.

Original issue reported on code.google.com by [email protected] on 14 Sep 2012 at 8:06

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.