Alert.png

Notice: This page contains information for the legacy Phidget21 Library.

Phidget21 is out of support. Bugfixes may be considered on a case by case basis.

Phidget21 does not support VINT Phidgets, or new USB Phidgets released after 2020. We maintain a selection of legacy devices for sale that are supported in Phidget21.

We recommend that new projects be developed against the Phidget22 Library.


Click on the 2phidget22.jpg button in the menu bar to go to the Phidget22 version of this page.

Alert.png

Language - iOS: Difference between revisions

From Phidgets Legacy Support
No edit summary
No edit summary
Line 1: Line 1:
[[Category:Language]]
[[Category:Language]]
[[File:icon-iOS.png|64x64px]] Preamble about the language's origin and its main characteristics.
[[File:icon-iOS.png|64x64px]] application are built using the Cocoa Touch framework and the Objective C programming language, both developed by [http://www.apple.com Apple].  




==Support==
iOS has a complete API for all Phidgets devices, and code samples for PhidgetInterfaceKit devices.


For a complete list of our supported languages and their support status, [[Levels of Support|click here]].
__TOC__


* Our honest opinion on how well this language is suited to controlling Phidgets. If it is a poor choice, suggest and link similar (better) languages.
==Introduction==
* In this section, list any restrictions or limitations that this particular language may impose. For example, incompatibility with certain operating systems.


==Development Environments and Compilers==
{{LanguageSupport|Android|nearly the complete Phidget API, including events, and only excepting a few open() calls outlined later|the Phidget Interface Kit and two Hello World examples.|Eclipse on Windows, Mac OS, and Linux|}}


Describe each major compiler and notable differences or important information. (eg. framework versions) If there are known issues/workarounds mention them and link to the corresponding issue at the bottom of the page.  
==Quick Downloads==
{{QuickDownloads|Android|
{{APIQuickDownloads|http://www.phidgets.com/documentation/JavaDoc.zip}}|
{{ExampleQuickDownloads|http://www.phidgets.com/downloads/examples/android-examples_2.1.8.20120216.tar.gz|(and Phidget Android Library)}}|
{{ExtraLibraryQuickDownloads|http://www.phidgets.com/downloads/examples/android-examples_2.1.8.20120216.tar.gz||(Phidget21.jar included in Examples)}}
{{WindowsQuickDownloads}}
{{MacQuickDownloads}}
{{LinuxQuickDownloads}}
}}
 
==Getting Started with Android Java (Eclipse)==
 
If you are new to writing code for Phidgets, we recommend starting by running, then modifying existing examples. This will allow you to:
{{ExampleCodeReasons}}
 
As Android development is primarily done on Eclipse, and Eclipse is relatively platform-independent, we provide instructions for Eclipse rather than by operating system.
 
For basic differences on installing and setting up Eclipse on your development system, you can try the [[OS - Android|Android Operating System]] page.  However, your best bet for information about general use of Eclipse on your development operating system (Windows, Mac, or Linux) will be the [http://www.eclipse.org/documentation/ Eclipse support page] or the Internet at large.
 
Phidgets can run directly plugged in to Android devices with a USB port and system 3.1 or later. 
 
Otherwise, Android can control a Phidget remotely over a network, by using the [[Phidget Webservice]]
 
Hence, we split instructions up by Android OS version number.
 
===Android Under 3.1 (and/or no USB Port)===
 
These types of phones and tablets can use Phidgets only remotely over a network using the [[OS - Android#Webservice|Phidget Webservice]].
 
====Use Our Examples====


==Quick Downloads==
Download and unpack the [http://www.phidgets.com/downloads/examples/android-examples_2.1.8.20120216.tar.gz Phidget Examples for Android].  There are two Hello World examples: {{Code|HelloWorldRemote}} (the one you want), and {{Code|HelloWorld}} (for tablets with a USB port).
Before you can run your program, you need to set up the proper environment and get the necessary files off the Phidgets website.
 
Visit the drivers section at www.phidgets.com and get the latest:
Import the {{Code|HelloWorldRemote}} example into Eclipse:
* [http://www.phidgets.com/drivers.php Phidget Framework]
* File → Import... → General → Existing Projects Into Workspace → (Next)
* [http://www.phidgets.com/drivers.php iOS Library]
* Select {{Code|HelloWorldRemote}} root directory → Select all files → Finish
You will need the Phidget Framework to use and to program with Phidgets. We also recommend that you download the following reference materials:
 
* [http://www.phidgets.com/documentation/Phidget21_C_Doc.zip API Manual]
Next, you '''must change''' the IP address within the example code to the IP address of the computer directly connected to the Phidget you are trying to control.  This happens on the line that says something like:
* [http://www.phidgets.com/documentation/web/cdoc/index.html API Reference]
<div class="source">
* [http://www.phidgets.com/downloads/examples/iOS_2.1.8.20110712.zip iOS Sample Code]
<syntaxhighlight lang=java>
* You can find a high level discussion about programming with Phidgets in general on the [[General API]] page.
device.open("192.168.3.133", 5001);
* The [[Device Functionality]] page explains the general operational information for your device.
</syntaxhighlight>
</div>


You may want to have these pages open while working through these instructions.
Also, note that the HelloWorldRemote example was written for Android 2.1.  If needed, you can change this in:
(Right Click on Project) &rarr; Properties &rarr; Resource (on left) &rarr; Android


==Getting Started==
To run the example: Right-click on project in Package Explorer (To open the Package Explorer, use Window &rarr; Show View &rarr; Package Explorer)


You will need the Phidget21 library and the iOS library to use and program with Phidgets.
Select Run As... &rarr; Android Application
As iOS devices do not have USB ports, support for Phidgets is made available through the WebService.
The system that is hosting the Phidgets will need to have the Phidget21 library installed.  
After the framework is installed, the WebService must be started.  
For more information on the WebService, please see the [[Phidgets Webservice|Webservice Page]].


===Setting up a Phidgets Project===
This will bring up the Android Virtual Device manager window.  If your Android hardware is plugged in to your debugging computer, you will see the hardware as an option on which to run the example.  You should run it directly on your Android device, unless you are comfortable setting up the emulator to run on your local network.


The Phidget examples were written in Objective-C and Xcode 4.0, and this tutorial assumes their use.
After the {{Code|HelloWorldRemote}} application starts running on your Android device:
Other versions of Xcode should work as well and would be set up in a similar manner. In Xcode:
# Make sure the Phidget Webservice is running on the computer with the IP address you put into the code
* Generate a new iOS Windows-based Application project with a descriptive name such as PhidgetTest.
#*For directions on how to set up and run the webservice on a remote computer, refer to the page [[Software Overview#Operating System Support|for that operating system]]
* Set up the Provisioning Profiles and Code Signing settings, if necessary.
# Plug a Phidget into that computer
* Download the Phidget21 iOS library, extract the file, and move the iphoneos and the iphonesimulator folders, as well as the phidget21.h into the same directory as the the .xcodeproj file.
* In xCode, open up the Project Settings > Build Settings.
* In Linking > Other Linker Flags, follow these steps for both Debug, and Release:
** Select "Any iOS Simulator SDK" and enter:


<div class="source"><syntaxhighlight lang=c>
And on your Android device, depending on which Phidget you plug in, you should see something like:


$(SRCROOT)/iphonesimulator/libPhidget21.a
[[Image:android_helloworld_remotehello.png|700px|alt=|link=]]


</syntaxhighlight></div>
And when you unplug that Phidget from the remote computer, you should see something like this on your Android device:


:* Select "Any iOS SDK" and enter:
[[Image:android_helloworld_remotegoodbye.png|700px|alt=|link=]]


<div class="source"><syntaxhighlight lang=c>
If you have the specific Phidget for the other included Android examples (i.e. the InterfaceKit), you can run the other examples in the same way.


$(SRCROOT)/iphoneos/libPhidget21.a
To envision the system in the background, you can refer to the Webservice section on the [[OS - Android]] page.


</syntaxhighlight></div>
====Write Your Own Code====


* In Search Path > Header Search Path, enter:
To write your own code from scratch, start with an Android project in Eclipse (File &rarr; New &rarr; Android Project).  Then....


<div class="source"><syntaxhighlight lang=c>
=====Step One: Link the Phidget Libraries to your Project=====


$(SRCROOT)
When you download and unzip the [http://www.phidgets.com/downloads/examples/android-examples_2.1.8.20120216.tar.gz Phidget Examples for Android], each project folder will (in addition to the project files themselves) contain three things:
# A libs/ folder (containing an armabi/ folder and a single file called libphidget21.so)
# A jar file containing the general Phidget java library (phidget21.jar)
# A jar file for directly driving USB devices from a USB port on the Android device (PhidgetsUSB.jar)


</syntaxhighlight></div>
Copy the {{Code|libs}} folder, the {{Code|PhidgetsUSB.jar}} file, and the {{Code|phidget21.jar}} file to your project folder.


* In the header file, add a reference to phidget21.h:  
To install libraries to run a Phidget '''remotely''' over a network using the Webservice:
# Add the libs/ folder to your project
#* To add the libs/ folder in Eclipse, simply place it in the root folder of your project
# Add the phidget21.jar file to your project
#* In Eclipse use the top-bar menu: Project &rarr; Properties &rarr; Java Build Path &rarr; Libraries (tab) &rarr; Add JAR


<div class="source"><syntaxhighlight lang=objc>
=====Step Two: Give your Program Permission to use the Internet=====


#import "phidget21.h"
Add the following to your <code>AndroidManifest.xml</code> file:


<div class="source"><syntaxhighlight lang=xml>
    <uses-permission android:name="android.permission.INTERNET"></uses-permission>
</syntaxhighlight></div>
</syntaxhighlight></div>


* A text field will be used for the purpose of capturing output. Open MainMenu.nib to bring up the Interface Builder. Drag a text field from the Library to the Window. 
=====Step Three: Include the Phidget Libraries in your Source=====
* Add a text field outlet in the header file. For example,
 
<div class="source"><syntaxhighlight lang=objc>


    @interface PhidgetTestAppDelegate : NSObject <UIApplicationDelegate>{
Then, in your code, include an {{Code|import}} reference to the library. In Android Java:
        IBOutlet UITextField *sensorValueTxt;
    }
    @property (nonatomic, retain) IBOutlet UIWindow *window;
    @property (nonatomic, retain) IBOutlet UITextField *sensorValueTxt;
    @end


<div class="source"><syntaxhighlight lang=java>
  // This contains all of the devices and the exceptions
  import com.phidgets.*;
  // This contains all of the event listeners
  import com.phidgets.event.*;
</syntaxhighlight></div>
</syntaxhighlight></div>


* In the implementation file, add the following line to the implementation section:
Then you are ready to begin coding!
 
<div class="source"><syntaxhighlight lang=objc>
===Android 3.1+ with USB Port===
 
If your tablet has a USB host port and is running Android 3.1 or later, you can plug Phidgets directly into it.
 
====Use Our Examples====
 
Download and unpack the [http://www.phidgets.com/downloads/examples/android-examples_2.1.8.20120216.tar.gz Phidget Examples for Android].  There are two Hello World examples: {{Code|HelloWorld}} (the one you want), and {{Code|HelloWorldRemote}} (for controlling Phidgets over the Webservice).
 
Import the {{Code|HelloWorld}} example into Eclipse:
* File &rarr; Import... &rarr; General &rarr; Existing Projects Into Workspace &rarr; (Next)
* Select {{Code|HelloWorldRemote}} root directory &rarr; Select all files &rarr; Finish
 
Note that the HelloWorld example was written for Android 3.1.  If needed, you can change this in:
(Right Click on Project) &rarr; Properties &rarr; Resource (on left) &rarr; Android
 
To run the example: Right-click on project in Package Explorer (To open the Package Explorer, use Window &rarr; Show View &rarr; Package Explorer)
 
Select Run As... &rarr; Android Application
 
This will bring up the Android Virtual Device manager window.  If your Android hardware is plugged in to your debugging computer, you will see the hardware as an option on which to run the example.  You should run it directly on your Android device, unless you are comfortable setting up the emulator to use your development computer's USB hub.
 
After the {{Code|HelloWorld}} application starts running on your Android device, plug a Phidget into your Android tablet's USB port!
 
Since the USB device requires special permission, the first thing you will probably see is a request from the Phidget example to use the USB port:
 
[[Image:android_helloworld_usb_permissions.png|500px|alt=|link=]]
 
And on your Android device, depending on which Phidget you plug in, you should see something like:
 
[[Image:android_helloworld_hello.png|700px|alt=|link=]]
 
And when you unplug that Phidget from the remote computer, you should see something like this on your Android device:
 
[[Image:android_helloworld_goodbye.png|700px|alt=|link=]]
 
If you have the specific Phidget for the other included Android examples (i.e. the InterfaceKit), you can run the other examples in the same way.
 
If you are having trouble running the examples, a method to debug the Android USB port is on the [[OS - Android]] page, under the Hardware section.
 
====Write Your Own Code====


  @synthesize sensorValueTxt;
To write your own code from scratch, start with an Android project in Eclipse (File &rarr; New &rarr; Android Project).  Then....


</syntaxhighlight></div>
=====Step One: Link the Phidget Libraries to your Project=====


* Also, be sure release the object in the dealloc method [sensorValueTxt release];
When you download and unzip the [http://www.phidgets.com/downloads/examples/android-examples_2.1.8.20120216.tar.gz Phidget Examples for Android], each project folder will (in addition to the project files themselves) contain three things:
* Connect the PhidgetTestAppDelegate class instance to sensorValueTxt.  
# A libs/ folder (containing an armabi/ folder and a single file called libphidget21.so)
# A jar file containing the general Phidget java library (phidget21.jar)
# A jar file for directly driving USB devices from a USB port on the Android device (PhidgetsUSB.jar)


The project now has access to Phidgets and we are ready to begin coding.
Copy the {{Code|libs}} folder, the {{Code|PhidgetsUSB.jar}} file, and the {{Code|phidget21.jar}} file to your project folder.
Please note that the iPhone library also contains a sample skeleton xCode project for iOS.  
This project contains the neccessary project settings for Phidgets development.  
Alternatively, you can use it to start developing with Phidgets.  


===Coding For Your Phidget===
To install libraries to run a Phidget '''remotely''' over a network using the Webservice:
# Add the libs/ folder to your project
#* To add the libs/ folder in Eclipse, simply place it in the root folder of your project
# Add the phidget21.jar file to your project
# Also add the PhidgetsUSB.jar file to your project
#* In Eclipse, to add jar files use the top-bar menu: Project &rarr; Properties &rarr; Java Build Path &rarr; Libraries (tab) &rarr; Add JAR


A Phidget object will need to be declared. For example, we can declare a PhidgetInterfaceKit in the .h header file with:
=====Step Two: Give your Program Permission to use USB=====
<div class="source"><syntaxhighlight lang=objc>


  CPhidgetInterfaceKitHandle ifkit
Add the following to your <code>AndroidManifest.xml</code> file:


<div class="source"><syntaxhighlight lang=xml>
    <uses-feature android:name="android.hardware.usb.host" />
</syntaxhighlight></div>
</syntaxhighlight></div>
 
The object name for any type of Phidget is listed in the API manual.
Every type of Phidget also inherits functionality from the Phidget base class.


===Connecting to the Phidget===
=====Step Three: Include the Phidget Libraries in your Source=====


Next, the Phidget object needs to be initialized and the program needs to try and connect to the Phidget over the WebService through a call to openRemoteIP() or openRemote().
Then, in your code, include an {{Code|import}} reference to the library. In Android Java:
These calls will tell the program to continuously try to connect to a Phidget, based on the parameters given, even trying to reconnect if it gets disconnected.
This means that simply calling open does not guarantee you can use the Phidget immediately.
We can handle this by using event driven programming and tracking the AttachEvents and DetachEvents, or by calling waitForAttachment.
WaitForAttachment will block indefinitely until a connection is made to the Phidget, or an optional timeout is exceeded.
For example, we can connect to a PhidgetInterfaceKit in the .m implementation file with:
 
<div class="source"><syntaxhighlight lang=objc>
   
    @implementation PhidgetTest
    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
    {
        CPhidgetInterfaceKit_create(&ifkit); 
        CPhidget_openRemoteIP((CPhidgetHandle)ifkit, -1, "192.168.2.163", 5001, NULL);
    }
    @end


<div class="source"><syntaxhighlight lang=java>
  // This contains all of the devices and the exceptions
  import com.phidgets.*;
  // This contains all of the event listeners
  import com.phidgets.event.*;
</syntaxhighlight></div>
</syntaxhighlight></div>


The openRemoteIP() and openRemote() calls can be used with parameters to try and get the first device it can find over the network, and open it based on a serial number.  
Then you are ready to begin coding!
The API manual provides more information on openRemoteIP() and openRemote().  
 
One important thing to remember is that when working with Phidgets, a local connection will reserve the device until closed.  
==Follow the Examples==
This prevents any other instances from retrieving data from the Phidget, including other programs.
 
The one connection per device limit does not apply when exclusively using the Phidget Webservice.
By following the instructions above, you probably now have a working example and want to understand it better so you can change it to do what you want. This section has resources for you to learn from the examples and write your own.
At the end of your program, don’t forget to call close to free any locks on the Phidget.
 
Programming with Phidgets in MATLAB makes extensive use of the mainstream Java Phidgets library, so the Java API reference will be helpful:
 
{{UsingAPhidgetInCodeGeneral|although you can only use the event code in Android|[http://www.phidgets.com/documentation/JavaDoc.zip Java API]}}
 
===API Support===
 
Most of the Java API is supported in Android. However, only some of the available open calls are supported:


<div class="source"><syntaxhighlight lang=objc>
When using a Phidget over a network, you can open the remote Phidget using one of the supported Java API calls:
<div class="source"><syntaxhighlight lang=java>
void open(int serial, java.lang.String ipAddress, int port)
void open(int serial, java.lang.String ipAddress, int port, java.lang.String password)
void openAny(java.lang.String ipAddress, int port)
void openAny(java.lang.String ipAddress, int port, java.lang.String password)
void openLabel(java.lang.String label, java.lang.String ipAddress, int port)
void openLabel(java.lang.String label, java.lang.String ipAddress, int port, java.lang.String password)
</syntaxhighlight></div>


  - (void)applicationWillTerminate:(UIApplication *)application
When using a Phidget when it is directly plugged in to an Android 3.1 or later tablet, you can use one of these supported Java API calls:
  {
<div class="source"><syntaxhighlight lang=java>
      CPhidget_close((CPhidgetHandle)ifkit);
void open(int serial)
      CPhidget_delete((CPhidgetHandle)ifkit);
void openAny()
  }
void openLabel(java.lang.String label)
</syntaxhighlight></div>


This leaves these Java API calls, which are '''unsupported''' on Android:
<div class="source"><syntaxhighlight lang=java>
void open(int serial, java.lang.String serverID)
void open(int serial, java.lang.String serverID, java.lang.String password)
void openAny(java.lang.String serverID)
void openAny(java.lang.String serverID, java.lang.String password)
void openLabel(java.lang.String label, java.lang.String serverID)
void openLabel(java.lang.String label, java.lang.String serverID,
java.lang.String password)
</syntaxhighlight></div>
</syntaxhighlight></div>


===Event Driven Programming===
===Code Snippets===


We recommend the use of event driven programming when working with Phidgets.
Specific calls in Android Java will differ in syntax from those on the [[General Phidget Programming]] page, but the concepts stay the same.   
We can hook an event handler at loading with the following code:  


<div class="source"><syntaxhighlight lang=objc>
It may help to have the [[General Phidget Programming]] page and this section open at the same time, because they parallel each other and you can refer to the Android Java syntax.  However, many additional concepts are covered on the General Phidget Programming page on a high level, such as using multiple Phidgets, handling errors, and different styles of programming.


    CPhidgetInterfaceKit_set_OnSensorChange_Handler(ifkit, gotSensorChange, self);
For example, if we were using a [[Product - 1018 - PhidgetInterfaceKit 8/8/8 | Phidget Interface Kit]] as our device, the general calls would look like this:
   
 
====Step One: Initialize and Open====
 
For opening a remote Phidget over the network using the Webservice:
 
<div class="source"><syntaxhighlight lang=java>
  InterfaceKitPhidget device;
  device = new InterfaceKitPhidget();
 
  // Open first detected Interface Kit, remotely with IP address and port
  device.open("192.168.3.33", 5001);
</syntaxhighlight></div>
</syntaxhighlight></div>


Next, the callback method needs to be set up before it can be used. For example,
For opening a Phidget directly attached to the tablet's USB port:
 
 
<div class="source"><syntaxhighlight lang=objc>
<div class="source"><syntaxhighlight lang=java>
 
 InterfaceKitPhidget device;
    int gotSensorChange(CPhidgetInterfaceKitHandle phid, void *context, int ind, int val)
com.phidgets.usb.Manager.Initialize(this);
    {
device = new InterfaceKitPhidget();
        NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
        [(id)context performSelectorOnMainThread:@selector(SensorChange:)
        withObject:[NSArray arrayWithObjects:[NSNumber numberWithInt:ind], [NSNumberGetting_Started_iOS created: 06/16/11 Page 4
        numberWithInt:val], nil] waitUntilDone:NO];
        [pool release];
        return 0;
    }


// Open locally, with Phidget in tablet USB port
 ik.open("192.168.3.33", 5001);
</syntaxhighlight></div>
</syntaxhighlight></div>


Above, the SensorChange method is invoked on the main thread. Event data is stored in a NSArray, which in turn is sent as a single argument to the SensorChange method.  
The direct open call prevents any other instances from retrieving data from the Phidget, including other programs.
The NSAutoreleasePool object is created to clean up released objects on the event thread, and is released at the end of the method.  
The one connection per device limit does not apply when exclusively using the Phidget Webservice.
The SensorChange method is defined as follows:
 
Both open calls will tell the program to continuously try to connect to a Phidget, based on the parameters given, even trying to reconnect if it gets disconnected.
This means that simply calling open does not guarantee you can use the Phidget immediately. We can handle this by using event driven programming and tracking the AttachEvents and DetachEvents....
 
====Step Two: Wait for Attachment (plugging in) of the Phidget====
 
To use the Phidget, it must be plugged in and a software event caught (i.e. attached).  
 
Android Java is '''only''' event-driven, so you cannot use {{Code|waitForAttachment()}} without hanging and being relatively unsafe with your threads.  Instead, you should define an event handler function that you can then synchronize and tie in with the attachment event itself.


<div class="source"><syntaxhighlight lang=objc>
First, let's write our handler:
 
     - (void)SensorChange:(NSArray *)sensorChangeData
<div class="source"><syntaxhighlight lang=java>
     {
  class AttachEventHandler implements Runnable {
        int sensorIndex, sensorValue;
     Phidget device;
        sensorIndex = [[sensorChangeData objectAtIndex:0] intValue];
     TextView eventOutput;
        sensorValue = [[sensorChangeData objectAtIndex:1] intValue];
 
        _sensorValueTxt.text = [NSString stringWithFormat:@"Sensor: %d, Value: %d",
    public AttachEventHandler(Phidget device, TextView eventOutput) {
        sensorIndex, sensorValue]];
      this.device = device;
    }  
      this.eventOutput = eventOutput; }


    public void run() {
      try {
        // The actual useful thing our handler does
eventOutput.setText("Hello " + device.getDeviceName() + ", Serial " + Integer.toString(device.getSerialNumber()));
      } catch (PhidgetException e) { e.printStackTrace(); }
       
      // Notify whoever called us (and is waiting) that we're done
      synchronized(this) { this.notify(); }
    }
  }
</syntaxhighlight></div>
</syntaxhighlight></div>


With this function, the code inside SensorChange will get executed every time the PhidgetInterfaceKit reports a change on one of its analog inputs.
This may seem complex, but really it is just:
Some events such as Attach and Detach belong to the base Phidget object and thus are common to all types of Phidgets. Please refer to the API manual and the iOS examples for a list of events and their usage.
# A class wrapper so we can work independently once we get permission from the main thread, and
# A way to call back to the {{Code|synchronized()}} call to let them know we're done and stay thread safe


===Working directly with the Phidget===
Now that we have our 'handler' we can hook it in as an event function to trigger on device attachment:


Some values can be read and sent directly to the Phidget, simply use the C API functions such as CPhidgetInterfaceKit_getSensorValue for PhidgetInterfaceKits.
<div class="source"><syntaxhighlight lang=java>
 
device.addAttachListener(new AttachListener() {
<div class="source"><syntaxhighlight lang=objc>
  public void attached(final AttachEvent attachEvent) {
    AttachEventHandler handler = new AttachEventHandler(attachEvent.getSource(), eventOutput);


  int sensorIndex = 0;
    // This is synchronised in case more than one device is attached before one completes attaching
  int sensorValue;
    synchronized(handler) {
  CPhidgetInterfaceKit_getSensorValue(ifkit, sensorIndex, &sensorValue);
 
  _sensorValueTxt.text = [NSString stringWithFormat:@"Sensor: %d, Value: %d",
      runOnUiThread(handler);
  sensorIndex, sensorValue]];
      try { handler.wait(); } catch (InterruptedException e) { e.printStackTrace(); }
    }
  }
});  
</syntaxhighlight></div>
</syntaxhighlight></div>
   
These functions can be used inside a polling loop as an alternative to event driven programming.


===Working with multiple Phidgets===
====Step Three: Do Things with the Phidget====


Multiple Phidgets of the same type can easily be run inside the same program.  
Again, because Android is event driven, use buttons (or timers) to schedule events if you want to poll the device at a certain interval or user specification. Otherwise, simply set the sensitivity and/or data rate (depending on your device type) and catch events as they come in using the handler structure above.
In our case, it  requires another InterfaceKit instance to be defined and initialized.
The new instance can then be set up, opened and used in the same process as the previous one.
If the application needs to distinguish between the devices, open can be called with the serial number of a specific Phidget.


===Other Phidgets===
====Step Four: Close and Delete====


The design given in this document can also be followed for almost all Phidgets.  
At the end of your program, don’t forget to call close to free any locks on the Phidget.
For example, if you were using a PhidgetRFID instead of an PhidgetInterfacekit, you would declare an RFID object instead of an InterfaceKit. The methods and events available would change but they can be accessed in a similar manner.  
 
We can put the close() call for Phidgets in Android within an overridden version of the onDestroy() Android application function.  Within it, we simply close the device. For Phidgets directly attached to a USB Android tablet, you should also call Uninitialize():
 
<div class="source"><syntaxhighlight lang=java>
  @Override
  protected void onDestroy() {
    super.onDestroy();
      try { device.close(); } catch (PhidgetException e) { e.printStackTrace(); }
      // Uninitialize should only be called for directly connected Phidgets
      com.phidgets.usb.Manager.Uninitialize();
  }   
</syntaxhighlight></div>


==Building your Project==
The ''complete'' set of functions you have available for all Phidgets can be found in the [http://www.phidgets.com/documentation/JavaDoc.zip Java API].  You can also find more description on any device-specific function either in the [[Device List|Device API]] page for calls available only on your specific Phidget.
Describe the different ways a project could be built using this language.


==Common Problems and Solutions/Workarounds==
==Common Problems and Solutions/Workarounds==
Here you can put various frequent problems and our recommended solutions.

Revision as of 19:09, 11 April 2012

Icon-iOS.png application are built using the Cocoa Touch framework and the Objective C programming language, both developed by Apple.


Introduction

If this is your first time working with a Phidget, we suggest starting with the Getting Started page for your specific device. This can be found in the user guide for your device. That page will walk you through installing drivers and libraries for your operating system, and will then bring you back here to use Android specifically.

Android is capable of using nearly the complete Phidget API, including events, and only excepting a few open() calls outlined later. We also provide example code in Android for the Phidget Interface Kit and two Hello World examples.

Android can be developed with Eclipse on Windows, Mac OS, and Linux.

You can compare Android with our other supported languages.

Quick Downloads

Just need the Android documentation, drivers, libraries, and examples? Here they are:

Documentation

Example Code

Libraries and Drivers


Getting Started with Android Java (Eclipse)

If you are new to writing code for Phidgets, we recommend starting by running, then modifying existing examples. This will allow you to:

  • Make sure your libraries are properly linked
  • Go from source code to a test application as quickly as possible
  • Ensure your Phidget is hooked up properly

As Android development is primarily done on Eclipse, and Eclipse is relatively platform-independent, we provide instructions for Eclipse rather than by operating system.

For basic differences on installing and setting up Eclipse on your development system, you can try the Android Operating System page. However, your best bet for information about general use of Eclipse on your development operating system (Windows, Mac, or Linux) will be the Eclipse support page or the Internet at large.

Phidgets can run directly plugged in to Android devices with a USB port and system 3.1 or later.

Otherwise, Android can control a Phidget remotely over a network, by using the Phidget Webservice

Hence, we split instructions up by Android OS version number.

Android Under 3.1 (and/or no USB Port)

These types of phones and tablets can use Phidgets only remotely over a network using the Phidget Webservice.

Use Our Examples

Download and unpack the Phidget Examples for Android. There are two Hello World examples: HelloWorldRemote (the one you want), and HelloWorld (for tablets with a USB port).

Import the HelloWorldRemote example into Eclipse:

  • File → Import... → General → Existing Projects Into Workspace → (Next)
  • Select HelloWorldRemote root directory → Select all files → Finish

Next, you must change the IP address within the example code to the IP address of the computer directly connected to the Phidget you are trying to control. This happens on the line that says something like:

device.open("192.168.3.133", 5001);

Also, note that the HelloWorldRemote example was written for Android 2.1. If needed, you can change this in: (Right Click on Project) → Properties → Resource (on left) → Android

To run the example: Right-click on project in Package Explorer (To open the Package Explorer, use Window → Show View → Package Explorer)

Select Run As... → Android Application

This will bring up the Android Virtual Device manager window. If your Android hardware is plugged in to your debugging computer, you will see the hardware as an option on which to run the example. You should run it directly on your Android device, unless you are comfortable setting up the emulator to run on your local network.

After the HelloWorldRemote application starts running on your Android device:

  1. Make sure the Phidget Webservice is running on the computer with the IP address you put into the code
  2. Plug a Phidget into that computer

And on your Android device, depending on which Phidget you plug in, you should see something like:

And when you unplug that Phidget from the remote computer, you should see something like this on your Android device:

If you have the specific Phidget for the other included Android examples (i.e. the InterfaceKit), you can run the other examples in the same way.

To envision the system in the background, you can refer to the Webservice section on the OS - Android page.

Write Your Own Code

To write your own code from scratch, start with an Android project in Eclipse (File → New → Android Project). Then....

Step One: Link the Phidget Libraries to your Project

When you download and unzip the Phidget Examples for Android, each project folder will (in addition to the project files themselves) contain three things:

  1. A libs/ folder (containing an armabi/ folder and a single file called libphidget21.so)
  2. A jar file containing the general Phidget java library (phidget21.jar)
  3. A jar file for directly driving USB devices from a USB port on the Android device (PhidgetsUSB.jar)

Copy the libs folder, the PhidgetsUSB.jar file, and the phidget21.jar file to your project folder.

To install libraries to run a Phidget remotely over a network using the Webservice:

  1. Add the libs/ folder to your project
    • To add the libs/ folder in Eclipse, simply place it in the root folder of your project
  2. Add the phidget21.jar file to your project
    • In Eclipse use the top-bar menu: Project → Properties → Java Build Path → Libraries (tab) → Add JAR
Step Two: Give your Program Permission to use the Internet

Add the following to your AndroidManifest.xml file:

    <uses-permission android:name="android.permission.INTERNET"></uses-permission>
Step Three: Include the Phidget Libraries in your Source

Then, in your code, include an import reference to the library. In Android Java:

  // This contains all of the devices and the exceptions
  import com.phidgets.*;
 
  // This contains all of the event listeners
  import com.phidgets.event.*;

Then you are ready to begin coding!

Android 3.1+ with USB Port

If your tablet has a USB host port and is running Android 3.1 or later, you can plug Phidgets directly into it.

Use Our Examples

Download and unpack the Phidget Examples for Android. There are two Hello World examples: HelloWorld (the one you want), and HelloWorldRemote (for controlling Phidgets over the Webservice).

Import the HelloWorld example into Eclipse:

  • File → Import... → General → Existing Projects Into Workspace → (Next)
  • Select HelloWorldRemote root directory → Select all files → Finish

Note that the HelloWorld example was written for Android 3.1. If needed, you can change this in: (Right Click on Project) → Properties → Resource (on left) → Android

To run the example: Right-click on project in Package Explorer (To open the Package Explorer, use Window → Show View → Package Explorer)

Select Run As... → Android Application

This will bring up the Android Virtual Device manager window. If your Android hardware is plugged in to your debugging computer, you will see the hardware as an option on which to run the example. You should run it directly on your Android device, unless you are comfortable setting up the emulator to use your development computer's USB hub.

After the HelloWorld application starts running on your Android device, plug a Phidget into your Android tablet's USB port!

Since the USB device requires special permission, the first thing you will probably see is a request from the Phidget example to use the USB port:

And on your Android device, depending on which Phidget you plug in, you should see something like:

And when you unplug that Phidget from the remote computer, you should see something like this on your Android device:

If you have the specific Phidget for the other included Android examples (i.e. the InterfaceKit), you can run the other examples in the same way.

If you are having trouble running the examples, a method to debug the Android USB port is on the OS - Android page, under the Hardware section.

Write Your Own Code

To write your own code from scratch, start with an Android project in Eclipse (File → New → Android Project). Then....

Step One: Link the Phidget Libraries to your Project

When you download and unzip the Phidget Examples for Android, each project folder will (in addition to the project files themselves) contain three things:

  1. A libs/ folder (containing an armabi/ folder and a single file called libphidget21.so)
  2. A jar file containing the general Phidget java library (phidget21.jar)
  3. A jar file for directly driving USB devices from a USB port on the Android device (PhidgetsUSB.jar)

Copy the libs folder, the PhidgetsUSB.jar file, and the phidget21.jar file to your project folder.

To install libraries to run a Phidget remotely over a network using the Webservice:

  1. Add the libs/ folder to your project
    • To add the libs/ folder in Eclipse, simply place it in the root folder of your project
  2. Add the phidget21.jar file to your project
  3. Also add the PhidgetsUSB.jar file to your project
    • In Eclipse, to add jar files use the top-bar menu: Project → Properties → Java Build Path → Libraries (tab) → Add JAR
Step Two: Give your Program Permission to use USB

Add the following to your AndroidManifest.xml file:

    <uses-feature android:name="android.hardware.usb.host" />
Step Three: Include the Phidget Libraries in your Source

Then, in your code, include an import reference to the library. In Android Java:

  // This contains all of the devices and the exceptions
  import com.phidgets.*;
 
  // This contains all of the event listeners
  import com.phidgets.event.*;

Then you are ready to begin coding!

Follow the Examples

By following the instructions above, you probably now have a working example and want to understand it better so you can change it to do what you want. This section has resources for you to learn from the examples and write your own.

Programming with Phidgets in MATLAB makes extensive use of the mainstream Java Phidgets library, so the Java API reference will be helpful:

  • Java API (This is the complete set of functions you have available for all Phidgets)
  • Device Specific APIs - The one for your Phidget can be found in its user guide.

To learn the details behind opening, configuring, using, and closing your Phidget, try the General Phidget Programming page. That page also describes using the Phidget in an event-driven manner and in a traditional manner, although you can only use the event code in Android.

API Support

Most of the Java API is supported in Android. However, only some of the available open calls are supported:

When using a Phidget over a network, you can open the remote Phidget using one of the supported Java API calls:

void open(int serial, java.lang.String ipAddress, int port)
void open(int serial, java.lang.String ipAddress, int port, java.lang.String password)
void openAny(java.lang.String ipAddress, int port)
void openAny(java.lang.String ipAddress, int port, java.lang.String password)
void openLabel(java.lang.String label, java.lang.String ipAddress, int port)
void openLabel(java.lang.String label, java.lang.String ipAddress, int port, java.lang.String password)

When using a Phidget when it is directly plugged in to an Android 3.1 or later tablet, you can use one of these supported Java API calls:

void open(int serial)
void openAny()
void openLabel(java.lang.String label)

This leaves these Java API calls, which are unsupported on Android:

void open(int serial, java.lang.String serverID)
void open(int serial, java.lang.String serverID, java.lang.String password)
void openAny(java.lang.String serverID)
void openAny(java.lang.String serverID, java.lang.String password)
void openLabel(java.lang.String label, java.lang.String serverID)
void openLabel(java.lang.String label, java.lang.String serverID,
java.lang.String password)

Code Snippets

Specific calls in Android Java will differ in syntax from those on the General Phidget Programming page, but the concepts stay the same.

It may help to have the General Phidget Programming page and this section open at the same time, because they parallel each other and you can refer to the Android Java syntax. However, many additional concepts are covered on the General Phidget Programming page on a high level, such as using multiple Phidgets, handling errors, and different styles of programming.

For example, if we were using a Phidget Interface Kit as our device, the general calls would look like this:

Step One: Initialize and Open

For opening a remote Phidget over the network using the Webservice:

  InterfaceKitPhidget device;
  device = new InterfaceKitPhidget();
 
  // Open first detected Interface Kit, remotely with IP address and port
  device.open("192.168.3.33", 5001);

For opening a Phidget directly attached to the tablet's USB port:

 InterfaceKitPhidget device;
 com.phidgets.usb.Manager.Initialize(this);
 device = new InterfaceKitPhidget();

 // Open locally, with Phidget in tablet USB port
 ik.open("192.168.3.33", 5001);

The direct open call prevents any other instances from retrieving data from the Phidget, including other programs. The one connection per device limit does not apply when exclusively using the Phidget Webservice.

Both open calls will tell the program to continuously try to connect to a Phidget, based on the parameters given, even trying to reconnect if it gets disconnected. This means that simply calling open does not guarantee you can use the Phidget immediately. We can handle this by using event driven programming and tracking the AttachEvents and DetachEvents....

Step Two: Wait for Attachment (plugging in) of the Phidget

To use the Phidget, it must be plugged in and a software event caught (i.e. attached).

Android Java is only event-driven, so you cannot use waitForAttachment() without hanging and being relatively unsafe with your threads. Instead, you should define an event handler function that you can then synchronize and tie in with the attachment event itself.

First, let's write our handler:

  class AttachEventHandler implements Runnable { 
    Phidget device; 
    TextView eventOutput;

    public AttachEventHandler(Phidget device, TextView eventOutput) {
      this.device = device;
      this.eventOutput = eventOutput; }

    public void run() {
      try {
        // The actual useful thing our handler does
	eventOutput.setText("Hello " + device.getDeviceName() + ", Serial " + Integer.toString(device.getSerialNumber()));
      } catch (PhidgetException e) { e.printStackTrace(); }
        
      // Notify whoever called us (and is waiting) that we're done
      synchronized(this) { this.notify(); }
    }
  }

This may seem complex, but really it is just:

  1. A class wrapper so we can work independently once we get permission from the main thread, and
  2. A way to call back to the synchronized() call to let them know we're done and stay thread safe

Now that we have our 'handler' we can hook it in as an event function to trigger on device attachment:

device.addAttachListener(new AttachListener() {
  public void attached(final AttachEvent attachEvent) {
    AttachEventHandler handler = new AttachEventHandler(attachEvent.getSource(), eventOutput);

    // This is synchronised in case more than one device is attached before one completes attaching
    synchronized(handler) {

      runOnUiThread(handler);
      try { handler.wait(); } catch (InterruptedException e) { e.printStackTrace(); }
    }
  }
});

Step Three: Do Things with the Phidget

Again, because Android is event driven, use buttons (or timers) to schedule events if you want to poll the device at a certain interval or user specification. Otherwise, simply set the sensitivity and/or data rate (depending on your device type) and catch events as they come in using the handler structure above.

Step Four: Close and Delete

At the end of your program, don’t forget to call close to free any locks on the Phidget.

We can put the close() call for Phidgets in Android within an overridden version of the onDestroy() Android application function. Within it, we simply close the device. For Phidgets directly attached to a USB Android tablet, you should also call Uninitialize():

  @Override
  protected void onDestroy() {
    super.onDestroy();
      try { device.close(); } catch (PhidgetException e) { e.printStackTrace(); }
      // Uninitialize should only be called for directly connected Phidgets
      com.phidgets.usb.Manager.Uninitialize();
  }

The complete set of functions you have available for all Phidgets can be found in the Java API. You can also find more description on any device-specific function either in the Device API page for calls available only on your specific Phidget.

Common Problems and Solutions/Workarounds