Code cleanup

This commit is contained in:
Gustave Monce
2019-12-22 12:25:48 +01:00
parent 0e6f905809
commit a2a1c2302b
149 changed files with 3980 additions and 4088 deletions
+5 -8
View File
@@ -6,11 +6,8 @@
*/
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime;
using System.Runtime.InteropServices;
using System.ComponentModel;
using System.Runtime.InteropServices;
namespace MadWizard.WinUSBNet.API
@@ -24,7 +21,7 @@ namespace MadWizard.WinUSBNet.API
public APIException(string message) :
base(message)
{
}
public APIException(string message, Exception innerException) : base(message, innerException)
{
@@ -40,11 +37,11 @@ namespace MadWizard.WinUSBNet.API
// ErrorCode = ErrorCode; // Break here
// return APIException.Win32(message, ErrorCode);
}
public static APIException Win32(string message, int errorCode)
public static APIException Win32(string message, int errorCode)
{
return new APIException(message, new Win32Exception(errorCode));
}
}
-5
View File
@@ -5,11 +5,6 @@
* http://www.opensource.org/licenses/mit-license.php
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MadWizard.WinUSBNet.API
{
internal struct DeviceDetails
+99 -99
View File
@@ -10,51 +10,51 @@
*/
using System;
using System.Runtime.InteropServices;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
namespace MadWizard.WinUSBNet.API
{
/// <summary>
/// Routines for detecting devices and receiving device notifications.
/// </summary>
internal static partial class DeviceManagement
{
/// <summary>
/// Routines for detecting devices and receiving device notifications.
/// </summary>
internal static partial class DeviceManagement
{
// Get device name from notification message.
// Also checks checkGuid with the GUID from the message to check the notification
// is for a relevant device. Other messages might be received.
public static string GetNotifyMessageDeviceName(IntPtr pDevBroadcastHeader, Guid checkGuid)
{
int stringSize;
{
int stringSize;
DEV_BROADCAST_DEVICEINTERFACE_1 devBroadcastDeviceInterface = new DEV_BROADCAST_DEVICEINTERFACE_1();
DEV_BROADCAST_HDR devBroadcastHeader = new DEV_BROADCAST_HDR();
DEV_BROADCAST_DEVICEINTERFACE_1 devBroadcastDeviceInterface = new DEV_BROADCAST_DEVICEINTERFACE_1();
DEV_BROADCAST_HDR devBroadcastHeader = new DEV_BROADCAST_HDR();
// The LParam parameter of Message is a pointer to a DEV_BROADCAST_HDR structure.
// The LParam parameter of Message is a pointer to a DEV_BROADCAST_HDR structure.
Marshal.PtrToStructure(pDevBroadcastHeader, devBroadcastHeader);
if ((devBroadcastHeader.dbch_devicetype == DBT_DEVTYP_DEVICEINTERFACE))
{
// The dbch_devicetype parameter indicates that the event applies to a device interface.
// So the structure in LParam is actually a DEV_BROADCAST_INTERFACE structure,
// which begins with a DEV_BROADCAST_HDR.
if ((devBroadcastHeader.dbch_devicetype == DBT_DEVTYP_DEVICEINTERFACE))
{
// The dbch_devicetype parameter indicates that the event applies to a device interface.
// So the structure in LParam is actually a DEV_BROADCAST_INTERFACE structure,
// which begins with a DEV_BROADCAST_HDR.
// Obtain the number of characters in dbch_name by subtracting the 32 bytes
// in the strucutre that are not part of dbch_name and dividing by 2 because there are
// 2 bytes per character.
// Obtain the number of characters in dbch_name by subtracting the 32 bytes
// in the strucutre that are not part of dbch_name and dividing by 2 because there are
// 2 bytes per character.
stringSize = System.Convert.ToInt32((devBroadcastHeader.dbch_size - 32) / 2);
// The dbcc_name parameter of devBroadcastDeviceInterface contains the device name.
// Trim dbcc_name to match the size of the String.
// The dbcc_name parameter of devBroadcastDeviceInterface contains the device name.
// Trim dbcc_name to match the size of the String.
devBroadcastDeviceInterface.dbcc_name = new char[stringSize + 1];
devBroadcastDeviceInterface.dbcc_name = new char[stringSize + 1];
// Marshal data from the unmanaged block pointed to by m.LParam
// to the managed object devBroadcastDeviceInterface.
// Marshal data from the unmanaged block pointed to by m.LParam
// to the managed object devBroadcastDeviceInterface.
Marshal.PtrToStructure(pDevBroadcastHeader, devBroadcastDeviceInterface);
@@ -66,7 +66,7 @@ namespace MadWizard.WinUSBNet.API
string deviceNameString = new String(devBroadcastDeviceInterface.dbcc_name, 0, stringSize);
return deviceNameString;
}
}
else if ((devBroadcastHeader.dbch_devicetype == DBT_DEVTYP_VOLUME))
{
DEV_BROADCAST_VOLUME vol = new DEV_BROADCAST_VOLUME();
@@ -80,10 +80,10 @@ namespace MadWizard.WinUSBNet.API
}
while (Mask > 0);
return @"\\.\" + Convert.ToChar(DriveInt) + ":";
}
}
return null;
}
}
private static byte[] GetProperty(IntPtr deviceInfoSet, SP_DEVINFO_DATA deviceInfoData, SPDRP property, out int regType)
{
uint requiredSize;
@@ -172,7 +172,7 @@ namespace MadWizard.WinUSBNet.API
details.DevicePath = devicePath;
details.DeviceDescription = GetStringProperty(deviceInfoSet, deviceInfoData, SPDRP.SPDRP_DEVICEDESC);
details.Manufacturer = GetStringProperty(deviceInfoSet, deviceInfoData, SPDRP.SPDRP_MFG);
// Heathcliff74
details.BusName = "";
try
@@ -180,7 +180,7 @@ namespace MadWizard.WinUSBNet.API
details.BusName = GetStringProperty(deviceInfoSet, deviceInfoData, new DEVPROPKEY(new Guid(0x540b947e, 0x8b40, 0x45bc, 0xa8, 0xa2, 0x6a, 0x0b, 0x89, 0x4c, 0xbd, 0xa2), 4));
}
catch { }
string[] hardwareIDs = GetMultiStringProperty(deviceInfoSet, deviceInfoData, SPDRP.SPDRP_HARDWAREID);
Regex regex = new Regex("^USB\\\\VID_([0-9A-F]{4})&PID_([0-9A-F]{4})", RegexOptions.IgnoreCase);
@@ -203,65 +203,65 @@ namespace MadWizard.WinUSBNet.API
return details;
}
public static DeviceDetails[] FindDevicesFromGuid(Guid guid)
{
public static DeviceDetails[] FindDevicesFromGuid(Guid guid)
{
IntPtr deviceInfoSet = IntPtr.Zero;
List<DeviceDetails> deviceList = new List<DeviceDetails>();
try
{
deviceInfoSet = SetupDiGetClassDevs(ref guid, IntPtr.Zero, IntPtr.Zero,
try
{
deviceInfoSet = SetupDiGetClassDevs(ref guid, IntPtr.Zero, IntPtr.Zero,
DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
if (deviceInfoSet == FileIO.INVALID_HANDLE_VALUE)
throw APIException.Win32("Failed to enumerate devices.");
int memberIndex = 0;
while(true)
{
// Begin with 0 and increment through the device information set until
// no more devices are available.
while (true)
{
// Begin with 0 and increment through the device information set until
// no more devices are available.
SP_DEVICE_INTERFACE_DATA deviceInterfaceData = new SP_DEVICE_INTERFACE_DATA();
// The cbSize element of the deviceInterfaceData structure must be set to
// the structure's size in bytes.
// The size is 28 bytes for 32-bit code and 32 bytes for 64-bit code.
deviceInterfaceData.cbSize = Marshal.SizeOf(deviceInterfaceData);
// The cbSize element of the deviceInterfaceData structure must be set to
// the structure's size in bytes.
// The size is 28 bytes for 32-bit code and 32 bytes for 64-bit code.
deviceInterfaceData.cbSize = Marshal.SizeOf(deviceInterfaceData);
bool success;
success = SetupDiEnumDeviceInterfaces(deviceInfoSet, IntPtr.Zero, ref guid, memberIndex, ref deviceInterfaceData);
success = SetupDiEnumDeviceInterfaces(deviceInfoSet, IntPtr.Zero, ref guid, memberIndex, ref deviceInterfaceData);
// Find out if a device information set was retrieved.
if (!success)
{
// Find out if a device information set was retrieved.
if (!success)
{
int lastError = Marshal.GetLastWin32Error();
if (lastError == ERROR_NO_MORE_ITEMS)
break;
throw APIException.Win32("Failed to get device interface.");
}
// A device is present.
}
// A device is present.
int bufferSize = 0;
success = SetupDiGetDeviceInterfaceDetail
(deviceInfoSet,
ref deviceInterfaceData,
IntPtr.Zero,
0,
ref bufferSize,
IntPtr.Zero);
success = SetupDiGetDeviceInterfaceDetail
(deviceInfoSet,
ref deviceInterfaceData,
IntPtr.Zero,
0,
ref bufferSize,
IntPtr.Zero);
if (!success)
{
if (Marshal.GetLastWin32Error() != ERROR_INSUFFICIENT_BUFFER)
throw APIException.Win32("Failed to get interface details buffer size.");
}
IntPtr detailDataBuffer = IntPtr.Zero;
try
{
// Allocate memory for the SP_DEVICE_INTERFACE_DETAIL_DATA structure using the returned buffer size.
detailDataBuffer = Marshal.AllocHGlobal(bufferSize);
@@ -288,10 +288,10 @@ namespace MadWizard.WinUSBNet.API
if (!success)
throw APIException.Win32("Failed to get device interface details.");
// Skip over cbsize (4 bytes) to get the address of the devicePathName.
IntPtr pDevicePathName = new IntPtr(detailDataBuffer.ToInt64() + 4);
string pathName = Marshal.PtrToStringUni(pDevicePathName);
@@ -299,7 +299,7 @@ namespace MadWizard.WinUSBNet.API
DeviceDetails details = GetDeviceDetails(pathName, deviceInfoSet, da);
deviceList.Add(details);
}
finally
@@ -311,58 +311,58 @@ namespace MadWizard.WinUSBNet.API
}
}
memberIndex++;
}
}
finally
{
}
}
finally
{
if (deviceInfoSet != IntPtr.Zero && deviceInfoSet != FileIO.INVALID_HANDLE_VALUE)
{
SetupDiDestroyDeviceInfoList(deviceInfoSet);
}
}
{
SetupDiDestroyDeviceInfoList(deviceInfoSet);
}
}
return deviceList.ToArray();
}
}
public static void RegisterForDeviceNotifications(IntPtr controlHandle, Guid classGuid, ref IntPtr deviceNotificationHandle)
{
public static void RegisterForDeviceNotifications(IntPtr controlHandle, Guid classGuid, ref IntPtr deviceNotificationHandle)
{
DEV_BROADCAST_DEVICEINTERFACE devBroadcastDeviceInterface = new DEV_BROADCAST_DEVICEINTERFACE();
IntPtr devBroadcastDeviceInterfaceBuffer = IntPtr.Zero;
try
{
int size = Marshal.SizeOf(devBroadcastDeviceInterface);
devBroadcastDeviceInterface.dbcc_size = size;
DEV_BROADCAST_DEVICEINTERFACE devBroadcastDeviceInterface = new DEV_BROADCAST_DEVICEINTERFACE();
IntPtr devBroadcastDeviceInterfaceBuffer = IntPtr.Zero;
try
{
int size = Marshal.SizeOf(devBroadcastDeviceInterface);
devBroadcastDeviceInterface.dbcc_size = size;
devBroadcastDeviceInterface.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE;
devBroadcastDeviceInterface.dbcc_reserved = 0;
devBroadcastDeviceInterface.dbcc_classguid = classGuid;
devBroadcastDeviceInterfaceBuffer = Marshal.AllocHGlobal(size);
devBroadcastDeviceInterface.dbcc_reserved = 0;
devBroadcastDeviceInterface.dbcc_classguid = classGuid;
devBroadcastDeviceInterfaceBuffer = Marshal.AllocHGlobal(size);
// Copy the DEV_BROADCAST_DEVICEINTERFACE structure to the buffer.
// Set fDeleteOld True to prevent memory leaks.
Marshal.StructureToPtr(devBroadcastDeviceInterface, devBroadcastDeviceInterfaceBuffer, true);
// Copy the DEV_BROADCAST_DEVICEINTERFACE structure to the buffer.
// Set fDeleteOld True to prevent memory leaks.
Marshal.StructureToPtr(devBroadcastDeviceInterface, devBroadcastDeviceInterfaceBuffer, true);
deviceNotificationHandle = RegisterDeviceNotification(controlHandle, devBroadcastDeviceInterfaceBuffer, DEVICE_NOTIFY_WINDOW_HANDLE);
deviceNotificationHandle = RegisterDeviceNotification(controlHandle, devBroadcastDeviceInterfaceBuffer, DEVICE_NOTIFY_WINDOW_HANDLE);
if (deviceNotificationHandle == IntPtr.Zero)
throw APIException.Win32("Failed to register device notification");
// Marshal data from the unmanaged block devBroadcastDeviceInterfaceBuffer to
// the managed object devBroadcastDeviceInterface
// the managed object devBroadcastDeviceInterface
Marshal.PtrToStructure(devBroadcastDeviceInterfaceBuffer, devBroadcastDeviceInterface);
}
finally
{
}
finally
{
// Free the memory allocated previously by AllocHGlobal.
if (devBroadcastDeviceInterfaceBuffer != IntPtr.Zero)
if (devBroadcastDeviceInterfaceBuffer != IntPtr.Zero)
Marshal.FreeHGlobal(devBroadcastDeviceInterfaceBuffer);
}
}
}
}
public static void StopDeviceDeviceNotifications(IntPtr deviceNotificationHandle)
{
{
if (!DeviceManagement.UnregisterDeviceNotification(deviceNotificationHandle))
throw APIException.Win32("Failed to unregister device notification");
}
}
}
}
}
+50 -50
View File
@@ -14,14 +14,14 @@ using System.Runtime.InteropServices;
namespace MadWizard.WinUSBNet.API
{
/// <summary>
/// API declarations relating to device management (SetupDixxx and
/// RegisterDeviceNotification functions).
/// </summary>
/// <summary>
/// API declarations relating to device management (SetupDixxx and
/// RegisterDeviceNotification functions).
/// </summary>
internal static partial class DeviceManagement
{
// from dbt.h
internal static partial class DeviceManagement
{
// from dbt.h
internal const Int32 DBT_DEVICEARRIVAL = 0X8000;
internal const Int32 DBT_DEVICEREMOVECOMPLETE = 0X8004;
@@ -40,31 +40,31 @@ namespace MadWizard.WinUSBNet.API
private const Int32 DIGCF_PRESENT = 2;
private const Int32 DIGCF_DEVICEINTERFACE = 0X10;
// Two declarations for the DEV_BROADCAST_DEVICEINTERFACE structure.
// Two declarations for the DEV_BROADCAST_DEVICEINTERFACE structure.
// Use this one in the call to RegisterDeviceNotification() and
// in checking dbch_devicetype in a DEV_BROADCAST_HDR structure:
// Use this one in the call to RegisterDeviceNotification() and
// in checking dbch_devicetype in a DEV_BROADCAST_HDR structure:
[StructLayout(LayoutKind.Sequential)]
[StructLayout(LayoutKind.Sequential)]
private class DEV_BROADCAST_DEVICEINTERFACE
{
internal Int32 dbcc_size;
internal Int32 dbcc_devicetype;
internal Int32 dbcc_reserved;
internal Guid dbcc_classguid;
internal Int16 dbcc_name;
}
{
internal Int32 dbcc_size;
internal Int32 dbcc_devicetype;
internal Int32 dbcc_reserved;
internal Guid dbcc_classguid;
internal Int16 dbcc_name;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
private class DEV_BROADCAST_DEVICEINTERFACE_1
{
internal Int32 dbcc_size;
internal Int32 dbcc_devicetype;
internal Int32 dbcc_reserved;
internal Guid dbcc_classguid;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 255)]
internal Char[] dbcc_name;
}
{
internal Int32 dbcc_size;
internal Int32 dbcc_devicetype;
internal Int32 dbcc_reserved;
internal Guid dbcc_classguid;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 255)]
internal Char[] dbcc_name;
}
[StructLayout(LayoutKind.Sequential)]
public class DEV_BROADCAST_VOLUME
@@ -75,21 +75,21 @@ namespace MadWizard.WinUSBNet.API
public Int32 dbcv_unitmask;
}
[StructLayout(LayoutKind.Sequential)]
[StructLayout(LayoutKind.Sequential)]
private class DEV_BROADCAST_HDR
{
internal Int32 dbch_size;
internal Int32 dbch_devicetype;
internal Int32 dbch_reserved;
}
{
internal Int32 dbch_size;
internal Int32 dbch_devicetype;
internal Int32 dbch_reserved;
}
private struct SP_DEVICE_INTERFACE_DATA
{
internal Int32 cbSize;
internal System.Guid InterfaceClassGuid;
internal Int32 Flags;
internal IntPtr Reserved;
}
{
internal Int32 cbSize;
internal System.Guid InterfaceClassGuid;
internal Int32 Flags;
internal IntPtr Reserved;
}
private struct SP_DEVINFO_DATA
{
internal Int32 cbSize;
@@ -145,14 +145,14 @@ namespace MadWizard.WinUSBNet.API
[DllImport("user32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern IntPtr RegisterDeviceNotification(IntPtr hRecipient, IntPtr NotificationFilter, Int32 Flags);
//[DllImport("setupapi.dll", SetLastError = true)]
//internal static extern Int32 SetupDiCreateDeviceInfoList(ref System.Guid ClassGuid, Int32 hwndParent);
//[DllImport("setupapi.dll", SetLastError = true)]
//internal static extern Int32 SetupDiCreateDeviceInfoList(ref System.Guid ClassGuid, Int32 hwndParent);
[DllImport("setupapi.dll", SetLastError = true)]
private static extern Int32 SetupDiDestroyDeviceInfoList(IntPtr DeviceInfoSet);
[DllImport("setupapi.dll", SetLastError = true)]
private static extern Int32 SetupDiDestroyDeviceInfoList(IntPtr DeviceInfoSet);
[DllImport("setupapi.dll", SetLastError = true)]
private static extern bool SetupDiEnumDeviceInterfaces(IntPtr DeviceInfoSet, IntPtr DeviceInfoData, ref System.Guid InterfaceClassGuid, Int32 MemberIndex, ref SP_DEVICE_INTERFACE_DATA DeviceInterfaceData);
[DllImport("setupapi.dll", SetLastError = true)]
private static extern bool SetupDiEnumDeviceInterfaces(IntPtr DeviceInfoSet, IntPtr DeviceInfoData, ref System.Guid InterfaceClassGuid, Int32 MemberIndex, ref SP_DEVICE_INTERFACE_DATA DeviceInterfaceData);
[DllImport("setupapi.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern bool SetupDiGetDeviceRegistryProperty(IntPtr DeviceInfoSet, ref SP_DEVINFO_DATA DeviceInfoData, SPDRP Property, out int PropertyRegDataType, byte[] PropertyBuffer, uint PropertyBufferSize, out UInt32 RequiredSize);
@@ -163,19 +163,19 @@ namespace MadWizard.WinUSBNet.API
[DllImport("setupapi.dll", CharSet = CharSet.Unicode, SetLastError = true)]
static extern unsafe bool SetupDiGetDeviceProperty(IntPtr deviceInfoSet, ref SP_DEVINFO_DATA DeviceInfoData, ref DEVPROPKEY propertyKey, out UInt32 propertyType, byte[] propertyBuffer, Int32 propertyBufferSize, out int requiredSize, UInt32 flags);
[DllImport("setupapi.dll", SetLastError = true, CharSet = CharSet.Unicode)]
[DllImport("setupapi.dll", SetLastError = true, CharSet = CharSet.Unicode)]
private static extern IntPtr SetupDiGetClassDevs(ref System.Guid ClassGuid, IntPtr Enumerator, IntPtr hwndParent, Int32 Flags);
[DllImport("setupapi.dll", SetLastError = true, CharSet = CharSet.Unicode)]
[DllImport("setupapi.dll", SetLastError = true, CharSet = CharSet.Unicode)]
private static extern bool SetupDiGetDeviceInterfaceDetail(IntPtr DeviceInfoSet, ref SP_DEVICE_INTERFACE_DATA DeviceInterfaceData, IntPtr DeviceInterfaceDetailData, Int32 DeviceInterfaceDetailDataSize, ref Int32 RequiredSize, ref SP_DEVINFO_DATA DeviceInfoData);
[DllImport("setupapi.dll", SetLastError = true, CharSet = CharSet.Unicode)]
private static extern bool SetupDiGetDeviceInterfaceDetail(IntPtr DeviceInfoSet, ref SP_DEVICE_INTERFACE_DATA DeviceInterfaceData, IntPtr DeviceInterfaceDetailData, Int32 DeviceInterfaceDetailDataSize, ref Int32 RequiredSize, IntPtr DeviceInfoData);
[DllImport("user32.dll", SetLastError = true)]
private static extern bool UnregisterDeviceNotification(IntPtr Handle);
[DllImport("user32.dll", SetLastError = true)]
private static extern bool UnregisterDeviceNotification(IntPtr Handle);
private const int ERROR_NO_MORE_ITEMS = 259;
private const int ERROR_INSUFFICIENT_BUFFER = 122;
}
}
}
+9 -9
View File
@@ -9,19 +9,19 @@
* See http://www.lvr.com/winusb.htm for more information
*/
using System;
using Microsoft.Win32.SafeHandles;
using System;
using System.Runtime.InteropServices;
namespace MadWizard.WinUSBNet.API
{
/// <summary>
/// API declarations relating to file I/O (and used by WinUsb).
/// </summary>
/// <summary>
/// API declarations relating to file I/O (and used by WinUsb).
/// </summary>
sealed internal class FileIO
{
public const Int32 FILE_ATTRIBUTE_NORMAL = 0X80;
sealed internal class FileIO
{
public const Int32 FILE_ATTRIBUTE_NORMAL = 0X80;
public const Int32 FILE_FLAG_OVERLAPPED = 0X40000000;
public const Int32 FILE_SHARE_READ = 1;
public const Int32 FILE_SHARE_WRITE = 2;
@@ -32,8 +32,8 @@ namespace MadWizard.WinUSBNet.API
public const Int32 ERROR_IO_PENDING = 997;
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
public static extern SafeFileHandle CreateFile(String lpFileName, UInt32 dwDesiredAccess, Int32 dwShareMode, IntPtr lpSecurityAttributes, Int32 dwCreationDisposition, Int32 dwFlagsAndAttributes, Int32 hTemplateFile);
}
}
}
+57 -58
View File
@@ -9,22 +9,21 @@
* See http://www.lvr.com/winusb.htm for more information
*/
using System;
using Microsoft.Win32.SafeHandles;
using System.Runtime.InteropServices;
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Threading;
using System.ComponentModel;
namespace MadWizard.WinUSBNet.API
{
/// <summary>
/// Wrapper for a WinUSB device dealing with the WinUSB and additional interface handles
/// </summary>
partial class WinUSBDevice : IDisposable
{
/// <summary>
/// Wrapper for a WinUSB device dealing with the WinUSB and additional interface handles
/// </summary>
partial class WinUSBDevice : IDisposable
{
private bool _disposed = false;
private SafeFileHandle _deviceHandle;
private SafeFileHandle _deviceHandle;
private IntPtr _winUsbHandle = IntPtr.Zero;
private IntPtr[] _addInterfaces = null;
public WinUSBDevice()
@@ -57,13 +56,13 @@ namespace MadWizard.WinUSBNet.API
if (disposing)
{
// Dispose managed resources
// Dispose managed resources
if (_deviceHandle != null && !_deviceHandle.IsInvalid)
_deviceHandle.Dispose();
_deviceHandle = null;
}
// Dispose unmanaged resources
// Dispose unmanaged resources
FreeWinUSB();
_disposed = true;
}
@@ -105,8 +104,8 @@ namespace MadWizard.WinUSBNet.API
bool success = WinUsb_GetDescriptor(_winUsbHandle, USB_STRING_DESCRIPTOR_TYPE,
index, 0, buffer, (uint)buffer.Length, out transfered);
if (!success)
throw APIException.Win32("Failed to get USB string descriptor (" + index + "): 0x" + Marshal.GetLastWin32Error().ToString("X8"));
throw APIException.Win32("Failed to get USB string descriptor (" + index + "): 0x" + Marshal.GetLastWin32Error().ToString("X8"));
int length = buffer[0] - 2;
if (length <= 0)
return null;
@@ -115,10 +114,10 @@ namespace MadWizard.WinUSBNet.API
}
public void ControlTransfer(byte requestType, byte request, ushort value, ushort index, ushort length, byte[] data)
{
uint bytesReturned = 0;
WINUSB_SETUP_PACKET setupPacket;
{
uint bytesReturned = 0;
WINUSB_SETUP_PACKET setupPacket;
setupPacket.RequestType = requestType;
setupPacket.Request = request;
setupPacket.Value = value;
@@ -128,26 +127,26 @@ namespace MadWizard.WinUSBNet.API
bool success = WinUsb_ControlTransfer(_winUsbHandle, setupPacket, data, length, ref bytesReturned, IntPtr.Zero);
if (!success) // todo check bytes returned?
throw APIException.Win32("Control transfer on WinUSB device failed.");
}
}
public void OpenDevice(string devicePathName)
{
public void OpenDevice(string devicePathName)
{
try
{
_deviceHandle = FileIO.CreateFile(devicePathName,
(FileIO.GENERIC_WRITE | FileIO.GENERIC_READ),
FileIO.FILE_SHARE_READ | FileIO.FILE_SHARE_WRITE,
IntPtr.Zero,
FileIO.OPEN_EXISTING,
FileIO.FILE_ATTRIBUTE_NORMAL | FileIO.FILE_FLAG_OVERLAPPED,
0);
_deviceHandle = FileIO.CreateFile(devicePathName,
(FileIO.GENERIC_WRITE | FileIO.GENERIC_READ),
FileIO.FILE_SHARE_READ | FileIO.FILE_SHARE_WRITE,
IntPtr.Zero,
FileIO.OPEN_EXISTING,
FileIO.FILE_ATTRIBUTE_NORMAL | FileIO.FILE_FLAG_OVERLAPPED,
0);
if (_deviceHandle.IsInvalid)
throw APIException.Win32("Failed to open WinUSB device handle.");
InitializeDevice();
}
catch(Exception)
catch (Exception)
{
if (_deviceHandle != null)
{
@@ -157,7 +156,7 @@ namespace MadWizard.WinUSBNet.API
FreeWinUSB();
throw;
}
}
}
private IntPtr InterfaceHandle(int index)
{
@@ -194,11 +193,11 @@ namespace MadWizard.WinUSBNet.API
pipes = pipeList.ToArray();
}
private void InitializeDevice()
{
bool success;
private void InitializeDevice()
{
bool success;
success = WinUsb_Initialize(_deviceHandle, ref _winUsbHandle);
success = WinUsb_Initialize(_deviceHandle, ref _winUsbHandle);
if (!success)
throw APIException.Win32("Failed to initialize WinUSB handle. Device might not be connected.");
@@ -237,10 +236,10 @@ namespace MadWizard.WinUSBNet.API
// Bind handle (needed for overlapped I/O thread pool)
ThreadPool.BindHandle(_deviceHandle);
// TODO: bind interface handles as well? doesn't seem to be necessary
}
}
public void ReadPipe(int ifaceIndex, byte pipeID, byte[] buffer, int offset, int bytesToRead, out uint bytesRead)
{
public void ReadPipe(int ifaceIndex, byte pipeID, byte[] buffer, int offset, int bytesToRead, out uint bytesRead)
{
bool success;
unsafe
{
@@ -254,7 +253,7 @@ namespace MadWizard.WinUSBNet.API
}
if (!success)
throw APIException.Win32("Failed to read pipe on WinUSB device.");
}
}
private unsafe void HandleOverlappedAPI(bool success, string errorMessage, NativeOverlapped* pOverlapped, USBAsyncResult result, int bytesTransfered)
{
@@ -276,13 +275,13 @@ namespace MadWizard.WinUSBNet.API
result.OnCompletion(true, null, bytesTransfered, false);
// is the callback still called in this case?? todo
}
}
public void ReadPipeOverlapped(int ifaceIndex, byte pipeID, byte[] buffer, int offset, int bytesToRead, USBAsyncResult result)
{
Overlapped overlapped = new Overlapped();
overlapped.AsyncResult = result;
unsafe
@@ -313,7 +312,7 @@ namespace MadWizard.WinUSBNet.API
uint bytesWritten;
pOverlapped = overlapped.Pack(PipeIOCallback, buffer);
bool success;
// Buffer is pinned already by overlapped.Pack
fixed (byte* pBuffer = buffer)
@@ -326,13 +325,13 @@ namespace MadWizard.WinUSBNet.API
}
}
public void ControlTransferOverlapped(byte requestType, byte request, ushort value, ushort index, ushort length, byte[] data, USBAsyncResult result)
{
uint bytesReturned = 0;
WINUSB_SETUP_PACKET setupPacket;
{
uint bytesReturned = 0;
WINUSB_SETUP_PACKET setupPacket;
setupPacket.RequestType = requestType;
setupPacket.Request = request;
setupPacket.Value = value;
@@ -349,7 +348,7 @@ namespace MadWizard.WinUSBNet.API
bool success = WinUsb_ControlTransfer(_winUsbHandle, setupPacket, data, length, ref bytesReturned, pOverlapped);
HandleOverlappedAPI(success, "Asynchronous control transfer on WinUSB device failed.", pOverlapped, result, (int)bytesReturned);
}
}
}
private unsafe void PipeIOCallback(uint errorCode, uint numBytes, NativeOverlapped* pOverlapped)
{
@@ -393,7 +392,7 @@ namespace MadWizard.WinUSBNet.API
}
public void WritePipe(int ifaceIndex, byte pipeID, byte[] buffer, int offset, int length)
{
{
uint bytesWritten;
bool success;
unsafe
@@ -408,8 +407,8 @@ namespace MadWizard.WinUSBNet.API
}
if (!success || (bytesWritten != length))
throw APIException.Win32("Failed to write pipe on WinUSB device.");
}
}
public void FlushPipe(int ifaceIndex, byte pipeID)
{
@@ -419,29 +418,29 @@ namespace MadWizard.WinUSBNet.API
}
public void SetPipePolicy(int ifaceIndex, byte pipeID, POLICY_TYPE policyType, bool value)
{
{
byte byteVal = (byte)(value ? 1 : 0);
bool success = WinUsb_SetPipePolicy(InterfaceHandle(ifaceIndex), pipeID, (uint)policyType, 1, ref byteVal);
if (!success)
throw APIException.Win32("Failed to set WinUSB pipe policy.");
}
}
public void SetPipePolicy(int ifaceIndex, byte pipeID, POLICY_TYPE policyType, uint value)
{
{
bool success = WinUsb_SetPipePolicy(InterfaceHandle(ifaceIndex), pipeID, (uint)policyType, 4, ref value);
if (!success)
throw APIException.Win32("Failed to set WinUSB pipe policy.");
}
}
public bool GetPipePolicyBool(int ifaceIndex, byte pipeID, POLICY_TYPE policyType)
{
byte result;
uint length = 1;
bool success = WinUsb_GetPipePolicy(InterfaceHandle(ifaceIndex), pipeID, (uint)policyType, ref length, out result);
if (!success || length != 1)
throw APIException.Win32("Failed to get WinUSB pipe policy.");
@@ -451,7 +450,7 @@ namespace MadWizard.WinUSBNet.API
public uint GetPipePolicyUInt(int ifaceIndex, byte pipeID, POLICY_TYPE policyType)
{
uint result;
uint length = 4;
bool success = WinUsb_GetPipePolicy(InterfaceHandle(ifaceIndex), pipeID, (uint)policyType, ref length, out result);
@@ -460,5 +459,5 @@ namespace MadWizard.WinUSBNet.API
throw APIException.Win32("Failed to get WinUSB pipe policy.");
return result;
}
}
}
}
+94 -94
View File
@@ -9,90 +9,90 @@
* See http://www.lvr.com/winusb.htm for more information
*/
using System;
using Microsoft.Win32.SafeHandles;
using System;
using System.Runtime.InteropServices;
using System.Threading;
namespace MadWizard.WinUSBNet.API
{
[StructLayout(LayoutKind.Sequential)]
struct USB_DEVICE_DESCRIPTOR
{
public byte bLength;
public byte bDescriptorType;
public ushort bcdUSB;
public byte bDeviceClass;
public byte bDeviceSubClass;
public byte bDeviceProtocol;
public byte bMaxPacketSize0;
public ushort idVendor;
public ushort idProduct;
public ushort bcdDevice;
public byte iManufacturer;
public byte iProduct;
public byte iSerialNumber;
public byte bNumConfigurations;
};
[StructLayout(LayoutKind.Sequential)]
struct USB_DEVICE_DESCRIPTOR
{
public byte bLength;
public byte bDescriptorType;
public ushort bcdUSB;
public byte bDeviceClass;
public byte bDeviceSubClass;
public byte bDeviceProtocol;
public byte bMaxPacketSize0;
public ushort idVendor;
public ushort idProduct;
public ushort bcdDevice;
public byte iManufacturer;
public byte iProduct;
public byte iSerialNumber;
public byte bNumConfigurations;
};
[StructLayout(LayoutKind.Sequential)]
struct USB_CONFIGURATION_DESCRIPTOR
{
public byte bLength;
public byte bDescriptorType;
public ushort wTotalLength;
public byte bNumInterfaces;
public byte bConfigurationValue;
public byte iConfiguration;
public byte bmAttributes;
public byte MaxPower;
}
[StructLayout(LayoutKind.Sequential)]
struct USB_CONFIGURATION_DESCRIPTOR
{
public byte bLength;
public byte bDescriptorType;
public ushort wTotalLength;
public byte bNumInterfaces;
public byte bConfigurationValue;
public byte iConfiguration;
public byte bmAttributes;
public byte MaxPower;
}
[StructLayout(LayoutKind.Sequential)]
struct USB_INTERFACE_DESCRIPTOR
{
public byte bLength;
public byte bDescriptorType;
public byte bInterfaceNumber;
public byte bAlternateSetting;
public byte bNumEndpoints;
public byte bInterfaceClass;
public byte bInterfaceSubClass;
public byte bInterfaceProtocol;
public byte iInterface;
};
enum USBD_PIPE_TYPE : int
{
UsbdPipeTypeControl,
UsbdPipeTypeIsochronous,
UsbdPipeTypeBulk,
UsbdPipeTypeInterrupt,
}
[StructLayout(LayoutKind.Sequential)]
struct WINUSB_PIPE_INFORMATION
{
public USBD_PIPE_TYPE PipeType;
public byte PipeId;
public ushort MaximumPacketSize;
public byte Interval;
}
[StructLayout(LayoutKind.Sequential)]
struct USB_INTERFACE_DESCRIPTOR
{
public byte bLength;
public byte bDescriptorType;
public byte bInterfaceNumber;
public byte bAlternateSetting;
public byte bNumEndpoints;
public byte bInterfaceClass;
public byte bInterfaceSubClass;
public byte bInterfaceProtocol;
public byte iInterface;
};
enum USBD_PIPE_TYPE : int
{
UsbdPipeTypeControl,
UsbdPipeTypeIsochronous,
UsbdPipeTypeBulk,
UsbdPipeTypeInterrupt,
}
[StructLayout(LayoutKind.Sequential)]
struct WINUSB_PIPE_INFORMATION
{
public USBD_PIPE_TYPE PipeType;
public byte PipeId;
public ushort MaximumPacketSize;
public byte Interval;
}
enum POLICY_TYPE : int
{
SHORT_PACKET_TERMINATE = 1,
AUTO_CLEAR_STALL,
PIPE_TRANSFER_TIMEOUT,
IGNORE_SHORT_PACKETS,
ALLOW_PARTIAL_READS,
AUTO_FLUSH,
RAW_IO,
}
enum POLICY_TYPE : int
{
SHORT_PACKET_TERMINATE = 1,
AUTO_CLEAR_STALL,
PIPE_TRANSFER_TIMEOUT,
IGNORE_SHORT_PACKETS,
ALLOW_PARTIAL_READS,
AUTO_FLUSH,
RAW_IO,
}
partial class WinUSBDevice
{
private const UInt32 DEVICE_SPEED = ((UInt32)(1));
partial class WinUSBDevice
{
private const UInt32 DEVICE_SPEED = ((UInt32)(1));
private enum USB_DEVICE_SPEED : int
{
UsbLowSpeed = 1,
@@ -110,75 +110,75 @@ namespace MadWizard.WinUSBNet.API
public ushort Length;
}
[DllImport("winusb.dll", SetLastError = true)]
[DllImport("winusb.dll", SetLastError = true)]
private static extern bool WinUsb_ControlTransfer(IntPtr InterfaceHandle, WINUSB_SETUP_PACKET SetupPacket, Byte[] Buffer, UInt32 BufferLength, ref UInt32 LengthTransferred, IntPtr Overlapped);
[DllImport("winusb.dll", SetLastError = true)]
private static unsafe extern bool WinUsb_ControlTransfer(IntPtr InterfaceHandle, WINUSB_SETUP_PACKET SetupPacket, Byte[] Buffer, UInt32 BufferLength, ref UInt32 LengthTransferred, NativeOverlapped* pOverlapped);
[DllImport("winusb.dll", SetLastError = true)]
[DllImport("winusb.dll", SetLastError = true)]
private static extern bool WinUsb_Free(IntPtr InterfaceHandle);
[DllImport("winusb.dll", SetLastError = true)]
[DllImport("winusb.dll", SetLastError = true)]
private static extern bool WinUsb_Initialize(SafeFileHandle DeviceHandle, ref IntPtr InterfaceHandle);
[DllImport("winusb.dll", SetLastError = true)]
[DllImport("winusb.dll", SetLastError = true)]
private static extern bool WinUsb_QueryDeviceInformation(IntPtr InterfaceHandle, UInt32 InformationType, ref UInt32 BufferLength, out byte Buffer);
[DllImport("winusb.dll", SetLastError = true)]
[DllImport("winusb.dll", SetLastError = true)]
private static extern bool WinUsb_QueryInterfaceSettings(IntPtr InterfaceHandle, Byte AlternateInterfaceNumber, out USB_INTERFACE_DESCRIPTOR UsbAltInterfaceDescriptor);
[DllImport("winusb.dll", SetLastError = true)]
[DllImport("winusb.dll", SetLastError = true)]
private static extern bool WinUsb_QueryPipe(IntPtr InterfaceHandle, Byte AlternateInterfaceNumber, Byte PipeIndex, out WINUSB_PIPE_INFORMATION PipeInformation);
[DllImport("winusb.dll", SetLastError = true)]
[DllImport("winusb.dll", SetLastError = true)]
private static unsafe extern bool WinUsb_ReadPipe(IntPtr InterfaceHandle, byte PipeID, byte* pBuffer, uint BufferLength, out uint LengthTransferred, IntPtr Overlapped);
[DllImport("winusb.dll", SetLastError = true)]
private static unsafe extern bool WinUsb_ReadPipe(IntPtr InterfaceHandle, byte PipeID, byte* pBuffer, uint BufferLength, out uint LengthTransferred, NativeOverlapped* pOverlapped);
[DllImport("winusb.dll", SetLastError = true)]
private static extern bool WinUsb_AbortPipe(IntPtr InterfaceHandle, byte PipeID);
// Two declarations for WinUsb_SetPipePolicy.
// Use this one when the returned Value is a Byte (all except PIPE_TRANSFER_TIMEOUT):
// Two declarations for WinUsb_SetPipePolicy.
// Use this one when the returned Value is a Byte (all except PIPE_TRANSFER_TIMEOUT):
[DllImport("winusb.dll", SetLastError = true)]
[DllImport("winusb.dll", SetLastError = true)]
private static extern bool WinUsb_SetPipePolicy(IntPtr InterfaceHandle, Byte PipeID, UInt32 PolicyType, UInt32 ValueLength, ref byte Value);
[DllImport("winusb.dll", SetLastError = true)]
private static extern bool WinUsb_GetPipePolicy(IntPtr InterfaceHandle, Byte PipeID, UInt32 PolicyType, ref UInt32 ValueLength, out byte Value);
// Use this alias when the returned Value is a UInt32 (PIPE_TRANSFER_TIMEOUT only):
// Use this alias when the returned Value is a UInt32 (PIPE_TRANSFER_TIMEOUT only):
[DllImport("winusb.dll", SetLastError = true)]
[DllImport("winusb.dll", SetLastError = true)]
private static extern bool WinUsb_SetPipePolicy(IntPtr InterfaceHandle, Byte PipeID, UInt32 PolicyType, UInt32 ValueLength, ref UInt32 Value);
[DllImport("winusb.dll", SetLastError = true)]
private static extern bool WinUsb_GetPipePolicy(IntPtr InterfaceHandle, Byte PipeID, UInt32 PolicyType, ref UInt32 ValueLength, out UInt32 Value);
[DllImport("winusb.dll", SetLastError = true)]
[DllImport("winusb.dll", SetLastError = true)]
private static unsafe extern bool WinUsb_WritePipe(IntPtr InterfaceHandle, byte PipeID, byte* pBuffer, uint BufferLength, out uint LengthTransferred, IntPtr Overlapped);
[DllImport("winusb.dll", SetLastError = true)]
private static unsafe extern bool WinUsb_WritePipe(IntPtr InterfaceHandle, byte PipeID, byte* pBuffer, uint BufferLength, out uint LengthTransferred, NativeOverlapped* pOverlapped);
[DllImport("kernel32.dll", SetLastError = true)]
private static unsafe extern bool CancelIo(IntPtr hFile);
[DllImport("kernel32.dll", SetLastError = true)]
private static unsafe extern bool CancelIoEx(IntPtr hFile, NativeOverlapped* pOverlapped);
[DllImport("winusb.dll", SetLastError = true)]
private static unsafe extern bool WinUsb_ResetPipe(IntPtr InterfaceHandle, byte PipeID);
[DllImport("winusb.dll", SetLastError = true)]
private static extern bool WinUsb_FlushPipe(IntPtr InterfaceHandle, byte PipeID);
[DllImport("winusb.dll", SetLastError = true)]
private static extern bool WinUsb_GetDescriptor(IntPtr InterfaceHandle, byte DescriptorType,
byte Index, UInt16 LanguageID, byte[] Buffer, UInt32 BufferLength, out UInt32 LengthTransfered);
@@ -194,12 +194,12 @@ namespace MadWizard.WinUSBNet.API
[DllImport("winusb.dll", SetLastError = true)]
private static extern bool WinUsb_GetAssociatedInterface(IntPtr InterfaceHandle, byte AssociatedInterfaceIndex,
out IntPtr AssociatedInterfaceHandle);
private const int USB_DEVICE_DESCRIPTOR_TYPE = 0x01;
private const int USB_CONFIGURATION_DESCRIPTOR_TYPE = 0x02;
private const int USB_STRING_DESCRIPTOR_TYPE = 0x03;
private const int ERROR_NO_MORE_ITEMS = 259;
}
}
}