Trouble accessing USB device using libusb library: (Error opening device)

74 Views Asked by At

I am working on a project that involves fetching input data from a gaming controller using the libusb library. However, I am encountering an issue where the program fails with the message "Error opening device." I have tried several troubleshooting steps, but the problem persists.

Problem Description: I wrote the following code to open the USB device:

#include <stdio.h>
#include "libusb-1.0.26/libusb-1.0.26/libusb/libusb.h"

#define VENDOR_ID 0x045E  // Replace with your controller's vendor ID
#define PRODUCT_ID 0x028E // Replace with your controller's product ID
#define FILENAME "controller_data.txt"

int main() {
    libusb_device_handle *dev_handle;
    libusb_context *ctx = NULL;

    // Initialize libusb
    if (libusb_init(&ctx) < 0) {
        fprintf(stderr, "Error initializing libusb\n");
        return 1;
    }

    // Open the device with the specified vendor and product IDs
    dev_handle = libusb_open_device_with_vid_pid(ctx, VENDOR_ID, PRODUCT_ID);
    if (dev_handle == NULL) {
        fprintf(stderr, "Error opening device\n");
        libusb_exit(ctx);
        return 1;
    }

    // Claim the interface (assuming interface 0)
    if (libusb_claim_interface(dev_handle, 0) < 0) {
        fprintf(stderr, "Error claiming interface\n");
        libusb_close(dev_handle);
        libusb_exit(ctx);
        return 1;
    }

    FILE *file = fopen(FILENAME, "w");
    if (file == NULL) {
        fprintf(stderr, "Error opening file\n");
        libusb_release_interface(dev_handle, 0);
        libusb_close(dev_handle);
        libusb_exit(ctx);
        return 1;
    }

    // Read data from the controller, print to console, and write to file
    unsigned char data[64];
    int transferred;

    while (1) {
        int result = libusb_interrupt_transfer(dev_handle, 0x81, data, sizeof(data), &transferred, 0);
        if (result == 0) {
            // Process and print data to console
            for (int i = 0; i < transferred; ++i) {
                printf("%02X ", data[i]);
            }
            printf("\n");

            // Write data to file
            fwrite(data, 1, transferred, file);
            fflush(file);
        } else {
            fprintf(stderr, "Error reading data: %d\n", result);
            break;
        }
    }

    // Release the interface, close the device, and close the file
    libusb_release_interface(dev_handle, 0);
    libusb_close(dev_handle);
    fclose(file);

    // Deinitialize libusb
    libusb_exit(ctx);

    return 0;
}

i triple checked my device ids which i found to be correct and also tried changing usb ports.

0

There are 0 best solutions below