Language - Java SBC Linux Javac

From Phidgets Support
Jump to: navigation, search

Java Development Environments
OS - Windows Windows Javac (Command Line)NetBeansEclipse
OS - macOS macOS Javac (Terminal)NetBeansEclipse
OS - Linux Linux Javac (Terminal)NetBeansEclipse
OS - Linux Phidget SBC Linux Javac (SBC Linux)

Language - Java

SBC Linux with javac

Welcome to using Phidgets with Java! By using Java, you will have access to the complete Phidget22 API, including events.

Javac is a command line-based compiler for java programs that compiles java code into bytecode class files.

Getting Started With the Phidget SBC

Welcome to using the Phidget SBC. If you haven't already, check out the user guide in order to set up the following:

  • Networking
  • Administrator password


If you are ready to go, the first step will be deciding how you will use the SBC:

  • Use a more powerful external computer to develop your code, and then simply copy the files to the SBC.
  • Use the SBC like any other Linux computer, simply connect a monitor and a keyboard and begin your development.


This guide will cover development using an external machine. For development using the SBC itself, check the Javac (Linux) page.

To begin, this video will help you get started:


Developing with an External Computer

There are two main ways in which you can access your SBC from an external computer:

  • SBC Web Interface
  • Secure Shell (SSH)

The user guide covers the SBC Web Interface in detail, so we will review SSH below.

SSH

If you are unfamiliar with SSH, it is a simple yet powerful tool that allows you to log into a remote machine in order to execute commands. You can also transfer files using the associated SCP tool.

In order to use SSH, you need to know the following things about the SBC:

  • IP address (e.g. 192.168.3.195) or the link local address (e.g. phidgetsbc.local)
  • The administrator password

You must also enable SSH on the SBC. You can do this via the SBC Web Interface which is shown in the image below:

SSH on Windows

To use SSH on Windows, we recommend PuTTY. Use the images below as a guide for configuring PuTTY (use the IP address or the link local address interchangeably):


After clicking open, simply login as root and provide the administrator password:


To transfer files between your SBC and Windows machine, we recommend either of these programs:

You will follow a similar process to access the SBC as described for SSH.

SSH on Linux and macOS

SSH is available on Linux and macOS by default. To run SSH, simply open the terminal and type the following:

ssh root@phidgetsbc.local

Or, something like this (you will need to know the IP address of your SBC):

ssh root@192.168.3.195

You will then be prompted for the password in order to gain access to the SBC:


To copy a file from the SBC to your development machine using SCP, simply open the terminal and type the following:

scp root@phidgetsbc.local:/path/to/source /path/to/destination

You can reverse this if you want to transfer a file from your development machine to your SBC:

scp  /path/to/source root@phidgetsbc.local:/path/to/destination

Installing Packages for Development

At this point you have connected to the SBC through one or more these three options:

  • SBC Web Interface
  • SSH
  • Directly via monitor and keyboard

Now that you are connected, you may want to start developing on/for the SBC. Before you do this, you need to install some packages.

The simplest way to install Java support on the SBC is via the install buttons on located on the SBC Web Interface (System->Packages). Check Include full Debian Package Repository before installing.


When developing for Java, ensure your development machine and your SBC have the same version of Java. Check your Java version by entering this command:

java -version

If you need to update the version of Java on your SBC, use the following commands:

apt-get install openjdk-7-jre-headless
su
update-alternatives --config java

You're now ready to begin programming! Continue through this guide for code examples and directions on where to go next.

Use Our Examples

For simplicity, if you have not used Phidgets before, we recommend trying them out directly on an external development machine like a desktop computer. For Java development, check the Javac (Windows), Javac (MacOS), or Javac (Linux) page, depending on your operating system.

One of the best ways to start programming with Phidgets is to use our example code as a guide.

Select an example that will work with your Phidget:

When developing on an external computer, you will write, compile, and test your programs on that machine. When you are ready, you will then upload your programs to the SBC to run them.

Follow these steps to get our examples running on an SBC:

1. Place phidget22.jar on your development machine in a directory that you will use to compile your Java files.

2. Copy all the example files from the example package to the same directory.

3. Compile the ExampleName.java file. If you are using a Windows machine, type the following into the command prompt:

javac -classpath .;phidget22.jar ExampleName.java

If you are using a Linux or macOS machine, type the following into the terminal:

javac -classpath .:phidget22.jar ExampleName.java

You should now have a number of .class files in your project directory


4. Using the SBC Web Interface, create a new project:



5. Transfer all the .class files from the development machine to the SBC, either using the SBC Web Interface or a tool like WinSCP. The project directory will be /usr/userapps/ProjectName

6. Use SSH to access the SBC terminal

7. Navigate to the project folder using the command:

cd /usr/userapps/ProjectName

8. You can now run the program with the command:

java ExampleName


Success! The example is running on your SBC. If you are already familiar with how to use Phidgets in your programs, you can jump ahead to Running a Program Automatically.

You should now have the example up and running for your device. Your next step is to look at the Editing the Examples section below for information about the example and important concepts for programming Phidgets. This would be a good time to play around with the device and experiment with some of its functionality.

Editing the Examples

To get our example code to run in a custom application, simply remove the calls to AskForDeviceParameters and PrintEventDescriptions, as well as the ChannelInfo object, then hard-code the addressing parameters for your application.

If you are unsure what values to use for the addressing parameters, check the Finding The Addressing Information page.

For instance:

//You may remove these lines and hard-code the addressing parameters to fit your application
ChannelInfo channelInfo = new ChannelInfo();  //Information from AskForDeviceParameters(). May be removed when hard-coding parameters.
PhidgetHelperFunctions.AskForDeviceParameters(channelInfo, ch);

ch.setDeviceSerialNumber(channelInfo.deviceSerialNumber);
ch.setHubPort(channelInfo.hubPort);
ch.setIsHubPortDevice(channelInfo.isHubPortDevice);
ch.setChannel(channelInfo.channel);

if(channelInfo.netInfo.isRemote) {
    ch.setIsRemote(channelInfo.netInfo.isRemote);
    if(channelInfo.netInfo.serverDiscovery) {
        try {
            Net.enableServerDiscovery(ServerType.DEVICE_REMOTE);
        }
        catch (PhidgetException e) {
            PhidgetHelperFunctions.PrintEnableServerDiscoveryErrorMessage(e);
            throw new Exception("Program Terminated: EnableServerDiscovery Failed", e);
        }
    }
    else {
        Net.addServer("Server", channelInfo.netInfo.hostname,
            channelInfo.netInfo.port, channelInfo.netInfo.password, 0);
    }
}


//This call may be harmlessly removed
PrintEventDescriptions();

Might become:

ch.setDeviceSerialNumber(370114);
ch.setHubPort(2);
ch.setIsHubPortDevice(true);

Notice that you can leave out any parameter not relevant to your application for simplicity.

You can then manipulate the rest of the code as your application requires. A more in-depth description of programming with Phidgets follows in the Write Code section.

For future Phidgets-based projects, you can leave out the PhidgetHelperFunctions.java and ChannelInfo.java classes entirely.

Write Code

By following the instructions for your operating system and compiler above, you now have working examples and a project that is configured. This teaching section will help you understand how the examples were written so you can start writing your own code.


Remember: your main reference for writing Java code will be the Phidget22 API Manual and the example code.

Step One: Create and Address

You will need to create your Phidget object in your code. For example, we can create a digital input object like this:

DigitalInput ch = new DigitalInput();

Next, we can address which Phidget we want to connect to by setting parameters such as DeviceSerialNumber.

ch.setDeviceSerialNumber(496911);

Although we are not including it on this page, you should handle the return codes of all Phidget functions. Here is an example of the previous code with error handling:

try {
    DigitalInput ch = new DigitalInput();
    ch.setDeviceSerialNumber(496911);
} catch (PhidgetException ex) {
    System.out.println(ex.getDescription());
}

Step Two: Open and Wait for Attachment

After we have specified which Phidget to connect to, we can open the Phidget object like this:

ch.open(5000);

To use a Phidget, it must be plugged in (attached). We can handle this by calling open(timeout), which will block indefinitely until a connection is made, or until the timeout value is exceeded. Simply calling open() does not guarantee you can use the Phidget immediately.

Alternately, you could verify the device is attached by using event driven programming and tracking the attach events.

To use events to handle attachments, we have to modify our code slightly:

ch.addAttachListener(new AttachListener() {
    public void onAttach(AttachEvent ae) {
        printf("Phidget attached!\n");
});

ch.open(5000);

We recommend using this attach listener to set any initialization parameters for the channel such as DataInterval and ChangeTrigger from within the AttachListener, so the parameters are set as soon as the device becomes available.

Step Three: Do Things with the Phidget

We recommend the use of event driven programming when working with Phidgets. In a similar way to handling an attach event as described above, we can also add an event listener for a state change event:

DigitalInput ch = new DigitalInput();

ch.addAttachListener(new AttachListener() {
    public void onAttach(AttachEvent ae) {
        printf("Phidget attached!\n");
});

ch.addStateChangeListener(new DigitalInputStateChangeListener() {
    public void onStateChange(DigitalInputStateChangeEvent e) {
        System.out.println("State changed: " + e.getState());
    }
});

ch.open(5000);

This code will connect a function to an event. In this case, the onStateChange function will be called when there has been a change to the channel's input.

If you are using multiple Phidgets in your program, check out our page on Using Multiple Phidgets for information on how to properly address them and use them in events.

If events do not suit your needs, you can also poll the device directly for data using code like this:

boolean state = ch.getState();
System.out.println("State: " + state);

Important Note: There will be a period of time between the attachment of a Phidget sensor and the availability of the first data from the device. Any attempts to get this data before it is ready will result in an exception. See more information on this on our page for Unknown Values.

Enumerations

Some Phidget devices have functions that deal with specific predefined values called enumerations. Enumerations commonly provide readable names to a set of numbered options.

Enumerations with Phidgets in Java will take the form of com.phidget22.EnumerationType.ENUMERATION_NAME.

For example, specifying a SensorType to use the 1142 for a voltage input would look like:

com.phidget22.VoltageSensorType.PN_1142

and specifying a K-Type thermocouple for a temperature sensor would be:

com.phidget22.ThermocoupleType.K

The Phidget error code for timing out could be specified as:

com.phidget22.ErrorCode.TIMEOUT

You can find the Enumeration Type under the Enumerations section of the Phidget22 API for your device, and the Enumeration Name in the drop-down list within.

Step Four: Close and Delete

At the end of your program, be sure to close your device:

ch.close();

Setting up a New Project

When you are building a project from scratch, or adding Phidget functionality to an existing project, you'll need to configure your development environment to properly link the Phidget Java library.

When developing on an external computer, you will write, compile, and test your programs on that machine. When you are ready, you will then upload your programs to the SBC to compile and run them.

To use the Phidget Java library, add the following import to your code:

import com.phidget22.*;

Once your code is written, follow these steps to get your program running on the SBC:

1. Place phidget22.jar on your development machine in a directory that you will use to compile your Java files.

2. Compile your ProgramName.java file. If you are using a Windows machine, type the following into the command prompt:

javac -classpath .;phidget22.jar ProgramName.java

If you are using a Linux or macOS machine, type the following into the terminal:

javac -classpath .:phidget22.jar ProgramName.java

You should now have a number of .class files in your project directory


4. Using the SBC Web Interface, create a new project:



5. Transfer all the .class files from the development machine to the SBC, either using the SBC Web Interface or a tool like WinSCP. The project directory will be /usr/userapps/ProjectName

6. Use SSH to access the SBC terminal

7. Navigate to the project folder using the command:

cd /usr/userapps/ProjectName

8. You can now run the program with the command:

java ExampleName

Success! The program is running on your SBC. Next, you may want to learn about running a program automatically.

Running a Program Automatically

After testing your program, you will likely want it to run on boot, or on a schedule, without your input.

Running a Program from the SBC Web Interface

To quickly test whether a program can be run automatically, you can try starting it from the SBC Web Interface.

1. To start the program, navigate to Projects->ProjectName->Startup Settings in the SBC Web Interface.

2. Select your program in the drop-down menu labeled Executable/Class Name.



3. Click the Start button on the SBC web interface.


4. You'll note that as it runs, there are two links below the Stop button which can be used to view the program output:

  • stdout: view the program output like you would in a terminal or command prompt
  • stderr: view the program error output


Run on Boot

Running on boot ensures that your program will never miss an event. As long as the SBC is running, your code will be running. This section assumes you have written and compiled your program on an external computer, and have uploaded it to the SBC Web Interface.


To have your program run on boot, navigate to Projects->ProjectName->Startup Settings in the SBC Web Interface. After selecting your project, copy the settings from the image below:



We will review some of the options that are shown in the image above:

  • Startup Order: lower numbers boot first. Booting later means more programs are available for use, booting earlier means other programs can use your program.
  • Run as a daemon: starts the program as a daemon. Unless you have explicitly written your program as a daemon, leave this checked, or else your SBC may hang on boot.
  • Executable/Class name: your main Java class or C file.
  • Arguments: any command line arguments the program needs.

After saving your changes, your program will run automatically whenever your SBC boots.

Run on a Schedule

Running your program on a schedule allows you to perform your task once a week, or once a minute without worrying about memory management issues or instability problems that may arise. It executes, and then gets cleaned up. To run your program on a schedule, we recommend using Cron. Cron can automatically schedule programs (known as jobs, or cron jobs). Cron simply reads a crontab file and runs whatever programs are listed, with whatever timing they are listed with. Cron runs continuously in the background, but the cron jobs only run as long as they naturally would, and then they exit.


Let`s set up your first cron job. We will use nano to edit the crontab file, but feel free to use whatever editor you prefer.


First, set your editor to nano:

export EDITOR=nano

Next, edit your crontab file:

crontab -e

Finally, schedule your cron job:

#cron job that will run at 5AM every week:
0 5 * * 1 /root/code/myprogram argument1


After entering your task, simply save and exit the file.

Run Using a Boot Script

If you want your program to run on boot, you can install your program into the boot order using a script. This process is covered here.

Phidget Programming Basics - Here you can find the basic concepts to help you get started with making your own programs that use Phidgets.

Data Interval/Change Trigger - Learn about these two properties that control how much data comes in from your sensors.

Using Multiple Phidgets - It can be difficult to figure out how to use more than one Phidget in your program. This page will guide you through the steps.

Polling vs. Events - Your program can gather data in either a polling-driven or event-driven manner. Learn the difference to determine which is best for your application.

Logging, Exceptions, and Errors - Learn about all the tools you can use to debug your program.

Phidget Network Server - Phidgets can be controlled and communicated with over your network- either wirelessly or over ethernet.