Как вы можете работать с USB-устройствами, используя .Net (C#)?
Как вы можете обнаруживать события USB (подключения / отключения) и как вы взаимодействуете с устройствами (чтение / запись).
Есть ли для этого собственное решение .Net?





Большинство наборов микросхем USB поставляются с драйверами. Силиконовые лаборатории есть.
Таким образом, у меня есть зависимость от самого драйвера? Есть ли универсальное решение, которое будет работать на всех машинах?
У вас будет зависимость как от dll, так и от оборудования, от используемого набора микросхем. Однако это самый быстрый способ начать работу с USB-соединением, если вы контролируете как программное обеспечение, так и оборудование.
Для этого нет решения родные (например, Системные библиотеки). Это причина, по которой существует SharpUSBLib, как указано Moobaa.
Если вы хотите накатить собственный обработчик для USB-устройств, вы можете проверить SerialPort класс System.IO.Ports.
Как можно использовать USB-порт через класс SerialPort?
Что ж, еще в '08 USB 1.0 не использовала технологию последовательного порта. : D Не уверен, как это сделать с USB 2.0 и USB 3.0
Я просто использую CreateFile winapi для доступа к usb :)
Существует общий набор инструментов WinDriver для написания USB-драйверов в пользовательском режиме, который также поддерживает # .NET.
Я пробовал использовать SharpUSBLib, и он испортил мой компьютер (требовалось восстановление системы). Это случилось с коллегой по тому же проекту.
Я нашел альтернативу в LibUSBDotNet: http://sourceforge.net/projects/libusbdotnet Еще не очень им пользовался, но кажется неплохим и недавно обновленным (в отличие от Sharp).
Обновлено: По состоянию на середину февраля 2017 года LibUSBDotNet была обновлена около 2 недель назад. Между тем SharpUSBLib не обновлялся с 2004 года.
Здесь есть руководство по использованию библиотеки SharpUSBLib и драйверов HID для работы с C#:
http://www.developerfusion.com/article/84338/making-usb-c-friendly/
У меня есть интерфейс к Крошечный, работающий довольно хорошо, используя Эта статья
Я бы порекомендовал LibUSBDotNet, библиотеку, которую я использую 2 года. Если вам нужно работать с USB-устройством (отправлять запросы, обрабатывать ответы), эта библиотека была лучшим решением, которое я мог найти.
Плюсы:
Минусы:
Не могу заставить библиотеку работать.
Я использовал следующий код, чтобы определить, когда USB-устройства были подключены и отключены от моего компьютера:
class USBControl : IDisposable
{
// used for monitoring plugging and unplugging of USB devices.
private ManagementEventWatcher watcherAttach;
private ManagementEventWatcher watcherRemove;
public USBControl()
{
// Add USB plugged event watching
watcherAttach = new ManagementEventWatcher();
//var queryAttach = new WqlEventQuery("SELECT * FROM Win32_DeviceChangeEvent WHERE EventType = 2");
watcherAttach.EventArrived += new EventArrivedEventHandler(watcher_EventArrived);
watcherAttach.Query = new WqlEventQuery("SELECT * FROM Win32_DeviceChangeEvent WHERE EventType = 2");
watcherAttach.Start();
// Add USB unplugged event watching
watcherRemove = new ManagementEventWatcher();
//var queryRemove = new WqlEventQuery("SELECT * FROM Win32_DeviceChangeEvent WHERE EventType = 3");
watcherRemove.EventArrived += new EventArrivedEventHandler(watcher_EventRemoved);
watcherRemove.Query = new WqlEventQuery("SELECT * FROM Win32_DeviceChangeEvent WHERE EventType = 3");
watcherRemove.Start();
}
/// <summary>
/// Used to dispose of the USB device watchers when the USBControl class is disposed of.
/// </summary>
public void Dispose()
{
watcherAttach.Stop();
watcherRemove.Stop();
//Thread.Sleep(1000);
watcherAttach.Dispose();
watcherRemove.Dispose();
//Thread.Sleep(1000);
}
void watcher_EventArrived(object sender, EventArrivedEventArgs e)
{
Debug.WriteLine("watcher_EventArrived");
}
void watcher_EventRemoved(object sender, EventArrivedEventArgs e)
{
Debug.WriteLine("watcher_EventRemoved");
}
~USBControl()
{
this.Dispose();
}
}
Вы должны убедиться, что вызываете метод Dispose () при закрытии приложения. В противном случае вы получите ошибку COM-объекта во время выполнения при закрытии.
Если на вашем ПК установлено программное обеспечение Национальные инструменты, вы можете создать драйвер USB, используя его "Мастер драйверов NI-VISA".
Шаги по созданию драйвера USB: http://www.ni.com/tutorial/4478/en/
После создания драйвера вы сможете записывать и читать байты на любое USB-устройство.
Убедитесь, что драйвер виден окнами в диспетчере устройств:

Код C#:
using NationalInstruments.VisaNS;
#region UsbRaw
/// <summary>
/// Class to communicate with USB Devices using the UsbRaw Class of National Instruments
/// </summary>
public class UsbRaw
{
private NationalInstruments.VisaNS.UsbRaw usbRaw;
private List<byte> DataReceived = new List<byte>();
/// <summary>
/// Initialize the USB Device to interact with
/// </summary>
/// <param name = "ResourseName">In this format: "USB0::0x1448::0x8CA0::NI-VISA-30004::RAW". Use the NI-VISA Driver Wizard from Start»All Programs»National Instruments»VISA»Driver Wizard to create the USB Driver for the device you need to talk to.</param>
public UsbRaw(string ResourseName)
{
usbRaw = new NationalInstruments.VisaNS.UsbRaw(ResourseName, AccessModes.NoLock, 10000, false);
usbRaw.UsbInterrupt += new UsbRawInterruptEventHandler(OnUSBInterrupt);
usbRaw.EnableEvent(UsbRawEventType.UsbInterrupt, EventMechanism.Handler);
}
/// <summary>
/// Clears a USB Device from any previous commands
/// </summary>
public void Clear()
{
usbRaw.Clear();
}
/// <summary>
/// Writes Bytes to the USB Device
/// </summary>
/// <param name = "EndPoint">USB Bulk Out Pipe attribute to send the data to. For example: If you see on the Bus Hound sniffer tool that data is coming out from something like 28.4 (Device column), this means that the USB is using Endpoint 4 (Number after the dot)</param>
/// <param name = "BytesToSend">Data to send to the USB device</param>
public void Write(short EndPoint, byte[] BytesToSend)
{
usbRaw.BulkOutPipe = EndPoint;
usbRaw.Write(BytesToSend); // Write to USB
}
/// <summary>
/// Reads bytes from a USB Device
/// </summary>
/// <returns>Bytes Read</returns>
public byte[] Read()
{
usbRaw.ReadByteArray(); // This fires the UsbRawInterruptEventHandler
byte[] rxBytes = DataReceived.ToArray(); // Collects the data received
return rxBytes;
}
/// <summary>
/// This is used to get the data received by the USB device
/// </summary>
/// <param name = "sender"></param>
/// <param name = "e"></param>
private void OnUSBInterrupt(object sender, UsbRawInterruptEventArgs e)
{
try
{
DataReceived.Clear(); // Clear previous data received
DataReceived.AddRange(e.DataBuffer);
}
catch (Exception exp)
{
string errorMsg = "Error: " + exp.Message;
DataReceived.AddRange(ASCIIEncoding.ASCII.GetBytes(errorMsg));
}
}
/// <summary>
/// Use this function to clean up the UsbRaw class
/// </summary>
public void Dispose()
{
usbRaw.DisableEvent(UsbRawEventType.UsbInterrupt, EventMechanism.Handler);
if (usbRaw != null)
{
usbRaw.Dispose();
}
}
}
#endregion UsbRaw
Использование:
UsbRaw usbRaw = new UsbRaw("USB0::0x1448::0x8CA0::NI-VISA-30004::RAW");
byte[] sendData = new byte[] { 0x53, 0x4c, 0x56 };
usbRaw.Write(4, sendData); // Write bytes to the USB Device
byte[] readData = usbRaw.Read(); // Read bytes from the USB Device
usbRaw.Dispose();
Надеюсь, это кому-то поможет.
Я безуспешно пробовал несколько из этих предложений. В итоге я написал рабочее решение с использованием Java и библиотеки hid4java. В качестве консольного приложения я могу выполнять оболочку из C# с помощью Process.Start(), передавая параметры, а также читая ответы. Это обеспечивает базовый ввод-вывод HID, но без событий подключения / отключения. Для этого мне нужно было бы переписать его, чтобы он работал как демон / служба и использовал именованные каналы или какой-либо другой транспортный сервер / клиент. На данный момент этого достаточно для выполнения работы, поскольку библиотека hi4java «просто работает».
USB-устройства обычно делятся на две категории: скрытые и USB. Устройство USB может быть или не быть устройством Hid, и наоборот. С Hid обычно немного проще работать, чем с прямым USB. На разных платформах разные API для работы как с USB, так и с Hid.
Вот документация для UWP:
Спрятал: https://docs.microsoft.com/en-us/uwp/api/windows.devices.humaninterfacedevice
Вот документация для Android: https://developer.xamarin.com/api/namespace/Android.Hardware.Usb/
Вот два класса для работы с USB / Hid на уровне необработанного Windows API:
https://github.com/MelbourneDeveloper/Device.Net/blob/master/src/Hid.Net/Windows/HidAPICalls.cs
public static class HidAPICalls
{
#region Constants
private const int DigcfDeviceinterface = 16;
private const int DigcfPresent = 2;
private const uint FileShareRead = 1;
private const uint FileShareWrite = 2;
private const uint GenericRead = 2147483648;
private const uint GenericWrite = 1073741824;
private const uint OpenExisting = 3;
private const int HIDP_STATUS_SUCCESS = 0x110000;
private const int HIDP_STATUS_INVALID_PREPARSED_DATA = -0x3FEF0000;
#endregion
#region API Calls
[DllImport("hid.dll", SetLastError = true)]
private static extern bool HidD_GetPreparsedData(SafeFileHandle hidDeviceObject, out IntPtr pointerToPreparsedData);
[DllImport("hid.dll", SetLastError = true, CallingConvention = CallingConvention.StdCall)]
private static extern bool HidD_GetManufacturerString(SafeFileHandle hidDeviceObject, IntPtr pointerToBuffer, uint bufferLength);
[DllImport("hid.dll", SetLastError = true, CallingConvention = CallingConvention.StdCall)]
private static extern bool HidD_GetProductString(SafeFileHandle hidDeviceObject, IntPtr pointerToBuffer, uint bufferLength);
[DllImport("hid.dll", SetLastError = true, CallingConvention = CallingConvention.StdCall)]
private static extern bool HidD_GetSerialNumberString(SafeFileHandle hidDeviceObject, IntPtr pointerToBuffer, uint bufferLength);
[DllImport("hid.dll", SetLastError = true)]
private static extern int HidP_GetCaps(IntPtr pointerToPreparsedData, out HidCollectionCapabilities hidCollectionCapabilities);
[DllImport("hid.dll", SetLastError = true)]
private static extern bool HidD_GetAttributes(SafeFileHandle hidDeviceObject, out HidAttributes attributes);
[DllImport("hid.dll", SetLastError = true)]
private static extern bool HidD_FreePreparsedData(ref IntPtr pointerToPreparsedData);
[DllImport("hid.dll", SetLastError = true)]
private static extern void HidD_GetHidGuid(ref Guid hidGuid);
private delegate bool GetString(SafeFileHandle hidDeviceObject, IntPtr pointerToBuffer, uint bufferLength);
#endregion
#region Helper Methods
#region Public Methods
public static HidAttributes GetHidAttributes(SafeFileHandle safeFileHandle)
{
var isSuccess = HidD_GetAttributes(safeFileHandle, out var hidAttributes);
WindowsDeviceBase.HandleError(isSuccess, "Could not get Hid Attributes");
return hidAttributes;
}
public static HidCollectionCapabilities GetHidCapabilities(SafeFileHandle readSafeFileHandle)
{
var isSuccess = HidD_GetPreparsedData(readSafeFileHandle, out var pointerToPreParsedData);
WindowsDeviceBase.HandleError(isSuccess, "Could not get pre parsed data");
var result = HidP_GetCaps(pointerToPreParsedData, out var hidCollectionCapabilities);
if (result != HIDP_STATUS_SUCCESS)
{
throw new Exception($"Could not get Hid capabilities. Return code: {result}");
}
isSuccess = HidD_FreePreparsedData(ref pointerToPreParsedData);
WindowsDeviceBase.HandleError(isSuccess, "Could not release handle for getting Hid capabilities");
return hidCollectionCapabilities;
}
public static string GetManufacturer(SafeFileHandle safeFileHandle)
{
return GetHidString(safeFileHandle, HidD_GetManufacturerString);
}
public static string GetProduct(SafeFileHandle safeFileHandle)
{
return GetHidString(safeFileHandle, HidD_GetProductString);
}
public static string GetSerialNumber(SafeFileHandle safeFileHandle)
{
return GetHidString(safeFileHandle, HidD_GetSerialNumberString);
}
#endregion
#region Private Static Methods
private static string GetHidString(SafeFileHandle safeFileHandle, GetString getString)
{
var pointerToBuffer = Marshal.AllocHGlobal(126);
var isSuccess = getString(safeFileHandle, pointerToBuffer, 126);
Marshal.FreeHGlobal(pointerToBuffer);
WindowsDeviceBase.HandleError(isSuccess, "Could not get Hid string");
return Marshal.PtrToStringUni(pointerToBuffer);
}
#endregion
#endregion
}
https://github.com/MelbourneDeveloper/Device.Net/blob/master/src/Usb.Net/Windows/WinUsbApiCalls.cs
public static partial class WinUsbApiCalls
{
#region Constants
public const int EnglishLanguageID = 1033;
public const uint DEVICE_SPEED = 1;
public const byte USB_ENDPOINT_DIRECTION_MASK = 0X80;
public const int WritePipeId = 0x80;
/// <summary>
/// Not sure where this constant is defined...
/// </summary>
public const int DEFAULT_DESCRIPTOR_TYPE = 0x01;
public const int USB_STRING_DESCRIPTOR_TYPE = 0x03;
#endregion
#region API Calls
[DllImport("winusb.dll", SetLastError = true)]
public static extern bool WinUsb_ControlTransfer(IntPtr InterfaceHandle, WINUSB_SETUP_PACKET SetupPacket, byte[] Buffer, uint BufferLength, ref uint LengthTransferred, IntPtr Overlapped);
[DllImport("winusb.dll", SetLastError = true, CharSet = CharSet.Auto)]
public static extern bool WinUsb_GetAssociatedInterface(SafeFileHandle InterfaceHandle, byte AssociatedInterfaceIndex, out SafeFileHandle AssociatedInterfaceHandle);
[DllImport("winusb.dll", SetLastError = true)]
public static extern bool WinUsb_GetDescriptor(SafeFileHandle InterfaceHandle, byte DescriptorType, byte Index, ushort LanguageID, out USB_DEVICE_DESCRIPTOR deviceDesc, uint BufferLength, out uint LengthTransfered);
[DllImport("winusb.dll", SetLastError = true)]
public static extern bool WinUsb_GetDescriptor(SafeFileHandle InterfaceHandle, byte DescriptorType, byte Index, UInt16 LanguageID, byte[] Buffer, UInt32 BufferLength, out UInt32 LengthTransfered);
[DllImport("winusb.dll", SetLastError = true)]
public static extern bool WinUsb_Free(SafeFileHandle InterfaceHandle);
[DllImport("winusb.dll", SetLastError = true)]
public static extern bool WinUsb_Initialize(SafeFileHandle DeviceHandle, out SafeFileHandle InterfaceHandle);
[DllImport("winusb.dll", SetLastError = true)]
public static extern bool WinUsb_QueryDeviceInformation(IntPtr InterfaceHandle, uint InformationType, ref uint BufferLength, ref byte Buffer);
[DllImport("winusb.dll", SetLastError = true)]
public static extern bool WinUsb_QueryInterfaceSettings(SafeFileHandle InterfaceHandle, byte AlternateInterfaceNumber, out USB_INTERFACE_DESCRIPTOR UsbAltInterfaceDescriptor);
[DllImport("winusb.dll", SetLastError = true)]
public static extern bool WinUsb_QueryPipe(SafeFileHandle InterfaceHandle, byte AlternateInterfaceNumber, byte PipeIndex, out WINUSB_PIPE_INFORMATION PipeInformation);
[DllImport("winusb.dll", SetLastError = true)]
public static extern bool WinUsb_ReadPipe(SafeFileHandle InterfaceHandle, byte PipeID, byte[] Buffer, uint BufferLength, out uint LengthTransferred, IntPtr Overlapped);
[DllImport("winusb.dll", SetLastError = true)]
public static extern bool WinUsb_SetPipePolicy(IntPtr InterfaceHandle, byte PipeID, uint PolicyType, uint ValueLength, ref uint Value);
[DllImport("winusb.dll", SetLastError = true)]
public static extern bool WinUsb_WritePipe(SafeFileHandle InterfaceHandle, byte PipeID, byte[] Buffer, uint BufferLength, out uint LengthTransferred, IntPtr Overlapped);
#endregion
#region Public Methods
public static string GetDescriptor(SafeFileHandle defaultInterfaceHandle, byte index, string errorMessage)
{
var buffer = new byte[256];
var isSuccess = WinUsb_GetDescriptor(defaultInterfaceHandle, USB_STRING_DESCRIPTOR_TYPE, index, EnglishLanguageID, buffer, (uint)buffer.Length, out var transfered);
WindowsDeviceBase.HandleError(isSuccess, errorMessage);
var descriptor = new string(Encoding.Unicode.GetChars(buffer, 2, (int)transfered));
return descriptor.Substring(0, descriptor.Length - 1);
}
#endregion
}
С любым из этих решений вам нужно будет либо опрашивать устройство с интервалом, либо использовать один из собственных классов прослушивания устройств API. Однако эта библиотека размещает слой между Hid и USB на всех платформах, чтобы вы могли легко обнаруживать подключения и отключения: https://github.com/MelbourneDeveloper/Device.Net/wiki/Device-Listener. Вот как вы бы это использовали:
internal class TrezorExample : IDisposable
{
#region Fields
//Define the types of devices to search for. This particular device can be connected to via USB, or Hid
private readonly List<FilterDeviceDefinition> _DeviceDefinitions = new List<FilterDeviceDefinition>
{
new FilterDeviceDefinition{ DeviceType= DeviceType.Hid, VendorId= 0x534C, ProductId=0x0001, Label = "Trezor One Firmware 1.6.x", UsagePage=65280 },
new FilterDeviceDefinition{ DeviceType= DeviceType.Usb, VendorId= 0x534C, ProductId=0x0001, Label = "Trezor One Firmware 1.6.x (Android Only)" },
new FilterDeviceDefinition{ DeviceType= DeviceType.Usb, VendorId= 0x1209, ProductId=0x53C1, Label = "Trezor One Firmware 1.7.x" },
new FilterDeviceDefinition{ DeviceType= DeviceType.Usb, VendorId= 0x1209, ProductId=0x53C0, Label = "Model T" }
};
#endregion
#region Events
public event EventHandler TrezorInitialized;
public event EventHandler TrezorDisconnected;
#endregion
#region Public Properties
public IDevice TrezorDevice { get; private set; }
public DeviceListener DeviceListener { get; private set; }
#endregion
#region Event Handlers
private void DevicePoller_DeviceInitialized(object sender, DeviceEventArgs e)
{
TrezorDevice = e.Device;
TrezorInitialized?.Invoke(this, new EventArgs());
}
private void DevicePoller_DeviceDisconnected(object sender, DeviceEventArgs e)
{
TrezorDevice = null;
TrezorDisconnected?.Invoke(this, new EventArgs());
}
#endregion
#region Public Methods
public void StartListening()
{
TrezorDevice?.Dispose();
DeviceListener = new DeviceListener(_DeviceDefinitions, 3000);
DeviceListener.DeviceDisconnected += DevicePoller_DeviceDisconnected;
DeviceListener.DeviceInitialized += DevicePoller_DeviceInitialized;
}
public async Task InitializeTrezorAsync()
{
//Get the first available device and connect to it
var devices = await DeviceManager.Current.GetDevices(_DeviceDefinitions);
TrezorDevice = devices.FirstOrDefault();
await TrezorDevice.InitializeAsync();
}
public async Task<byte[]> WriteAndReadFromDeviceAsync()
{
//Create a buffer with 3 bytes (initialize)
var writeBuffer = new byte[64];
writeBuffer[0] = 0x3f;
writeBuffer[1] = 0x23;
writeBuffer[2] = 0x23;
//Write the data to the device
return await TrezorDevice.WriteAndReadAsync(writeBuffer);
}
public void Dispose()
{
TrezorDevice?.Dispose();
}
#endregion
}
Больше ответов здесь: stackoverflow.com/questions/2803890/net-api-for-hid-usb