Trabajar con dispositivos USB in.NET


Usando. Net (C#), ¿cómo se puede trabajar con dispositivos USB?

Cómo puede detectar eventos USB (conexiones/desconexiones) y cómo se comunica con los dispositivos (lectura/escritura).

¿Existe una solución nativa. Net para hacer esto?

Author: David Thibault, 2008-09-16

11 answers

No existe una solución nativa (por ejemplo, bibliotecas del sistema) para esto. Esa es la razón por la que SharpUSBLib existe como se menciona en moobaa.

Si desea lanzar su propio controlador para dispositivos USB, puede consultar la clase SerialPort de System.IO. Ports .

 21
Author: Jon Limjap,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:10:38

He intentado usar SharpUSBLib y arruinó mi computadora (necesitaba una restauración del sistema). Le pasó a un compañero de trabajo en el mismo proyecto también.

He encontrado una alternativa en LibUSBDotNet: http://sourceforge.net/projects/libusbdotnet No lo he usado mucho todavía, pero parece bueno y recientemente actualizado (a diferencia de Sharp).

EDITAR: A mediados de febrero de 2017, LibUSBDotNet se actualizó hace aproximadamente 2 semanas. Mientras tanto, SharpUSBLib no se ha actualizado desde 2004.

 24
Author: Sofox,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-02-14 14:06:49
 11
Author: moobaa,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-09-16 02:06:31

Utilicé el siguiente código para detectar cuándo se conectaron y desenchufaron dispositivos USB de mi computadora:

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();
        }


    }

Debe asegurarse de llamar al método Dispose() al cerrar su solicitud. De lo contrario, recibirá un error de objeto COM en tiempo de ejecución al cerrar.

 11
Author: Syn,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-12-11 22:33:46

Recomendaría LibUSBDotNet, la biblioteca que he estado usando durante 2 años. Si tienes que trabajar con un dispositivo USB (enviar solicitudes, procesar respuestas), esta biblioteca fue la mejor solución que pude encontrar.

Ventajas:

  • Tiene todos los métodos que necesita para trabajar en modo synch o asynch.
  • Código fuente proporcionado
  • Suficientes muestras para comenzar a usarlo de inmediato.

Contras:

  • Mala documentación (es un problema común para proyectos de código abierto). Básicamente, puede encontrar una descripción común de los métodos en el archivo de ayuda de CHM y eso es todo. Pero todavía encuentro muestras proporcionadas y el código fuente es suficiente para codificar. Solo que a veces veo un comportamiento extraño y quiero saber por qué se implementó de esta manera y ni siquiera puedo obtener una pista...
  • ya no parece soportado. La última versión se publicó en octubre de 2010. Y a veces es difícil obtener respuestas.
 4
Author: Alex Klaus,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-10-02 00:25:13

Hay un tutorial sobre cómo hacer que la biblioteca SharpUSBLib y los controladores HID funcionen con C# aquí:

Http://www.developerfusion.com/article/84338/making-usb-c-friendly /

 2
Author: James Crowley,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-03-08 16:35:47

Hay un kit de herramientas genérico WinDriver para escribir controladores USB en modo usuario que también admiten#. NET

 1
Author: Ilya,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-09-16 08:31:25

Si tiene el software National Instruments en su PC, puede crear un controlador USB utilizando su "NI-VISA Driver Wizard".

Pasos para crear el Controlador USB: http://www.ni.com/tutorial/4478/en/

Una vez que haya creado el controlador, podrá Escribir y Leer bytes en cualquier dispositivo USB.

Asegúrese de que el controlador sea visto por Windows en el Administrador de dispositivos:

introduzca la descripción de la imagen aquí

Código 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

Uso:

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();

Espero que esto ayuda a alguien.

 1
Author: Pabinator,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-02-27 22:50:04

La mayoría de los chipsets USB vienen con controladores. Silicon Labs tiene uno.

 0
Author: Nick,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-09-16 02:11:02

He conseguido que una interfaz para un Teensy funcione bastante bien, usando este artículo

 0
Author: Brad Bruce,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-08-19 15:45:29

Probé varias de estas sugerencias sin suerte. Terminé escribiendo una solución de trabajo usando Java y la biblioteca hid4java . Como una aplicación de consola, puedo descargarla desde C # usando Process.Start(), pasando parámetros y leyendo respuestas. Esto proporciona E/S HID básicas pero sin eventos de conexión/desconexión. Para eso tendría que reescribirlo para que se ejecute como un demonio/servicio y usar tuberías con nombre o algún otro transporte de servidor/cliente. Por ahora, es suficiente para hacer el trabajo desde el hi4java biblioteca "solo funciona".

 0
Author: Mike Lowery,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-06-19 20:56:36