Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

USB HID hangs on Read() in C#

Tags:

c#

.net

winapi

usb

hid

I am trying to connect to a USB digital scale. The code does connect to the scale as scale.IsConnected comes true, but it hangs on scale.Read(250) where 250 should be the timeout in milliseconds, but it never return from Read.

I am using the code from this thread except one change which was due to the new version of Mike O Brien's HID Library:

public HidDevice[] GetDevices ()
{
    HidDevice[] hidDeviceList;
            
    // Metler Toledo
    hidDeviceList = HidDevices.Enumerate(0x0eb8).ToArray();
    if (hidDeviceList.Length > 0)
        return hidDeviceList;
    
    return hidDeviceList;
}

I managed to get the scale working, take a look at Mike's answer here

like image 249
PUG Avatar asked Apr 16 '12 16:04

PUG


1 Answers

I managed to get the scale working. In my callback, which runs when scale returns data, I was doing Read which is a blocking call.

So a deadlock was created, and I should have only used ReadReport or Read. Take a look at Mike's example below which he posted here.

using System;
using System.Linq;
using System.Text;
using HidLibrary;

namespace MagtekCardReader
{
    class Program
    {
        private const int VendorId = 0x0801;
        private const int ProductId = 0x0002;

        private static HidDevice _device;

        static void Main()
        {
            _device = HidDevices.Enumerate(VendorId, ProductId).FirstOrDefault();

            if (_device != null)
            {
                _device.OpenDevice();

                _device.Inserted += DeviceAttachedHandler;
                _device.Removed += DeviceRemovedHandler;

                _device.MonitorDeviceEvents = true;

                _device.ReadReport(OnReport);

                Console.WriteLine("Reader found, press any key to exit.");
                Console.ReadKey();

                _device.CloseDevice();
            }
            else
            {
                Console.WriteLine("Could not find reader.");
                Console.ReadKey();
            }
        }

        private static void OnReport(HidReport report)
        {
            if (!_device.IsConnected) {
                return;
            }

            var cardData = new Data(report.Data);

            Console.WriteLine(!cardData.Error ? Encoding.ASCII.GetString(cardData.CardData) : cardData.ErrorMessage);

            _device.ReadReport(OnReport);
        }

        private static void DeviceAttachedHandler()
        {
            Console.WriteLine("Device attached.");
            _device.ReadReport(OnReport);
        }

        private static void DeviceRemovedHandler()
        {
            Console.WriteLine("Device removed.");
        }
    }
}
like image 178
PUG Avatar answered Oct 27 '22 07:10

PUG