Using our USB modules with Java

Using our USB modules with Java

Numerous customers have asked for a Java library, and we are finally able to fulfill their wish: we are publishing today the beta-test version of the Java library. We need to finalize the documentation and probably to correct a few bugs, but all the functionalities available in the other languages are implemented and commented.




How to access USB peripherals from Java?

There is no obvious answer to this question. Even if the Java slogan is "Write once, run anywhere", it's quite different in the real world. To access the USB bus (and the hardware in general) there is no solution which is 100% Java. By wanting to create a "clean" abstraction of a machine, Sun moved away from numerous scenarios where one needs to access hardware. There is a platform which does indeed provide native access to the USB peripherals: Android. But this API is available only on the latest versions of the OS and few mobile phones and tablets completely support it. For the other architectures, viable solutions imply either non portable code, or use of an external application which provides the hardware abstraction that the JVM should have implemented in a better world. This application must be available and installed on all the platforms one wants to support.

there is no solution which is 100% Java
there is no solution which is 100% Java



In our case, we are going to follow the exact same strategy we have been employing for PHP and JavaScript: use the VirtualHub as a gateway. The Java code communicates with the VirtualHub by TCP, the later is responsible for accessing the USB modules natively and for forwarding the USB traffic on the TCP socket. As the VirtualHub is available on the main platforms (Windows, Mac OSX, as well as Linux in 32 bits and 64 bits, and ARM), we can keep Sun's promise ("Write once, run anywhere")!

The VirtuaHub serves as a gateway to access the USB module
The VirtuaHub serves as a gateway to access the USB module



A short example
We are going to write a short sample program to illustrate the particularities of the Java library. The goal is simply to display in a loop the ambient light value on a command line.

Before we start to code, we must remember to run the VirtualHub on the machine to which the modules are connected. We must also take care to copy the yoctoAPI.jar file in our classpath (or to add the Binaries directory to our classpath).

The first thing to do in the code is to import the Yoctopuce classes with import com.yoctopuce.YoctoAPI.*;. Then we must register the VirtualHub which runs on the same machine, taking care to intercept potential exceptions. This step allows us to access all the modules connected to the machine.



 try {
    // setup the API to use local VirtualHub
    YAPI.RegisterHub("http://127.0.0.1:4444/");
} catch (YAPI_Exception ex) {
    System.out.println("Cannot contact VirtualHub on 127.0.0.1 (" + ex.getLocalizedMessage() + ")");
    System.out.println("Ensure that the VirtualHub application is running");
    System.exit(1);
}
 



We must now access the light sensor of the Yocto-Light. We have two options:
1. To use the first sensor connected
2. To access a particular sensor by specifying its hardware identifer.

We are going to support both. If the program is launched without arguments, we use YLightSensor.FirstLightSensor() to find a connected light sensor. If the program is launched with a hardware identifier in the command line, we pass this information directly to YLightSensor.FindLightSensor(args[0] ).


YLightSensor sensor;
if(args.length>0) {
    sensor = YLightSensor.FindLightSensor(args[0] );
} else {
    sensor = YLightSensor.FirstLightSensor();
    if(sensor== null){
        System.out.println("No module connected (check USB cable)");
    }
}
 



Now that we have our YLightSensor object, the remainder of the code is trivial. It is a never ending loop which periodically reads the module value and displays it. We must only add some lines of code to correctly catch exceptions (for instance if the module is disconnected while the program is running). To temporize the loop, we must use YAPI.Sleep() which, on top of waiting intelligently (without uselessly using the CPU), periodically checks the connection with the VirtualHub. In this precise example, we don't use any callback; therefore, we could have used a classical waiting method (for example Thread.currentThread().sleep(1000);), but it's better to learn good habits from the start.



public class Demo {

  /**
   * @param args the command line arguments
   */

  public static void main(String[] args)
  {
    try {
      // setup the API to use local VirtualHub
      YAPI.RegisterHub("http://127.0.0.1:4444/");
    } catch (YAPI_Exception ex) {
      System.out.println("Cannot contact VirtualHub on 127.0.0.1 ("
                         + ex.getLocalizedMessage() + ")");
      System.out.println("Ensure that the VirtualHub application is running");
      System.exit(1);
    }

    YLightSensor sensor;
    if (args.length > 0) {
      sensor = YLightSensor.FindLightSensor(args[0] + ".lightSensor");
    } else {
      sensor = YLightSensor.FirstLightSensor();
      if (sensor == null) {
        System.out.println("No module connected (check USB cable)");
      }
    }
    while (true) {
      try {
        System.out.println("Current ambient light: "
                           + sensor.get_currentValue() + " lx");
      } catch (YAPI_Exception ex) {
        System.out.println("Module not connected (check identification and USB cable)");
      }
      System.out.println(" (press Ctrl-C to exit)");
      YAPI.Sleep(1000);
    }
  }
}

 



Why do we publish the library in a beta version?
For several reasons. First, we are pretty sure that there are still a few bugs which escaped our notice and the documentation has not been fully translated yet. Nevertheless, the API is usable. If you have already used one of our libraries, you can easily do without the Java documentation, objects and methods are the same as in the other languages. Only the syntax specific to Java differs.

Second, each language has its own conventions and particularities. Even if technically the porting of the Java library works, we also want our library to the intuitive and easy to access from all stand points. Therefore, we count on your improvement suggestions, if need be. Likewise, we want our users to start coding without having to learn a new environment or to understand how to compile their project with our library. To reach this goal, we provide full projects enabling you to run examples in an IDE, for now only in the NetBeans environment that we use. Naturally, we are going to add Eclipse in the coming weeks. There too, if you have comments, don't hesitate to contact us by email or to leave a comment.

Download beta Library for Java here

Add a comment No comment yet
Back to blog












Yoctopuce, get your stuff connected.