Is there a guide to using the libusbk C# binding?

309 views Asked by At

I'm sort of new to C#, I decided to give it a try because I heard it was similar to Java, for my first project I decided to take a look at the C# binding of libusbk.

With some trial and error I got it to find my device and be able to read and write data, the only issue is it only lets me send data once. I need to send 197272 bytes of data but I can only send it 4096 bytes at a time and for some reason it only succeeds with one write and fails at the next.

Here is my code, it's pretty basic but I'm just experimenting.

static void Main(string[] args) {
        byte[] data = new byte[0x30298];
        // Create data to be written

        int device_count = 0;
        KLST_DEVINFO_HANDLE device_info;
        LstK lst = new LstK(KLST_FLAG.NONE);
        lst.Count(ref device_count);

        while (lst.MoveNext(out device_info)) {
            if (device_info.Common.Vid == 0x0955 && device_info.Common.Pid == 0x7321) {
                Console.WriteLine("Device detected");

                UsbK usb = new UsbK(device_info);
                usb.ClaimInterface(0, true);

                byte[] read_buffer = new byte[16];
                bool readID = usb.ReadPipe(IN_ENDPOINT, read_buffer, 16, out int t, IntPtr.Zero);

                int offset = 0;
                int chunk_size = 0x1000;
                int total_bytes_sent = 0;

                while (offset < data.Length) {
                    int length = offset + chunk_size > data.Length ? (data.Length - offset) % chunk_size : chunk_size;
                    byte[] temp = new byte[length];
                    Array.Copy(data, offset, temp, 0, length);
                    offset += length;

                    bool transfered = usb.WritePipe(0x01, data, length, out int length_transfered, IntPtr.Zero);

                    if (transfered) {
                        Console.WriteLine("Sent " + length_transfered + " bytes to device.");
                        total_bytes_sent += length_transfered;
                    } else if (!transfered || length_transfered != length) {
                        Console.WriteLine("Transfer failed. Sent " + length_transfered + " out of " + length + " bytes to device.");
                        break;
                    }
                }

                if (total_bytes_sent != data.Length) {
                    Console.WriteLine("Transfer failed.");
                }
            }
        }
    }

The output is as described above, It succeeds with the first write and fails on the next one. What I'm mainly after is a written guide on how to use this binding, the examples in the dev kit don't explain how to use it. Any help will be appreciated.

0

There are 0 answers