Java Usb communication Usb4Java (High Api)

I’m posting an example of how to use the high api of usb4java.
It should be straight forward to understand but if they are questions just ask.
There is an example at the bottom to show you how to use it.

  • Pingback: Java Usb communication Usb4Java (Low Api) | Mets-Blog()

  • Don

    Hi Metin,

    I’m using the high api and it is definitely a lot easier to use, however when I compile my code I get the following error message:

    “Exception in thread “usb4java Device Scanner” java.lang.IllegalStateException: Device is already attached
    at org.usb4java.javax.AbstractDevice.setParentUsbPort
    at org.usb4java.javax.Port.connectUsbDevice
    at org.usb4java.javax.Ports.connectUsbDevice
    at org.usb4java.javax.Hub.connectUsbDevice
    at org.usb4java.javax.Hub.connectUsbDevice
    at org.usb4java.javax.DeviceManager.scanNewDevices
    at org.usb4java.javax.DeviceManager.scanNewDevices
    at org.usb4java.javax.DeviceManager.scan
    at org.usb4java.javax.DeviceManager.scan
    at org.usb4java.javax.DeviceManager.scan
    at org.usb4java.javax.DeviceManager.scan
    at org.usb4java.javax.DeviceManager$

    I used your example code above but with the product ID and vendor ID for my device and I took out the send data function since I’m not trying to do that with this device (I need to read data).
    I know it’s telling me the device is already attached, and I’m guessing your implementation for a printer was on a shared network so your device wasn’t physically attached to your usb port??

    I’m not sure which part of the code I need to adjust, since my device is physically connected to the usb port on my computer and it’s giving me the error above. I’m confused as to which function calls it’s referring to in the error as none of that seems to be in my code. Do you know what it means and how I would need to modify your code to stop getting the error?

    Thank you so much

  • Don

    Just an update I pulled up the javax documentation and found where these functions where but I still don’t understand how they are being called by the above code and what I would need to do to get rid of them?

    • metin

      hi don,
      I updated the post, I added a method to read data and changed the getter for interface.
      I also read the documentation a bit, the same pipe can be used to send and receive data, it is a blocking operation so it will wait untill data is received or an error occurs.
      About your error, haven’t seen it before, make sure zadig is completely uninstalled. There should be a checkbox when you uninstall it from hardware manager, be sure to check that.
      Unfortunately couldn’t test receiving data. I will post reading data with low api later.

      • metin

        added one more method, reading asynchron, will not block. my preffered way, now I need a suitable device.

  • Don

    Thanks for the update and adding a read function Metin!

    I’m still trying to figure out the errors I get when I compile. I’m almost certain it is in the getRootUsbHoob() function or the UsDevice findDevice(Usb hub, short vendorId, short ProductId) so my device is being found because it tell me it’s already attached, but I don’t think it is opening it up and getting it’s interface and executing the read function through its endpoints or pipes.

    Would it be possible for you to test the functions getRootusbHub(), the two findDevice functions and the getDeviceInterface function only with something as simple as USB mass storage device or anything you can physically connect to your port via a usb knowing it’s product and vendor id and see if you get the same errors I’ m getting? The send or read functions are not necessary for this test since I’m almost sure my errors come from one of the other functions but I can’t pin down exactly what I need to change and the documentation on javax is unclear to say the least.

    Thanks for you help! I really appreciate it.

    • metin

      I already tried all the functions you mentioned it is working, my guess is that your error cause coming from zadig driver. Try uninstalling it and use the high api or just leave it and use the low api. Im thinking of opening a discussion page for this kind of stuff 🙂

      • Don

        Hey Metin a discussion page is a pretty good idea. So I’m so close to finding a solution. Everything works up until adding the usb pipe event listener. For some reason when I compile, the program doesn’t execute that block of code that adds the event listener and then extracts the bytes of data. I don’t getting any errors when I compile. Is there any way to verify usb event listener is being used and function dataeventoccured is actually being called? I’m wondering if it’s never being executed because it isn’t properly extracting data from my device or the device isn’t sending any data to the software. Is there anything that allows me to verify an event listener has been created? And once I do that, verify if data is there to extract, or if no data is there for extraction?

        Thanks for all your help.

        • metin

          I havent had the time to test it but I’m at the same point as you, trying to get the asynchron read work. You can try the synchron to see if you can read some data. I will start making a discussion page.

  • Chris

    thank you for the example. The code is almost the same I found on the usb4java website. Nevertheless there is something interesting for me:
    Where did you get the “commands” for your device ->
    byte[] initEP = new byte[] { 0x1b, ‘@’ };
    byte[] cutP = new byte[] { 0x1d, ‘V’, 1 };
    you send before and after actual communicating with the device? Is this something written in the specs of the device or can I simply find it out with some tool or even usb4java. I’m just new to the “usb-device-business” and I want to read data from my bicycle home trainer where I do not have specs at all.

    Cheers, chris

    • metin

      those commands for the printer are universal. some of them may not be but whatever. I found them on the net and worked for all printers. Most of the device vendors also provide specifications.

      No I don’t send before and after communication, the communication is open and then I send those commands.

      • Chris

        OK – thank you Metin.
        With “communication” I meant your own arbitrary data which is sent to the printer. There are these two special commands leading/trailing – which do not seem to be just out of your fantasy 😉

        • metin

          Well communication for me is the opened pipe, also even if don’t send those 2 commands the printer will still print but will not cut the paper at the end.

          • Chris

            Aaahhh – now I understand (and know, that the ‘P’ is for paper). Thanks.
            Did not know what this commands were for.

  • giuseppe

    I’ve the following error, can you help me ?.

    • metin

      Is that all the error says? <>

  • Kevin Nathan

    I seem to be getting a null pointer for iface from getDeviceInterface. I modified your main function a little to reflect how I will be using this in our program. This is a Point Of Sale display to which we only need to write, no read.

    Here’s the error:

    New usb4java: highusb.Usb4JavaHigh@ec7c94
    New usbDevice: Bus 002 Device 096: ID 0fa8:a030
    Exception in thread “main” java.lang.NullPointerException
    at highusb.Usb4JavaHigh.getDeviceInterface(
    at highusb.TestApp.main(
    Java Result: 1
    BUILD SUCCESSFUL (total time: 0 seconds)

    And here is my main function from TestApp:

    public static void main(final String[] args) throws UsbException {

    Usb4JavaHigh usb4java = new Usb4JavaHigh();
    System.out.println(“New usb4java: ” + usb4java.toString());

    UsbDevice usbDevice = usb4java.findDevice(vendor, product);
    System.out.println(“New usbDevice: ” + usbDevice.toString());

    UsbInterface iface = usb4java.getDeviceInterface(usbDevice, 0); // line 45
    System.out.println(“New iface: ” + iface.toString());

    String str;
    String data;
    int row;

    row = 0;
    data = “Row 1 test”;
    str = String.valueOf(TD3000_DIGSEL) + String.valueOf((char) (row * 20)) + data;
    usb4java.sendBulkMessage(iface, data, 0);

    row = 1;
    data = “Row 2 test”;
    str = String.valueOf(TD3000_DIGSEL) + String.valueOf((char) (row * 20)) + data;
    usb4java.sendBulkMessage(iface, data, 0);

    • metin

      Check your driver, check the configuration and interface list if it is null. From device you can get the configuraions list and from that the interface list. see if one of them is empty or null

      • Hi Metin,
        I am a little bit confused on what you meant by driver. It is is giving a nullpointer as well on the getdeviceinterface. I badly need your help! Thank you!

  • Kevin Nathan

    Ok, I will check those again as soon as I can. This project is on a bit lower priority, so I can’t get to it every day. I will let you know what I find as soon as I can get to it. Thanks!

  • Kevin Nathan

    This is what I get. There is one configuration and one interface in each list:

    configuration list size: 1
    i: 0 is not null
    configuration.string : null
    configuration.toString: USB configuration 01
    isActive: false
    interface list size: 1
    j: 0 is not null
    InterfaceString: null
    InterfaceString: USB interface 00

    And this is the code generating the above:

    List confList;
    List ifaceList;

    confList = dev.getUsbConfigurations();
    System.out.println(“configuration list size: ” + confList.size());

    for (UsbConfiguration conf : confList) {
    if (conf != null) {
    System.out.println(“i: ” + i + ” is not null”);
    try {
    System.out.println(“configuration.string : ” + conf.getConfigurationString());
    System.out.println(“configuration.toString: ” + conf.toString());
    System.out.println(“isActive: ” + conf.isActive());
    ifaceList = conf.getUsbInterfaces();
    System.out.println(“interface list size: ” + ifaceList.size());
    for (UsbInterface face : ifaceList) {
    if (face != null) {
    System.out.println(” j: ” + j + ” is not null”);
    System.out.println(” InterfaceString: ” + face.getInterfaceString());
    System.out.println(” InterfaceString: ” + face.toString());
    } else {
    System.out.println(” j: ” + j + ” is null”);
    } catch (UsbException | UnsupportedEncodingException | UsbDisconnectedException ex) {
    Logger.getLogger(SayHello.class.getName()).log(Level.SEVERE, null, ex);
    } else {
    System.out.println(“i: ” + i + ” is null”);

    • metin

      The only thing I can think of is the driver, but not entirely sure. Anyway I will provide a general solution with pure java as long as the driver is installed properly. Sorry for the late answer I was at a conference.

    • metin
  • San

    Hi metin,
    hope you still check this thread
    I’m getting the following error

    javax.usb.UsbPlatformException: USB error 12: Can’t open device Bus 001 Device 007: ID 11ca:0222: Operation not supported or unimplemented on this platform

    I’ve read some posts that talks about using (zadig) which you have specifically mentioned not to
    I’m actually new to Java let alone Javax but I’ll do my best to follow through


    • metin

      That is probably because of the driver. By the way what are you trying to connect, printer?

  • San

    Full error

    javax.usb.UsbPlatformException: USB error 12: Can’t open device Bus 001 Device 007: ID 11ca:0222: Operation not supported or unimplemented on this platform
    at org.usb4java.javax.ExceptionUtils.createPlatformException(
    at org.usb4java.javax.AbstractDevice.claimInterface(
    at org.usb4java.javax.Interface.claim(
    at usbtrial2.USBtrial2.readMessage(
    at usbtrial2.USBtrial2.main(
    javax.usb.UsbClaimException: No interface is claimed
    at org.usb4java.javax.AbstractDevice.releaseInterface(
    at org.usb4java.javax.Interface.release(
    at usbtrial2.USBtrial2.readMessage(
    at usbtrial2.USBtrial2.main(
    BUILD SUCCESSFUL (total time: 7 seconds)

  • San

    Its a atm card-reader with biometrics capabilities
    This code works for any device right?

  • metin

    I discouraged zadig against printers, should have written that better. For printers one should avoid usb4java altogether. You on the other hand should probably use it. Before that check if you can connect it any other way, maybe a serial port? If not replace the atm’s default driver using zadig. The code works if the driver is ok.

  • San

    Thanks alot metin
    I’ll try that out

  • San

    THanks a lot Metin it works!

  • me

    i used your code to read all the connected usb devices, but when i use my programm on another computer (it works fine with mine) i always get:

    Do you know why or have an alternative to read connected devices?

    • metin

      That means on that other pc something is different, make sure that the file is on the root of your classpath. Try to reproduce by removing that property file from your classpath in your pc and see if you get the same error. Other than that something like user rights might be the problem but its a long stretch, try to run it as admin if on windows.

      • me

        Thanks for your reply!
        Removing the property file does not result in getting the same error.
        After this i log in as admin on windows, but got the same Nullpointerexception. Maybe it is a problem in the jarfile from usb4java? Some users report it contains still a few bugs.

        • metin

          I can’t be sure without knowing more details, project and deployment. I suggest you to try this example project from on that other pc

          • me

            I haven’t tried the examples, but when i run the console on my pc as an admin, i get the same error (NullpointerException).
            When i have found a soloution, i will post it.

  • Jeroen

    Hi Metin, you say you discourage using zadig for printers, but the combination of zadig, a Custom printer and Usb4Java is what we’re using right now. It works most of the time, but it’s unstable (when checking the status of the printer / USB port every 5 seconds it sometimes goes into ‘disconnected’, back to ‘connected’ and back to reconnected in a few minutes, and then stable again for an hour or an hour and a half before showing errors again …)
    So you seem to be right about your discouragement, but my main question it this case is: what solution do you recommend when you want to be able to not only print text, but also request the status of the printer to know when it runs out of paper?

  • QUST

    Hi Metin , my Hid Device just like a touch pad , when I touch the pad , I want recive some data . Could you tell how to program it ,I have used your method ,but it can’t recive the data , I think my program need a thread .

    • metin

      Well if its a hid device and get recognized as such(you can see it under hid devices in windows in hardware manager), then you should use an api for hid instead of this usb api. The hid api are way better than this one. just google java hid

Recent Posts

Recent Comments