Quantcast
Channel: Zer's Programming Page
Viewing all 119 articles
Browse latest View live

HIDSharp ASync Stream Reading

$
0
0

First of all, thank you for making this amazing library, and for putting it out there. Looks extremely professional and well designed!

I'm new to HID communication, but not to programming and hardware communication (done quite a bit of Serial Port and MIDI stuff in .NET)

I'm trying to figure out the "proper" way to do communication with my HID device. What I have made through trial-and-error works, but I'm sure it's not "correct".

Here's a sample of my code:

        HidSharp.HidDevice USBDevice;
        HidSharp.DeviceList USBList;
        HidSharp.HidStream USBStream;
        IAsyncResult result;


        byte[] testUSBHeader = new byte[] { 01, 14, 0x0a, 0, 0x0b, 0, 0x32, 0, 2, 0, 1, 0, 0x10, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
        byte[] USBBuffer;

        private void btnConnect_Click(object sender, EventArgs e)
        {
            USBList = DeviceList.Local;
            USBDevice = USBList.GetHidDevices(0x0483,0xA0E0).First();
            if (USBDevice != null && USBDevice.TryOpen(out USBStream))
            {
                USBStream.ReadTimeout = 32767;
                textBox1.Text = USBDevice.DevicePath;
                btnConnect.Text = "Connected!";
                USBBuffer = new byte[65];
                result = USBStream.BeginRead(USBBuffer, 0, 64, new AsyncCallback(BytesReady), null);
            }
        }

        private void btnSend_Click(object sender, EventArgs e)
        {
            byte[] BytesToSend = new byte[65];
            Array.Copy(testUSBHeader, 0, BytesToSend, 1, testUSBHeader.Length);
            BytesToSend[0] = 0;
            USBStream.Write(BytesToSend, 0, 65);
        }

        private void BytesReady(IAsyncResult result)
        {
            try
            {
                Debug.WriteLine($"Bytes Read = {USBStream.EndRead(result)}");

                if (listBox1.InvokeRequired)
                    listBox1.BeginInvoke((MethodInvoker)delegate () { listBox1.Items.Add(BitConverter.ToString(USBBuffer)); ; });
                else
                    listBox1.Items.Add(BitConverter.ToString(USBBuffer));

                result = USBStream.BeginRead(USBBuffer, 0, 64, new AsyncCallback(BytesReady), null);

            }
            catch (Exception)
            {

                 }
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            USBStream.EndRead(result);
            USBStream.Dispose();
        }
    }

Some things I don't quite understand:
Why do I need to call BeginRead inside BytesReady? It seems if I don't, no more reads happen. I thought BeginRead would continue until Cancelled. I've tried it with and without EndRead, it only ever reads more than once unless I call it again.

How do I close the stream and stop reading? When I call USBStream.Close() or USBStream.Dispose(), it calls BytesReady continuously. The only way I can get it to stop is with the try/catch on EndRead, so it doesn't call BeginRead again.

What is a better way to do what I'm trying to do?

Thank you for your help and advice!


Beta not building in VS2015

$
0
0

I was able to import and change my project to use the alpha HIDSharp. Still, Win10 is about 3 times slower than Win 7. Any hints would be greatly appreciated.

Thanks!

20th January 2016.

$
0
0

After the server crashed few days ago, stat reset dosnt work anymore. Can you please fix that?
Also, Mr spy broke the spell Mind blast few years ago by accident, any way to fix that by any chance?

Cheers.

HidSharp issue - debian/windows

$
0
0

Hi,

thanks for a great platform. I have a C# program which I want to use on a windows and linux platform.
It get data from a HID-device by sending a series of bytes and then receiving data back.
It works great on windows 10, but I am having some issues on linux.
Below you see the communication. I send 6 bytes (00-00-00-00-01-58) (hex values) and get data back ... but only on windows, not on linux.
I have set up the permission in the .rules and I have managed to get some communication with the HID, so I am pretty sure it is not a permission issue.

I am using the latest version hidsharp,  2.0.1 from nuget.

Any ideas?

thanks,


Christian

--- executed on win10 pc ---
28/04/2018 15.54.36 - Device found: HidSharp.Platform.Windows.WinHidDevice
28/04/2018 15.54.41 - 00-00-00-00-01-58
28/04/2018 15.54.41 - 00-41-42-43-3C-04-02-31-48-7C-5C-5E-26-7C-7C-75-4E-46-4A-37-52-7C-42-61-79-65-72-36-32-31-30-5E-30-31-2E-31-32-5C-30-31-2E-30-34-5C-32-35-2E-32-35-5C-30-31-2E-30-30-2E-41-5E-36-32-31-33-2D-31-30
28/04/2018 15.54.41 - 00-41-42-43-3C-30-31-36-38-37-5E-30-30-30-30-2D-5E-42-47-31-30-30-31-36-38-37-42-7C-41-3D-30-5E-43-3D-32-32-5E-47-3D-64-61-2C-65-6E-5C-61-72-5C-7A-68-5C-68-72-5C-63-73-5C-64-61-5C-6E-6C-5C-66-69
.......

--- executed on raspberry pi zero with debian (stretch) on mono (all updated) ---
28/04/2018 15:53:09 - Device found: HidSharp.Platform.Linux.LinuxHidDevice
28/04/2018 15:53:14 - 00-00-00-00-01-58
28/04/2018 15:53:24 - Error: timeout

HidSharp not able to read the device data

$
0
0

Hi, I have a 2D scanner. The device is can be identified correctly, but by some reasons not able to get barcode value from the scanner. I will appreciate it very much if you could give some clues ...
I use HIDSharp20.
In the system it is identified as "HID Keyboard Device".
I use usb scanner YHD-M200

It uses device: "Honeywell Imaging & Mobility     HID POS C0A7AE (VID 3118, PID 2441, version 0.0)".

Output:

   (VID 5102, PID 3, version 0.0)
Dell Dell USB Keyboard ? (VID 16700, PID 8195, version 3.1)
Honeywell Imaging & Mobility     HID POS C0A7AE (VID 3118, PID 2441, version 0.0)
Honeywell Imaging & Mobility     HID Keyboard Emulation C0A7AE (VID 3118, PID 2441, version 0.0)
Honeywell Imaging & Mobility     REM C0A7AE (VID 3118, PID 2441, version 0.0)

Opening HID class device...
HID POS
Max Lengths:
  Input:   64
  Output:  64
  Feature: 2

The operating system name for this device is:
  \\?\hid#vid_0c2e&pid_0989&mi_01#7&24fa9ba&0&0000#{4d1e55b2-f16f-11cf-88cb-001111000030}

Read timed out.
Read timed out.
Read timed out.
Read timed out.
Read timed out.
Read timed out.
Read timed out.

----------------------------------------------------------

using System;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;

namespace HidSharp.Test
{
    class Program
    {
        static void Main(string[] args)
        {
            HidDeviceLoader loader = new HidDeviceLoader();
            Thread.Sleep(2000); // Give a bit of time so our timing below is more valid as a benchmark.

            var stopwatch = new Stopwatch();
            stopwatch.Start();
            var deviceList = loader.GetDevices().ToArray();
            stopwatch.Stop();
            long deviceListTotalTime = stopwatch.ElapsedMilliseconds;

            Console.WriteLine("Complete device list (took {0} ms to get {1} devices):",
                              deviceListTotalTime, deviceList.Length);
            foreach (HidDevice dev in deviceList)
            {
                Console.WriteLine(dev);
            }
            Console.WriteLine();

            Console.WriteLine("Opening HID class device...");


            var dtest_evice = loader.GetDevices(3118);
            var device = loader.GetDevices(3118).FirstOrDefault(d => d.ProductName == "HID POS");
            if (device == null) { Console.WriteLine("Failed to open device."); Environment.Exit(1); }
            Console.Write(device.ProductName);
            Console.Write(@"
Max Lengths:
  Input:   {0}
  Output:  {1}
  Feature: {2}

The operating system name for this device is:
  {3}

"
, device.MaxInputReportLength
, device.MaxOutputReportLength
, device.MaxFeatureReportLength
, device.DevicePath
);

            HidStream stream;
            if (!device.TryOpen(out stream)) { Console.WriteLine("Failed to open device."); Environment.Exit(2); }
            StringBuilder sb = new StringBuilder();
            using (stream)
            {
                int n = 0;
                while (true)
                {

                    var bytes = new byte[device.MaxInputReportLength];
                    int count = 0;
                   
                    try
                    {
                        count = stream.Read(bytes, 0, bytes.Length);
                                            }
                    catch (TimeoutException)
                    {
              //          Console.Write(count);
                        Console.WriteLine("Read timed out.");
                        continue;
                    }

                    if (count > 0)
                    {
                        var decoded = Encoding.UTF8.GetString(bytes);
                        if (decoded.IndexOf("\u0002\u0003]Q1\n\r\n\0") >= 0)
                        {
                            Console.WriteLine(sb.ToString());
                            sb.Length = 0;
                        }
                        else
                        {
                            sb.Append(decoded.Replace("\u00028]Q1", "").Replace("s\0\u0001", " "));
                        }
                        Console.WriteLine();
                        if (++n == 100)
                        {
                            break;
                        }
                    }
                }
            }

            Console.WriteLine("Press a key to exit...");
            Console.ReadKey();
        }
    }
}

Please release the server files for Faldon

$
0
0

The game is virtually dead, but with the server files out, we can get active teams to develop new servers and keep the game alive.

Program hanging the second time

$
0
0

The plugin works great but the second time it hangs.
Do I need to close the device? Is there a way to close the connection?

Thanks!!

Here is the code:

DeviceList list = DeviceList.Local;

        hidDevice = list.GetHidDeviceOrNull(VendorId, ProductId);
        if(hidDevice != null)
        {
            Debug.Log(hidDevice.GetFriendlyName());
            DeviceStream deviceStream;
            if (hidDevice.TryOpen(out deviceStream))
            {
                deviceStream.WriteTimeout = 1000;
                deviceStream.Write(mStartData, 0, mStartData.Length);
                deviceStream.Close();
            }
        }

On Mac Device list count is 0

$
0
0

Hi, I am using the latest code on MAC but I cannot find any device even tho there are USB devices connected.

Here is the code:

DeviceList list = DeviceList.Local;

Debug.Log(list.GetAllDevices().Count());

Is there anything else I need to do on MAC?


Project Signing (Strong Name)

$
0
0

I'm trying to use HidSharp 2.0.2 from NuGet but I'm getting error "Referenced assembly 'HidSharp' does not have a strong name".
My project is using Signing and I guess that all referenced projects must be signed too.
Is there a reason for HidSharp not be signed?
I'm using many projects from NuGet and they all have a Strong Name...

HidSharp doesn't work with Linux+dotnet

$
0
0

HidSharp currently has hard Mono dependency in NativeMethods.uname which lead to LinuxHidManaged.IsSupported => false all time

About HIDSharp V2.0.2 work on Mac system

$
0
0

Sir,
    When I use this library to connect with one HID device, normally working is good on windows and Mac(use .dotnet development environment),but sometimes the console message popup abnormal info and function is shutdown, such as below:
    Could you give me some advice on how to fix this issue? Thank a lot!

FailFast:
A callback was made on a garbage collected delegate of type 'HidSharp!HidSharp.Platform.MacOS.NativeMethods+IOHIDDeviceCallback::Invoke'.

   at HidSharp.Platform.MacOS.NativeMethods.CFRunLoopRun()
   at HidSharp.Platform.MacOS.NativeMethods.CFRunLoopRun()
   at HidSharp.Platform.MacOS.MacHidManager.Run(System.Action)
   at System.Threading.Thread.ThreadMain_ParameterizedThreadStart(System.Object)
   at System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object)
[1]    28889 abort      ./KYC_API
➜  usbClient
➜  usbClient

Controller not found on Mac

$
0
0

Hi,
I have an Xbox controller connected to my Mac (using a USB cable).  I have the appropriate driver installed.  The driver includes a System Preferences tool to test/verify the device is working, and I get feedback in that app when I use the controller.  Also, in the "About this Mac" / "System Report"; under Hardware / USB, I see (under the USB 3.0 Bus category) the Microsoft controller with the Product Id and Vendor Id listed.

But, when I run the HidSharp.Test code, it only lists the Apple Keyboard & Mouse stuff - not the game controller as expected. 

When I log "DeviceList.Local.ToString()" I see:  Mac OS HID

Any advise or controller suggestions (even if it means buying a different one) would be greatly appreciated.

Thanks in advance!

About HIDSharp V2.0.5 work on Mac system

$
0
0

Sir,
    We design one type HID device using at WIN and Mac system both;   I have No.1 and No.2 HID device with different serial number,  at windows platform when we plug and unplug HID, the operation system internal can be refreshed in time, so I can always get right serial number. But mac system is something difference, when I replace No1 with No2 Hid Device, the operation system already refresh device list, but HIDsharp related api can not get the latest one even I add list.changed.
Could you give me some advice on how to fix?
   Thanks in advance

            DeviceList list = DeviceList.Local;
            list.Changed += (sender, e) => Console.Write("Device list changed.\n");   //20181217
            HidDevice[] hidDeviceList = list.GetHidDevices().ToArray();
            List<string> arraylist = new List<string>();
            arraylist.Clear(); //Clear buffer
            foreach (HidDevice onehid in hidDeviceList)
            {
                if ( onehid.VendorID == 0x0483 && onehid.ProductID == 0x5710)
                {
                    arraylist.Add(onehid.GetSerialNumber());                   
                    continue;
                }
            }
            if (arraylist.Count() == 0)
            {
                throw new Exception("not found device");
            }

            return arraylist.ToArray();

Create an event when attach/detach removable drive HidSharp Linux

$
0
0

Hi all!
I try to use nuget package HidSharp 2.0.5 for catch an event when removable drive is connected/disconnected. I'm debugging on Windows now, but my code is does not catch any hid devices connection events. I would be run this app at Linux in future via Mono. Can anyone help me please?

static void Main(string[] args)
    {
        var list = DeviceList.Local;

        Console.WriteLine("USB monitor");

        list.Changed += (sender, e) => Console.WriteLine("Device list changed.");

        var hidDeviceList = list.GetHidDevices().ToArray();

        Console.WriteLine("Complete device list {0} devices:", hidDeviceList.Length);

        foreach (var device in hidDeviceList)
        {
            Console.WriteLine(device);
        }

        Console.ReadLine();
    }

Get removable drive name in Linux

$
0
0

Hi everyone! Is it possible to get removable drive name via HidSharp in Linux when app running through the Mono?
All my removable drives automounted on /media/usb0...usb7


Device not seen with HidSharp 2.0.5 on Mac

$
0
0

I am trying to connect to a USB weather station. Previously using HidSharp 1.5 this worked fine on Windows, Linux and Mac. Now I have upgraded to HidSharp 2.0.5 (to remove the libudev 0 requirement), the device is still seen by users on Windows and Linux, but Mac users get a null return when calling GetHidDeviceOrNull() using the VID/PID.

I've added code to list all the devices found when the program starts and this fails on Macs running 2.0.5, but works on Windows and Linux

DeviceList devicelist = DeviceList.Local;
LogMessage("Finding All USB HID Devices");
var allDevices = devicelist.GetAllDevices();
foreach (HidDevice dev in allDevices)
{
    LogMessage("  " + dev.ToString());
}

On Macs this hangs after outputting "Finding All USB HID Devices"
One user has macOS 10.14.2.
Mono 5.16.0.220, 64 bit.

Any ideas? What diagnostics I can gather for you?
I don't have a Mac so I'm having to get users to run test code for me, and I cannot debug.

HIDSharp V2.0.5 work on Mac system

$
0
0

Sir,
   When I use latest HIDSharp dll(V2.0.5), we still find some garbage case happened sometimes
Below is typical log file for your information.
   Best wishes





      Executed action method KYC_API.Controllers.ValuesController.Get (KYC_API), returned result Microsoft.AspNetCore.Mvc.OkObjectResult in 1.792ms.
info: Microsoft.AspNetCore.Mvc.Infrastructure.ObjectResultExecutor[1]
      Executing ObjectResult, writing value of type 'Microsoft.AspNetCore.Mvc.JsonResult'.
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[2]
      Executed action KYC_API.Controllers.ValuesController.Get (KYC_API) in 1.995ms
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
      Request finished in 2.127ms 200 application/json; charset=utf-8
FailFast:
A callback was made on a garbage collected delegate of type 'HidSharp!HidSharp.Platform.MacOS.NativeMethods+IOHIDDeviceCallback::Invoke'.

   at HidSharp.Platform.MacOS.NativeMethods.CFRunLoopRun()
   at HidSharp.Platform.MacOS.NativeMethods.CFRunLoopRun()
   at HidSharp.Platform.MacOS.MacHidManager.Run(System.Action)
   at System.Threading.Thread.ThreadMain_ParameterizedThreadStart(System.Object)
   at System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object)
Abort trap: 6
logout
Saving session...
...copying shared history...
...saving history...truncating history files...
...completed.
Deleting expired sessions...6 completed.

Latest version (from nuget) does not always work on Linux/dotnet

$
0
0

I have a simple program that talks to an HID device
It runs fine on Windows/.NET, Linux/Mono, Windows/dotnet but not so much on Linux/dotnet

Basically it crashes when enumerating the HID devices:

AvailableDevices = DeviceList.Local.GetHidDevices(VID, PID).Select(d => new HidDeviceUI(d)).ToList();

     
Sometimes this works and returns the list of devices, but most of the times it results in the following error:

double free or corruption (out)

(this happens as both a normal user and as root user)

Please note that all OS/Framework combinations have been tested on two distinct computers.

Dotnet version on Linux: 2.2.103
Ubuntu 18.0.4.1

HidSharp RegisterClass failed

$
0
0

I'm seeing an error on one machine where it throws an InvalidOperation Exception

  at HidSharp.Platform.Windows.WinHidManager.Run(Action readyCallback)
   at HidSharp.Platform.HidManager.RunImpl(Object readyEvent)
   at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.ThreadHelper.ThreadStart(Object obj)</StackTrace><ExceptionString>System.InvalidOperationException: HidSharp RegisterClass failed.
   at HidSharp.Platform.Windows.WinHidManager.Run(Action readyCallback)
   at HidSharp.Platform.HidManager.RunImpl(Object readyEvent)
   at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.ThreadHelper.ThreadStart(Object obj)

Is there any known issues around this?

C servers not working

$
0
0

I recently purchases citizenship and it is not working.

Viewing all 119 articles
Browse latest View live