Quantcast
Channel: James's Programming Page
Viewing all 141 articles
Browse latest View live

Unable to open HID class device (OK) exception while open on Linux

$
0
0

I have an issue on Linux. When I call Open method it throws "Unable to open HID class device (OK)". But when I check CanOpen, it is true but cannot open. I also use TryOpen method  but it didnt work. On windows side it works without any issue. I use HidSharpCore 1.2.1.1 at .net 5.0. 

Please help me to solve this issue.

private static object lo = new object();
        public byte[] WriteAndWaitResponse(byte[] data)
        {

            lock (lo)
            {
                byte[] result;
                Console.WriteLine("vid:" + vendorId + " pid:" + productId);

                if (!DeviceList.Local.TryGetHidDevice(out Dev, vendorId, productId))
                {
                    Console.WriteLine("Cannot GetHidDevice");
                    return null;
                }

                HidStream stream = null;
                if (Dev.CanOpen)
                {
                    
                    try
                    {
                        OpenConfiguration configuration = new OpenConfiguration();
                        stream = Dev.Open();
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                    }
                    if(stream == null)
                    {
                        Console.WriteLine("Try Open failed");
                    }
                }
                else
                {
                    Console.WriteLine("Cannot Open");
                }

                try
                {
                    stream.Write(data);
                    Console.WriteLine("data:" + data.Length);
                    Thread.Sleep(100);
                    result = stream.Read();
                    Console.WriteLine("result:" + result.Length);

                    return result;
                }
                catch (Exception ex)
                {

                    throw new RealDeviceException("error while writing to USB", ex);
                }
            }
        }

HidSharp Freezed In Unity Edito for mac sometimes

$
0
0

It works well in Unity2020.3.12f when I play in editor first time.
If I stop play and restart play or change some script in unity to make it recompile, it freeze unity editor forever.
And when device list changed, this freeze can be recovered and unity will run normally.

When I build into a mac application, if I call application.Quit() to exit application, it freeze to, and also can be recovered by change device list(plug some device in/out).

If not call GetDeviceList(), all about above will not happend.Also, DeviceListChanged callback will not be called.

I wanna know how to repair this issue.

HidSharp Read Timeout

$
0
0

I have been using HidSharp on a RPi and it is been running fine.
I allow up to 4 streams and poll each of the 4 devices/streams (if used and not null) every 50mS.
Up until now I have used with multiple Hid devices successfully. Mostly card reader devices (but with keyboards/mice that I ignore).
I now have a numeric keypad but every few times my app runs, it enumerates and identifies the device but no data is received until I restart the unit. The same keypad when using a text editor is working, just not on my reads in my app.
If polling, what Read Timeout would I use? The same or less than the polling rate, or set it high and do not worry?

Problems writing to Skylander RFID portal

$
0
0

For fun I wanted to to play around with the skylander rfid portal. This is an USB Hid device and the "protocol" is quite simple or so it appears from SKyDumper project (h**ps://github.com/capull0/SkyDumper). This tool SkyDumper works on my linux computer, but when I try to convert it to hidsharp it won't work.

To be more specific.
* I can detect the portal just fine and get the device.
* I can open a HidStream
* I then try to send the "restart" message. Basically report Zero and the letter R, the rest all zeros.
* As soon as this is send out the portal starts sending status messages which I receive continuously. So the message did wake up something.
* However the write errors out with an exception. On my linux laptop its and I/O exception hardcoded in the output source code of hidsharp and on windows its a timeout exception.

I'm no usb export and have little clue why this happens.

I converted portalIO.cpp to the C# code below. I must be missing something silly I think. No reason for it to work using the original cpp code and not thru HidSharp. The first write failure occurs on the call to restartportal. After that I am buried in status output from the portal but nothing else. Any further write messages give the same result

If anyone has a clue or suggestion on what to try next? That would be appreciated.

using System;
using System.Text;
using HidSharp;
using System.Linq;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using HidSharp.Reports;
using HidSharp.Reports.Input;

namespace SkyReaderLib
{
    public class PortalIO
    {
        public const int rw_buffer_size = 0x21;
        public const int TIMEOUT = 30000;
        public const int SKYLANDER_SIZE = 1024;
        public const int MAX_STR = 255;
        private HidDevice portal;
        private HidStream portalStream;

        private bool initialized = false;


        public event EventHandler<StatusChangedEventArgs> StatusEvent;


        public static IEnumerable<HidDevice> ListPortals()
        {

            IEnumerable<HidDevice> devices = DeviceList.Local.GetHidDevices()
                .Where(x => (x.VendorID == 0x12ba || x.VendorID == 0x54c || x.VendorID == 0x1430)
                    && (x.ProductID == 0x150 || x.ProductID == 0x967));

#if DEBUG
            if (devices.Any())
            {
                Console.WriteLine("Found portal usb devices:");
                foreach (HidDevice device in devices)
                {
                    Console.WriteLine($"\t{device.GetFriendlyName()}");
                }

            }
#endif
            return devices;
        }




        // Send a command to the portal
        private void Write(byte[] message)
        {

            try
            {
                byte[] buffer = new byte[portal.GetMaxOutputReportLength()];
                message.CopyTo(buffer, 0);
#if DEBUG
                Console.WriteLine("Issued report out:");
                Console.WriteLine(string.Join(" ", buffer));
#endif
                portalStream.Write(buffer);
            }
            catch (Exception e)
            {
                Console.WriteLine($"Exception while issuing a report occured: {e}");
            }
       

        }

        private bool CheckResponse(out RWBlock response, byte expect)
        {
            response = new RWBlock();
#if DEBUG
            Console.WriteLine(">>> CheckResponse\n");
#endif

            int result = portalStream.Read(response.buffer, 0, rw_buffer_size);

            if (result < 0)
                throw new Exception("Could not read response");

#if DEBUG
            Console.WriteLine("CheckResponse read = {0} bytes\n", result);
#endif

            response.dwBytesTransferred = result;

   

            // found wireless USB but portal is not connected
            if (response.buffer[0] == 'Z')
                throw new Exception("Found portal dongle, but portal not connected");

            // Status says no skylander on portal
            // if (response->buffer[0] == 'Q' && response->buffer[1] == 0)
            //     throw 11;


#if DEBUG
            Console.WriteLine("<<< CheckResponse\n");
#endif
            return (response.buffer[0] != expect);

        }

        //
        public void PortalStatus()
        {
            byte[] buffer = new byte[portal.GetMaxOutputReportLength()];

            buffer[0] = 0;
            buffer[1] = (byte)'S';
           
            Write(buffer);
        }


        // Start portal
        public void RestartPortal()
        {
            byte[] buffer = new byte[portal.GetMaxOutputReportLength()];

            buffer[0] = 0;
            buffer[1] = (byte)'R';
            Write(buffer);
                       
        }

        // Antenna up / activate
        public void ActivatePortal(int active)
        {
            byte[] buffer = new byte[portal.GetMaxOutputReportLength()];
           
            buffer[0] = 0;
            buffer[1] = (byte)'A';
            buffer[2] = (byte)active;

            Write(buffer);
        }

        // Set the portal color
        public void SetPortalColor(byte r, byte g, byte b)
        {
            byte[] buffer = new byte[portal.GetMaxOutputReportLength()];

            buffer[0] = 0;
            buffer[1] = (byte)'C';
            buffer[2] = r; // R
            buffer[3] = g; // G
            buffer[4] = b; // B

            Write(buffer);
        }

        // Release hPortalInstance
        ~PortalIO()
        {
            ActivatePortal(0);
            portalStream.Close();
        }

        public void Flash()
        {

            for (; ; )
            {
                ActivatePortal(1);
                ActivatePortal(0);
            }
        }



        public PortalIO(HidDevice portal)
        {
            Console.WriteLine("Connecting to portal.\n");

            this.portal = portal;

            initialized = OpenPortal(portal);
            if (initialized)
            {
                RestartPortal();
                ActivatePortal(1);
                SetPortalColor(0xC8, 0xC8, 0xC8);
            }
            else
            {
                Console.WriteLine("Error initializing portal.");
            }
        }

        private bool OpenPortal(HidDevice portal)
        {
            Console.WriteLine(portal.GetMaxInputReportLength());
            ReportDescriptor descriptor = portal.GetReportDescriptor();

            HidDeviceInputReceiver reciever = descriptor.CreateHidDeviceInputReceiver();
            bool opened = portal.TryOpen(out portalStream);

            var x = portal.GetReportDescriptor();

            reciever.Start(portalStream);
            reciever.Received += OnReceiverReceived;
           
            portalStream.Closed += PortalStreamOnClosed;
           
            return opened;
        }

        private void PortalStreamOnClosed(object? sender, EventArgs e)
        {
            Console.WriteLine("Closed!");
        }

        private void OnReceiverReceived(object sender, EventArgs args)
        {
            try
            {
                var receiver = (HidDeviceInputReceiver)sender;

                if (receiver.Stream?.Device == null)
                {
                    return;
                }

                var length = receiver.Stream.Device.GetMaxInputReportLength();

                var buffer = new byte[length];

                if (receiver.TryRead(buffer, 0, out Report report))
                {
                   // Console.WriteLine($"Received report with id: {report.ReportID}, type: {report.ReportType}");

                    report.Read(buffer, 0, (bytes, offset, item, dataItem) =>
                    {
                       // Console.WriteLine(string.Join(" ", bytes));
                    });

                    switch((char)buffer[1])
                    {
                        case 'S':
                            StatusEvent?.Invoke(this, new StatusChangedEventArgs(buffer));
                            break;
                        default:
                            break;
                    }
                }
                else
                {
                    Console.WriteLine("Failed to read report.");
                }
            }
            catch (Exception e)
            {
                Console.WriteLine($"Exception while reading report occured: {e}");
            }
        }




    }
}

Write to device example?

$
0
0

Hey,

Im working on a project, and have been having some success with HidSharp. I can read from my device just fine, and can access the data i need from the IN reports.

However I totally cannot see how i can write OUT reports back to the device. I've trawled the internet, but no examples.

Ive found I can get the OUT report I need using the GetReport() method but i dont know how to write my values into it, or send it.

Any advice/help much appreciated.

Potential issue with HIDSharp with USB 2.0 Devices on USB 3.0 ports?

$
0
0

I'm having a very strange issue trying to interface with a USB FullSpeed Generic 64-byte HID via HIDSharp, but the problem *only* appears when connected to USB 3.0 ports.  It's entirely possible (and I would say, likely) that the issue lies on the device end rather than the PC/HIDSharp end, but I wanted to at least check and see if there was anything on the Host PC end I could check?

What I'm seeing is that I'm writing data to EP2 (64 Bytes, 10ms, INT) with a hidStream.Write() call, I can see on my USB analyzer (a Beagle USB 12) that the bytes are making it out to the device but on the device firmware side the endpoint status never reports an Event Pending (Out Buffer Full), which is how my firmware knows that data has been received on the endpoint.  Like I said, it seems more likely to be an issue on the device side, but wanted to at least see if there's any funny business I could check for on the host PC side.

Is anyone aware of any known issues with HIDSharp interfacing with 2.0 devices on 3.0 ports?  Any gotchas I should be aware of maybe?

WinHidDevice OutputReportByteLength is wrongly read

$
0
0

Hi,

We have a custom HID device that has OutputReportByteLength set to 4 bytes in firmware, but when we open it in Windows, the value is equal to the InputReportByteLength, i.e. 31.

Is it Windows error ?
Linux reports correct value - HidSharp was not used there to test.

HidSharp HidManager thread spinning on Linux

$
0
0

Hi,

I've noticed that after some random time the HidManager thread starts looping rapidly on Linux. The loop pins one core to 100% usage.
I've tried to profile the code a bit, and it seems that the NativeMethods.poll returns immediately (Platform/Linux/LinuxHidManager.cs, row 63, "ret = NativeMethods.retry(() => NativeMethods.poll(fds, (IntPtr)1, -1));").

My usage of the library is just opening a device, sending a report to the HID stream and reading a response report, then closing the stream. I'm doing this every 5 minutes or so, and at some random time the HidManager thread starts to eat up the CPU. The program seems to continue working despite this.


Have issues trying to get 16-bit joystick inputs consistently

$
0
0

Hello. As the title says, I'm having trouble trying to run a 16-bit joystick/hardware. Sometimes, it works when I run the code. Sometimes it doesn't. It's inconsistent and I need help.

I have no troubles with 8-bit. Just with 16-bit joystick I'm having troubles with.

Here's the code:

static void Main()
{
    var list = DeviceList.Local;
    
    var joystick = list.GetHidDeviceOrNull(productID: 12345);

    if (joystick != null)
    {
        using (var stream = joystick.Open())
        {
            var inputReportBuffer = new byte[joystick.GetMaxInputReportLength()];
            while (true)
            {
                try
                {
                    int length = stream.Read(inputReportBuffer, 0, inputReportBuffer.Length);
                    Console.Write($"Worked!\n");
                    Thread.Sleep(1000);
                }
                catch (Exception ex)
                {
                    Console.Write($"Crashed!\n");
                    Console.WriteLine($"Exception: {ex.Message}\n{ex.StackTrace}");
                }

            }
        }
    }
    else
    {
        Console.WriteLine("Joystick not found.");
    }
}

Please help me. I really appreciate any kind of help.

HidSharp write: 'Operation failed early: The parameter is incorrect'

$
0
0

Hello,

I have a USB scanner for bar codes/QR codes/MRZ.
I have a user manual from the manufacturer, which contains a set of QR codes that allow me to configure the device.
For example by scanning the following values:

$>:S01010F.<$ (Enter Setup)
$>: S0F0516.<$ (USB HID POS)
$>:S01000F.<$ (Exit Setup)

I was able to switch the device to "USB HID POS" mode. (default mode being "USB HID-KBW" in which the scanner behaves like a keyboard)
In this mode I am able to read scanned data using the HidSharp library.

However I also need to be able to change the settings of the device programmatically. But when I call stream.Write, I always get the following exception:

System.IO.IOException: 'Operation failed early: The parameter is incorrect'

Stack trace:
at HidSharp.Platform.Windows.NativeMethods.OverlappedOperation(IntPtr ioHandle, IntPtr eventHandle, Int32 eventTimeout, IntPtr closeEventHandle, Boolean overlapResult, NativeOverlapped* overlapped, UInt32& bytesTransferred)

There's an inner exception that just says Win32Exception: 'The parameter is incorrect' (no stack trace)

Info about the device:

// hdev.ToString() + " | " + hdev.DevicePath
Linux 3.10.14 with dwc2-gadget hidpos 00000000 (VID 4619, PID 33287, version 3.10) | \\?\hid#vid_120b&pid_8207#7&52366e0&0&0000#{4d1e55b2-f16f-11cf-88cb-001111000030}

(the device itself has "Linux" in the name, I'm currently running Windows 10)

The following is an enumeration over the device's Reports:

Max Lengths: Input 64, Output 64, Feature 0
Serial Ports:
1 device items found.
Usage: 8C0001 9175041
Input: ReportID=2, Length=64, Items=1
63 Elements x 8 Bits, Units: None, Expected Usage Type: 0, Flags: Variable, BufferedBytes, Usages: 8C00FE 9175294
Output: ReportID=4, Length=64, Items=1
63 Elements x 8 Bits, Units: None, Expected Usage Type: 0, Flags: Variable, Relative, Nonlinear, Volatile, Usages: 8C0000 9175040

What I'm trying to do:

Assuming the device supports receiving setup commands, and that these are the same as the commands from the QR codes, I've been trying to send the following commands to the device (one at a time):

01010F (Enter Setup)
0C0814 (Set external illumination to "Always on")
01000F (Exit Setup)

NOTE: I've tried sending it in the format $>:S01010F.<$ and S01010F, but I suspect those are just some tags telling the QR parser it's a command, and the actual command is the 6 digit hex string.

I've tried creating the input buffer diretly:
var enterSetupBuffer = Encoding.ASCII.GetBytes("01010F");

I've tried creating a byte array of size 64 and setting the first few bytes in the array:
var someBuffer = new byte[64];
someBuffer[0] = 0x01;
someBuffer[1] = 0x01;
someBuffer[2] = 0x0F;
(and some variations on this)

no matter what I do, I get the same error: Operation failed early: The parameter is incorrect.
Some more details: I try to write using the HidStream.Write(buffer). I attempt the write before I start reading from the device. stream.CanWrite is returning true.

As you've probably guessed, I'm not good with hardware. I'm primarily a business application developer. All my attempts so far have been pretty much guesswork. I don't even know if it's the device rejecting my attempts at communication, or if there's something else I don't even know about tripping me up before the data is even sent to the device.

Any help would be greatly appreciated.

Screen sizing / mouse movement in RemoteViewing

$
0
0

Hi, hoping this board is still monitored?

Thanks for your effort in developing this.

I am currently trying to implement a VNC client in a C# form using this. I tried VNCSharp previously but found the performance to be poor. RemoteViewing seems much better in that respect. However I find that if I use any sizemode other than AutoSize then the mouse scaling seems incorrect - i.e. I cannot reach the bottom X amount of the screen, depending on how much the size of the control differs from that used by autosize.

If I use Autosize the problem I have is that the control is then bigger than the form in which I need to display it. I added a panel and made this the parent of the control so I at least get scrollbars and everything works but not userfriendly! Anyideas on a better solution?

TIA

Mike

HidSharp mocking

$
0
0

Hi,

Thanks for the great HidSharp library, I find it very useful. I am using it in one C# project to communicate with a specific device and want to be able to write unit tests for it. Unfortunately, the library currently makes use of concrete types with no interfaces. This makes it hard to mock/fake for testing.

Is there any chance an `IHidDevice` interface could be added to the NuGet package please? I would be happy to contribute it myself, if you are accepting outside contributions and can tell me how best to share my code with you, as it isn't hosted on GitHub.

I envisage something like this:

```
public interface IHidDevice
{
    Stream Open();
    int ProductID { get; }
    int VendorID { get; }
}
```

Shift key not working

$
0
0

Hi, I find that using the remoteviewing client then keys such as shift key are not sent to server. Other clients with same server the key functionality works as expected

HIDSharp 2.6.2 released.

$
0
0

I've posted a new version of HIDSharp, 2.6.2. Here's the link: https://software.seekye.com/hidsharp

I've been using HIDSharp for device testing and programming through Raspberry Pi devices, so Linux support is greatly improved by this version:

HidDevice.GetSerialPorts() lets you get the serial ports corresponding to a USB composite HID device.
HidDevice.GetUsbPort() lets you get information about the USB port to which the HID device is connected. You can use this for visual displays where you have a number of USB devices connected to the same hub, and don't want the connected device list dancing around.
SerialDevice.GetManufacturerName(), GetProductName(), and GetSerialNumber() all work on Linux now.

There are other improvements and bug fixes as well.

Enjoy!

God bless.

James

RemoteViewing 1.0.0 released.

$
0
0

I've posted a new version of RemoteViewing, 1.0.0. Here's the link: https://software.seekye.com/remoteviewing

It adds support for 16-bit color mode. I found one of my virtual machines used this mode, and RemoteViewing did not previously support it.

It also fixes mouse coordinate scaling on the Windows Forms control. Thanks to mike10 for reporting this bug!

Enjoy!

God bless.

James


HIDSharp 2.6.3 released.

$
0
0

I've posted a new version of HIDSharp, 2.6.3. Here's the link: https://software.seekye.com/hidsharp

This version improves the shutdown behavior on Windows, Mac, and Linux. It also adds a ManualShutdown() method to trigger that shutdown behavior. If you're doing some custom behavior loading and unloading assemblies, this version should be a great improvement for you.

Enjoy!

God bless.

James

DeltaSCP 1.1 released.

$
0
0

I've posted an initial public release of DeltaSCP, 1.1. Here's the link: https://software.seekye.com/deltascp

This is a simple Linux differential copy utility that operates over SSH. I wrote it in 2010, and posted it on SourceForge briefly -- it appears to be gone now -- but never made a proper release of it.

At any rate, this version uses SHA-256 hashes instead of SHA-1 and has some basic versioning in the protocol so I can improve it in the future if I want to.

Mostly this is useful for backing up virtual machine images over the Internet.

Enjoy!

God bless.

James

Signed Axis Minimum values are forced to 0

$
0
0

Hi,

Thanks for this library. There's a problem in the report descriptor parsing with signed values for axis (PhysicalMinimum and LogicalMinimum).

When a negative value is found, it is forced to 0 in Reports/Encoding/EncodedItems, line 160 and 162 :

Changing the following two lines fixes the bug:

EncodedItem.cs : L160 change
{ DataValue = (uint)(sbyte)value; if (value < 0) { Data.Add(0); } }
to
{ DataValue = (uint)(sbyte)value; }

and EncodedItem:L162 change
{ DataValue = (uint)(short)value; if (value < 0) { Data.Add(0); Data.Add(0); } }
to
{ DataValue = (uint)(short)value; }

I don't understand what is the purpose of these 2 tests, and if it is a correct fix. Currently I'm stuck in the development of a plugin for a software that uses this library in a dll because of this bug.

RemoteViewing 1.0.1 released.

$
0
0

I've posted a new version of RemoteViewing, 1.0.1. Here's the link: https://software.seekye.com/remoteviewing

It drastically speeds up the VNC server, and fixes some bugs in it as well. Basic Hextile support is in, so 16x16 regions which are a solid color now take 5 bytes to transfer instead of 1024. This helps on text-heavy pages.

Enjoy!

God bless.

James

RemoteViewing 1.1.0 released.

$
0
0

I've posted a new version of RemoteViewing, 1.1.0. Here's the link: https://software.seekye.com/remoteviewing

It fixes some bugs (one potential crash bug in the VNC client), but mainly, it adds 8-bit color support (ugly) and Zlib support (useful) to the VNC server.

With Zlib support, the VNC server is actually practical to use over the Internet. It uses about 10X less bandwidth, at least when using normal desktop applications. CPU usage is a bit higher when using Zlib, but you can always turn off compression in the VNC client if this is a problem.

Enjoy!

God bless.

James

Viewing all 141 articles
Browse latest View live