问题
I am using Mike O Brien's HID Library to connect to digital scale,
Device opens successfully then displays device attached & removed messages perfectly. But only runs OnReport for about 20 times initially
After Inital approx 20 runs on OnReport it never runs again, unless I remove usb cable and re-connect.
My code is below
if (scale.IsConnected)
{
scale.Inserted += DeviceAttachedHandler;
scale.Removed += DeviceRemovedHandler;
scale.MonitorDeviceEvents = true;
scale.ReadReport(OnReport);
MessageBox.Show("Hold Application Here");
Event Handlers for the scale
private void DeviceAttachedHandler()
{
MessageBox.Show("Device attached.");
scale.ReadReport(OnReport);
}
private static void DeviceRemovedHandler()
{
MessageBox.Show("Device removed.");
}
private void OnReport(HidReport report)
{
if (!scale.IsConnected) { return; }
//var cardData = new Data(report.Data);
decimal weight = Convert.ToDecimal(report.Data[4]);// (Convert.ToDecimal(report.Data[4]) +
MessageBox.Show(weight.ToString());
//Convert.ToDecimal(report.Data[5]) * 256) / 100;
//Console.WriteLine(!cardData.Error ? Encoding.ASCII.GetString(cardData.CardData) : cardData.ErrorMessage);
//Console.WriteLine(report.Data);
scale.ReadReport(OnReport);
}
回答1:
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, 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.");
}
}
}
来源:https://stackoverflow.com/questions/10130837/connecting-to-digital-scalemetler-toledo-ps90-as-hid-runs-onreport-only-when-c