.Net (C#) を使用して、どのように USB デバイスを操作できますか?
USB イベント (接続/切断) を検出する方法と、デバイスと通信する方法 (読み取り/書き込み)。
これを行うためのネイティブ .Net ソリューションはありますか?
.Net (C#) を使用して、どのように USB デバイスを操作できますか?
USB イベント (接続/切断) を検出する方法と、デバイスと通信する方法 (読み取り/書き込み)。
これを行うためのネイティブ .Net ソリューションはありますか?
SharpUSBLibを使用してみましたが、コンピューターが台無しになりました(システムの復元が必要です)。同じプロジェクトの同僚にも起こりました。
LibUSBDotNetで別の方法を見つけました:http ://sourceforge.net/projects/libusbdotnet Havn はまだあまり使用していませんが、(Sharpとは異なり)良好で最近更新されたようです。
編集:2017年2月中旬の時点で、LibUSBDotNetは約2週間前に更新されました。一方、SharpUSBLibは2004年以降更新されていません。
このためのネイティブ(たとえば、システムライブラリ)ソリューションはありません。これが、moobaaが述べたようにSharpUSBLibが存在する理由です。
USBデバイス用に独自のハンドラーをロールしたい場合は、System.IO.PortsのSerialPortクラスをチェックアウトできます。
次のコードを使用して、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 オブジェクト エラーが発生します。
私が2年間使用しているライブラリであるLibUSBDotNetをお勧めします。USB デバイス (リクエストの送信、レスポンスの処理) を使用する必要がある場合、このライブラリは私が見つけた最良のソリューションでした。
長所:
短所:
C# で動作する SharpUSBLib ライブラリと HID ドライバーを取得するためのチュートリアルがここにあります。
http://www.developerfusion.com/article/84338/making-usb-c-friendly/
#.NET もサポートするユーザー モードで USB ドライバーを作成するための汎用ツールキットWinDriverがあります。
PC にナショナル インスツルメンツのソフトウェアがある場合は、 「NI-VISA ドライバ ウィザード」を使用して USB ドライバを作成できます。
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();
これが誰かに役立つことを願っています。
ほとんどのUSBチップセットにはドライバーが付属しています。 SiliconLabsには1つあります。
この記事を使用して、 Teensyへのインターフェイスが非常にうまく機能するようになりました。