libusb_open returns LIBUSB_ERROR_ACCESS?

Pankaj picture Pankaj · Apr 10, 2013 · Viewed 7.3k times · Source

I am using libusb in my android app using jni. I am able to find the device using libusb. but not able to open it.

TestExP.c

#include <stdio.h>
#include <sys/types.h>
#include <string.h>
#include <libusb.h>
#include <jni.h>

#define MY_VENDOR_ID    0xXXXX
#define MY_PRODUCT_ID       0xXXXX

int is_usbdevblock( libusb_device *dev )
{
struct libusb_device_descriptor desc;
int r = libusb_get_device_descriptor( dev, &desc );

if( desc.idVendor == MY_VENDOR_ID && desc.idProduct == MY_PRODUCT_ID ){
    return 1;
}

return 0;
}
char* mymethod()
{
    libusb_device **list;
    libusb_device *found = NULL;
    libusb_context *ctx = NULL;
    int attached = 0;
    if(libusb_init(&ctx)!=0)
       return "libusb init failed";

    libusb_set_debug(ctx,3);
    ssize_t cnt = libusb_get_device_list(ctx, &list);
    ssize_t i = 0;
    int err = 0;
    if (cnt < 0)
        return "No usb device on system";
    for(i = 0; i < cnt; i++){
        libusb_device *device = list[i];
        if( is_usbdevblock(device) ){
            found = device;
        break;
        }
    }
    if(found){
        libusb_device_handle *handle;
        err = libusb_open(found, &handle);
        if (err)
            return "Open error";
        return "Device Opened";
    }
return "Device not found";
}

JNIEXPORT jstring JNICALL Java_com_example_test_Test_TestOpen(JNIEnv* env, jobject obj)
{
    return mymethod();
}

Android.mk

 include $(CLEAR_VARS)
 LOCAL_MODULE    := libusb-1.0
 LOCAL_SRC_FILES := libusb-1.0.so
 include $(PREBUILT_SHARED_LIBRARY)

 include $(CLEAR_VARS)
 LOCAL_MODULE    := TestExP
 LOCAL_SRC_FILES := TestExP.c
 LOCAL_SHARED_LIBRARIES += usb-1.0
 include $(BUILD_SHARED_LIBRARY)

in my activity class I do following...

test.java

static{
    System.loadLibrary("usb-1.0");
    System.loadLibrary("TestExP");
}
 public native String TestOpen();

Everything runs fine. when i run this program it returns -3 libusb error code which says "LIBUSB_ERROR_ACCESS" What I am doing wrong. Some say give permisions to the usb device. I can open the device using Android USB-APIs and make a connection to device. But I want to do that with libusb-1.0.

Answer

kyb picture kyb · Mar 7, 2016

Find your device and remember its VID and PID:

lsusb

Create rules file:

sudo gedit /etc/udev/rules.d/99-my-android-device.rules

Enter next strings to file, fill 03eb and 204f with your VID and PID:

ACTION!="add|change", GOTO="my_android_device_rules_end"
SUBSYSTEM!="usb|tty|hidraw", GOTO="my_android_device_rules_end"

ATTRS{idVendor}=="03eb", ATTRS{idProduct}=="204f", MODE="664", GROUP="plugdev"

LABEL="my_android_device_rules_end"

Add yourself to group plugdev:

usermod -aG plugdev $USER

Relogin or restart.

Also you could be interested in similar issue.