USB HID freezes on Read () in C #

I am trying to connect to a digital USB scale. The code connects to the scale because scale.IsConnected is executing, but hangs on scale.Read(250) , where 250 should be a timeout in milliseconds, but it never returns from Read

I use the code from this thread, with the exception of one change that was associated with the new version of the Mike O Brien 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 of the work, take a look at Mike, answer here

+6
source share
2 answers

I managed to get the scale of work. In my callback, which is executed when the scale returns data, I did Read , which is a blocking call. Thus, a dead end was created, should only use ReadReport or Read to 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."); } } } 
+4
source

I cannot help you with your problem, but some time ago I had to integrate the foot switch into the application, and I found this USB HID C # library that worked fine:

http://www.codeproject.com/Articles/18099/A-USB-HID-Component-for-C

Perhaps you should try, because it is very easy to integrate.

David

+2
source

Source: https://habr.com/ru/post/913339/


All Articles