Tuesday, July 10, 2012

UPnP Android stack

In this tutorial I will try to cover the basics steps of implementing an UPnP control point in an Android application. By doing this we can discover/integrate/control UPnP devices in our local area network. This tutorial focuses on discovering one UPnP device, invoking a control event on this device and handeling the callback event coming from the device.

Final result

What is UPnP 

For a better understanding of what Universal Plug and Play is you shoud visit the websites Wikipedia  and UPnP.org.


Requirements

Eclipse + Android SDK

You should have a eclipse environment installed for Android development

UPnP Developer tools by intel

By using the developer tools delivered by intel, setting up and testing with the UPnP protocol isn't that dificult. To get started download the developer tools from the intel website:
Watch the following tutorials regarding the tools:

Tutorial

Control UPnP devices with developer tools

Now that we have had a simple introduction to UPnP-developer tools it's time to start working. First we need to start spying the network for UPnP-traffic. Device spy lists all UPnP enabled devices of your local area network. You can invoke events on these devices by opening an service in the treeview and double clicking an function (e.g. SetTarget). 

Open the Device Spy:
  • Start > Programs > Developer tools for UPnP technology > Device Spy

Create an UPnP-device

Open the Network Light:
  • Start > Programs > Developer tools for UPnP technology > Netwok Light

We are using the Network Light from the developer tools as our endpoint in this setup. Intel's Network Light is a virtual lightbulb that can be enabled, disabled and dimmed.Verify that the network light is listed in the device spy. Play around with the network light from the device spy, for example you can enable/disable the lightbulb by invoking the setTarget(True) and setTarget(False) function.

For more information on the Network Light module you can take a look at:
standardizeddcps/Lighting Controls_1/UPnP-ha-DimmableLight-v1-Device*.pdf


Generate the UPnP-stack for our application

Open Device Builder:
  • Start > Programs > Developer tools for UPnP technology > Device Builder
Do the following actions:

  • File > Open from network...
    • Select Network Light 
    • Click ok
  • Select Network Light in the main window
    • Open the Configuration tab
      • alter the Generation type to Control Point
  • File > Generate stack...
    • Change the following values to
      • Target Platform : Java Stack - Android
      • Project Name : LightSwitch
      • Output Path : C:\upnp
      • Package : be.tvn.dev.upnp.lightswitch
These actions will generate the source code of an Android application which developers can use to make their own Android applications.


Listing generated files

the following java files are generated in the package  "be.tvn.dev.upnp.lightswitch" :
  • - CpDimming.java 
    • Resembles the service : um:schemas-upnp-org:service:Dimming:1
  • - CpSwitchPower.java
    • Resembles the service :  um:schemas-upnp-org:service:SwitchPower:1
  • - LightSwitch.java
    • MainActivity of our Android project


Import the generated code into Eclipse

  • File > Import > General tab > Existing Projects into Workspace
    • Select upnp as your root directory
    • Verify that LightSwitch-project is checked
    • Click Finish


Resolve Eclipse errors

Move the UPnP library to the libs folder
  • Right click project > New > Folder > Folder name : libs
  • Copy and paste UPnPLibrary.jar from the root folfer to the libs folder
  • Verify that UPnPLibrary.jar is referenced
Remove @Override annotations
  • Ctrl + F and Replace All
Fix project properties
  • Right click project > Android Tools > Fix Project Properties
Clean project
  • Project > Clean...


Run your application

If all errors are removed from the package explorer it's time to start running the application. Before continuing we should enable WiFi on our Android phone and enable debug information on the Network Light.
  • Network Light > right click > Debug information
    • enable debug information by clicking the green/orange/red icons
  • Eclipse > right click project > Run as > Android Application
When the application is installed you should see 2 buttons on the screen. One for starting the NetworkLight server and one for stopping the NetworkLight server. If you press the start button you should see the following debug information appear in the debug dialog.




Adding functionality to the Android application

Now that we can integrate with the Network Light is time to start adding buttons to toggle the bulb on & off. To accomplish this we only need to edit 2 files:
  • main.xml
  • LightSwitch.java

Add a button to our main.xml file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="@string/hello"
    />
<Button android:text="Start Device" android:id="@+id/Button01" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
<Button android:text="Stop Device" android:id="@+id/Button02" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
<Button android:text="Toggle on/off" android:id="@+id/lightswitch" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>

</LinearLayout>


Add new variables to our LightSwitch.java variables
public class LightSwitch extends Activity 
{
 
 private UPnPControlPoint mCP1;

 // BUTTON
 private Button toggleButton;
 
 // UPNP 
 private CpSwitchPower.InvokeHandler mCpSwitchPowerInvokeHandler;
 private CpSwitchPower mCpSwitchPower;
 private Object mCpSwitchPowerObject;

 ...

}
Reference button and add onClickListener to the button in onCreate-function
/** Called when the activity is first created. */
    
    public void onCreate(Bundle savedInstanceState) 
    {
        // ONCREATE AND CONTENTVIEW
        // START AND STOP BUTTONS
        ...
                
        // FIND REFERENCE TO BUTTON
        toggleButton = (Button)findViewById(R.id.lightswitch);
        
        // DISABLE BUTTON UNTIL INITIATED BY SERVICE
        toggleButton.setEnabled(false);
        
        // DEFINE ONCLICK EVENT
        toggleButton.setOnClickListener(new OnClickListener() {
   
    public void onClick(View v) {
        if((Boolean)v.getTag()){
        // lightbulb is on -> switch off
        mCpSwitchPower.action_SetTarget.Invoke(false, mCpSwitchPowerObject, mCpSwitchPowerInvokeHandler);
       }else{
        // lightbulb is off -> switch on
        mCpSwitchPower.action_SetTarget.Invoke(true, mCpSwitchPowerObject, mCpSwitchPowerInvokeHandler);
       }
       // DISABLE BUTTON UNTIL CALLBACK
             v.setEnabled(false);
    }
   });

    }



Change implementation of OnAddedDevice(UPnPDevice device)-function
       public void OnAddedDevice(UPnPDevice device)
       {
        //STORE REFERENCE OF INVOKE HANDLER
        mCpSwitchPowerInvokeHandler = mHandler_SwitchPower;
        
        // INITIATE SERVICE
           UPnPService service;
           service = device.GetService(CpSwitchPower.ServiceType).get(0);
           service.userObject = new CpSwitchPower(service);
           ((CpSwitchPower)service.userObject).LoadSCPD(null, new CpSwitchPower.LoadedSCPDHandler()
           {
   /** Called when service is initated */   
   public void OnCpSwitchPower_LoadedSCPD(CpSwitchPower sender,boolean success, Object userObject) {    
    // STORE REFERENCE TO UPNP OBJECTS
    mCpSwitchPower = sender;
    mCpSwitchPowerObject = userObject;
    // GET INITIAL STATE OF LIGHTBULB 
    mCpSwitchPower.action_GetTarget.Invoke(mCpSwitchPowerObject, mCpSwitchPowerInvokeHandler);
   }
           });
       }
Change implementation of mHandler_SwitchPower
CpSwitchPower.InvokeHandler mHandler_SwitchPower = new CpSwitchPower.InvokeHandler()
       {
           
           public void OnGetStatus(int errorCode, boolean ResultStatus, Object userState)
           {
           }
           
           public void OnGetTarget(int errorCode, boolean newTargetValue, Object userState)
           {
             final boolean value = newTargetValue;
             runOnUiThread(new Runnable() {
               public void run() {
                 // store state of lightbulb 
                 toggleButton.setTag(value);
                 // enable button
                 toggleButton.setEnabled(true);
               }
             });
           }
           
           public void OnSetTarget(int errorCode, Object userState)
           {
              runOnUiThread(new Runnable() { 
                public void run() {
                  // switch state of lightbulb
                  Boolean isOn = ((Boolean)toggleButton.getTag() == true) ? false : true;
                  // store state of lightbulb
                  toggleButton.setTag(isOn);
                  // enable button
                  toggleButton.setEnabled(true);
                }
              });
           }
       };

Resolve small errors and run application



Download


NOTES

  • This example doesn't handle error codes
    • Your application should manage error codes
  • This example mimics a situation with one particular UPnP-device.
    • Your application should have the possibility to manage more than one device
  • This example ignores the state of a service
    • Your application should manage state of services
    • Your application should check services before invoking functions
  • This example implements one of the two services available in the Network Light

3 comments: