Language - Java Linux Eclipse: Difference between revisions

From Phidgets Support
No edit summary
No edit summary
Line 26: Line 26:
Next, create a new Java project. Give it the same name as the example you downloaded above:
Next, create a new Java project. Give it the same name as the example you downloaded above:


[[Image:Java_eclipse_linux_newproject.PNG|link=| center]]
[[Image:Java_eclipse_linux_newproject.PNG|link=| center|500px]]




Click ''Next >'' and add phidget22.jar to your project as an external jar:
Click ''Next >'' and add phidget22.jar to your project as an external jar:
[[Image:Java_eclipse_linux_addjar.PNG|link=| center]]
[[Image:Java_eclipse_linux_addjar.PNG|link=| center|500px]]




Finally, drag the example java file into the src folder that has been created for you and run the example:
Finally, drag the example java file into the src folder that has been created for you and run the example:


[[Image:Java_eclipse_linux_run.png|link=|center]]
[[Image:Java_eclipse_linux_run.png|link=|center|700px]]




Line 51: Line 51:
==Setting up a New Project==
==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 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.
To begin, create a new Java project:
[[Image:Java_eclipse_linux_newproject.PNG|link=| center |500px]]
Click ''Next >'' and add phidget22.jar to your project as an external jar:
[[Image:Java_eclipse_linux_addjar.PNG|link=| center|500px]]
Create a new Class in your project:
[[Image:Java_eclipse_linux_newClass_menu.png|link=|center|700px]]
Name the class, and be sure to check the ''public static void main'' box.
[[Image:Java_eclipse_linux_newClass.png|link=|center|500px]]




Line 57: Line 73:
import com.phidget22.*;
import com.phidget22.*;
</syntaxhighlight>
</syntaxhighlight>
You can now create your project as shown in the [[#Use Our Examples|Use Our Examples]] section.


The project now has access to Phidgets.
The project now has access to Phidgets.

Revision as of 17:24, 31 August 2018

Java Development Environments
OS - Windows Windows

JAVA JC WIN.png JAVA JC WIN on.png

JAVA NETBEANS.png JAVA NETBEANS on.png

JAVA ECLIPSE.png JAVA ECLIPSE on.png

OS - macOS macOS

JAVA JC TRM.png JAVA JC TRM on.png

JAVA NETBEANS.png JAVA NETBEANS on.png

JAVA ECLIPSE.png JAVA ECLIPSE on.png

OS - Linux Linux

JAVA JC TRM.png JAVA JC TRM on.png

JAVA NETBEANS.png JAVA NETBEANS on.png

JAVA ECLIPSE.png JAVA ECLIPSE on.png

OS - Linux Phidget SBC Linux

JAVA JC SBC.png JAVA JC SBC on.png

OS - Android Android

JAVA AS ANDROID.png JAVA AS ANDROID on.png

Language - Java

Linux with Eclipse

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

Eclipse is an IDE used to write, compile, and run Java applications.

Install Phidget Drivers for Linux

Before getting started with the guides below, ensure you have the following components installed on your machine:

  1. You will need the Phidgets Linux Drivers
  2. You will need the Java Development Kit from Oracle
  3. You will need a copy of phidget22.jar

Use Our Examples

One of the best ways to start programming with Phidgets is to use our example code as a guide. In order to run the examples, you will need to download and install Eclipse. You will also need a copy of phidget22.jar.


Now that you have Eclipse installed, select an example that will work with your Phidget:


Next, create a new Java project. Give it the same name as the example you downloaded above:

Java eclipse linux newproject.PNG


Click Next > and add phidget22.jar to your project as an external jar:

Java eclipse linux addjar.PNG


Finally, drag the example java file into the src folder that has been created for you and run the example:

Java eclipse linux run.png


Before you run the example, you may need to set up your Udev rules. An explanation on how to do this is provided on the Linux OS page, which can be accessed here.


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 can be found in our guide on Phidget Programming Basics.

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.

To begin, create a new Java project:

Java eclipse linux newproject.PNG


Click Next > and add phidget22.jar to your project as an external jar:

Java eclipse linux addjar.PNG


Create a new Class in your project:

Java eclipse linux newClass menu.png


Name the class, and be sure to check the public static void main box.

Java eclipse linux newClass.png


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

import com.phidget22.*;

The project now has access to Phidgets.

Further Reading

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.