Creating AIR Native Extensions for BlackBerry PlayBook

The PlayBook NDK 1.0 was released at BlackBerry DevCon Americas 2011 this week and with it comes the ability to create AIR Native Extensions. AIR Native Extensions is one of the big features available in AIR 3.0 on all other platforms. However, Native Extensions have been available in the AIR Runtime on the PlayBook since it launched. So when developing your application and your ANE, it is not necessary to target AIR 3.0. You can target AIR 2.7 and the BlackBerry Tablet OS 1.0.7 if you like.

Pre-requisites

In order to create an ANE you will need to download and install the following tooling.

PlayBook NDK 1.0https://bdsc.webapps.blackberry.com/native/
Once installed, this is what you will use to develop the native portion of our ANE.

Flash Builder 4.6 public pre-release – http://adobe.ly/qGRD3d
The current release version of Flash Builder, 4.5.1, does not contain support for ANE development. It is possible to use it with lots of work arounds, but it is better to simply sign up for the pre-release of 4.6.

Currently Flash Builder 4.6 only comes with the Flex 4.6 SDK, which requires you to have AIR 3.1, even if you are only creating an ActionScript project. So to get around this, I would recommend copying the 4.5.1 SDK from your Flash Builder 4.5/sdks folder before un-installing it and installing Flash Builder 4.6. This will allow you to develop ANE’s and target AIR 2.7.

Or you can download the latest Flex 4.5.1 SDK from the Flex open source site here. http://opensource.adobe.com/wiki/display/flexsdk/Download+Flex+4.5 You will then need to download the AIR SDK and overlay it on top of the Flex SDK.
AIR SDK download – http://www.adobe.com/special/products/air/sdk/
Overlay instructions – http://kb2.adobe.com/cps/495/cpsid_49532.html

Hopefully that wasn’t too painful to get up and running and as more of these tools get officially released it will become easier.

Source code for the native and ActionScript implementations as well as a sample application can be downloaded here.

Developing the native library

Before you can start coding the native side there are a couple of things that are required in order to set up your project correctly.

First create a new project.
File > New > BlackBerry Tablet OS C/C++ Project


After you create name for you project you will be asked to select what type of project to create. Make sure to select Shared Library > Empty Project.

When you press Finish your project will be created. Once created select Project > Properties.

The Project Properties dialog is presented and we need to add the AirStub library to your build configuration.
1. Select C/C++ Build > Settings from the left menu.
2. Select QCC Linker > Libraries
3. Click the “+” Button in the Libraries Section.
4. Enter “AirStub” into the prompt.


You will need to do this to every Build Configuration you plan on using. To add the AirStub library to another configuration, select it from the Configuration drop down at the top of the dialog.

With that your project is ready to start coding. Create a new Source File and name it main.c, or something similar.

Throughout this article I will explain some of the native code, as we show some simple examples of how to interact with native code. For more information on all of the C methods read through the documentation on Adobe’s web site. http://help.adobe.com/en_US/air/extensions/index.html

You can also look through the FlashRuntimeExtensions.h header file to find all of the methods and properties.

I have attached a sample project that with this article and in the next section will explain the pieces of it.

Initializing the extension

void ExtInitializer(void** extDataToSet, FREContextInitializer* ctxInitializerToSet,
FREContextFinalizer* ctxFinalizerToSet) {
*extDataToSet = NULL;
*ctxInitializerToSet = &ContextInitializer;
*ctxFinalizerToSet = &ContextFinalizer;
}

The ExtInitializer method is called when your extension is initialized by your application. The method can be called whatever you want and is defined later on. However, the method signature must match the FREInitializer(). For more info check out the documentation here http://help.adobe.com/en_US/air/extensions/WSb464b1207c184b141a93a0d1129383bfc42-8000.html

This method sets pointers to the ContextInitializer and ContextFinalizer methods. Next let’s have a look at the ContextInitializer.

void ContextInitializer(void* extData, const uint8_t* ctxType,
FREContext ctx, uint32_t* numFunctionsToSet,
const FRENamedFunction** functionsToSet)
{
static FRENamedFunction s_classMethods[] =
{
{(const uint8_t *)"helloNative", NULL, helloNative},
{(const uint8_t *)"getElementAt", NULL, getElementAt},
{(const uint8_t *)"updateBitmap", NULL, updateBitmap},
};
const int c_methodCount = sizeof(s_classMethods) / sizeof(FRENamedFunction);
 
// Update caller with the required data
*functionsToSet = s_classMethods;
*numFunctionsToSet = c_methodCount;
}

Your context initializer method can be called anything as long as it matches the FREContextInitializer(). For more information have a look at the documentation here.
http://help.adobe.com/en_US/air/extensions/WSb464b1207c184b14-62b8e11f12937b86be4-7ffd.html

The purpose of this method is to set up a mapping to all of your methods that will be called from ActionScript. In our example we have 3 methods, helloNative, getElementAt, and updateBitmap. The first argument in the s_classMethods elements is the string that will be used to call the method from ActionScript. You will see how this works later on when we look at developing the ActionScript side.

The third argument is a reference to the native method. Although these 2 names can be different, it is best practice to keep them the same.

Once your methods are defined, update the pointers that where passed in to the function with the methods and the method count.

Before we look at the implementation of the native methods lets quickly take a look at the finalizer methods.

void ContextFinalizer(FREContext ctx) {
return;
}

When your extension context is unloaded the above method will be called. This is the opportunity to do any cleanup and dispose of any objects in your extension.

Creating native methods

Now that our methods are defined in our context initializer let’s create the native methods. All of the methods need to have the same method signature – FREFunction() – http://help.adobe.com/en_US/air/extensions/WSb464b1207c184b14-62b8e11f12937b86be4-7ffa.html

Here is what our helloNative method looks like.

FREObject helloNative(FREContext ctx, void* functionData, uint32_t argc, FREObject argv[]);

The first argument, FREContext ctx, is the context of the extension.
The second argument, void* functionData, is native data passed to the method. When setting up a mapping of the methods in the context initializer, the second parameter of the object was NULL. You could have created some data and had it passed in as this argument to our function.
The third argument, uint32_t argc, is the number of arguments passed from ActionScript.
The fourth argument, FREObject argv[], is an array of all the arguments passed from ActionScript.

The FREObject represents any ActionScript object of any data type. Every object passed from ActionScript will be of this type and every object returned from native to ActionScript must be of this type. You can see that the method signature for the method returns an FREObject. It is up to the native code to convert an FREObject into a native data type so it can work with it. Fortunately there are a number of methods to help with this. Here is a list of them and based on the name it should be fairly straightforward what does what.

FREGetObjectAsInt32 ( FREObject object, int32_t  *value );
FREGetObjectAsUInt32( FREObject object, uint32_t *value );
FREGetObjectAsDouble( FREObject object, double   *value );
FREGetObjectAsBool  ( FREObject object, uint32_t *value );
FREGetObjectAsUTF8( FREObject object, uint32_t* length,const uint8_t** value );

Suppose the first argument passed into your method was an int. You would do the following to convert the value.

int32_t index;
FREGetObjectAsInt32( argv[ 0 ], &index );

Setting a native data type to an FREObject to return to ActionScript is pretty much the same, but the reverse. You can see an example of this in the implementation of the helloNative method.

const char *out = "Hello Native\n";
FREObject result;
FRENewObjectFromUTF8((uint32_t)(strlen(out) + 1), (uint8_t*) out, &result);

These few simple concepts are the basics for creating native methods for ActionScript to call. The getElementAt() method shows how to easily access elements in an Array using native methods. The updateBitmap() method shows how to modify a BitmapData object from ActionScript and have it re-drawn with the new values. These examples should get you started on creating the native code for your ANE.

Coding the ActionScript implementation

Included in the sample there is a Flash Builder 4.6 Flex Library project called firstane. This project includes the ActionScript implementation of our ANE. The FirstANE class has 3 methods that mimic our native methods. It is good practice to do this whenever possible so methods are easy to map across the 2 code bases.

Creating the extension context

In the constructor of the class we create a reference in ActionScript to our extension context.

ext = ExtensionContext.createExtensionContext( "qnx.extensions.FirstANE", null );

The first argument is the ID of the extension. This can be anything you like, but should be something that is unique to you. Reverse domain is always a great standard. Later in this article we’ll show where to define this.

The second argument is an optional context type. This is passed to the context initialization method so that the native code can initialize different implementation based on a context. Most extensions will not require this, but more complicate extensions it may be useful.

Once we have a reference to the extension, native methods are now available to be called. Calling native methods are really simple. If we have a look at the getElementAt() method it shows how to call a native method with arguments and return the result from the native code.

public function getElementAt( items:Array, index:int ):String
{
return( ext.call( "getElementAt", items, index ) as String );
}

To call any native method the ExtensionContext.call() method is used – http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/external/ExtensionContext.html#call()

The first parameter is the string that you used in the context initializer. This is the method that we are going to call.

The second and third parameters are arguments that are passed to the native method.

The returned value of the call() method is the value returned from the native method. Because this could be any data type, it is necessary to cast it to the type that the method is expecting.

Defining the extension

In the bin folder of the firstane project there is an extension.xml file. This is the file that is used to define the extension. Here is what it looks like.

<extension xmlns="http://ns.adobe.com/air/extension/2.5">
    <id>qnx.extensions.FirstANE</id>
    <versionNumber>1</versionNumber>
    <platforms>
        <platform name="QNX-ARM">
           <applicationDeployment> 
		<nativeLibrary>libfirstane.so</nativeLibrary> 
		<initializer>ExtInitializer</initializer>
	          	<finalizer>ExtFinalizer</finalizer>
	</applicationDeployment>
        </platform>
    </platforms>
</extension>

The node is the root node and the version at the end must be 2.5. This value is not the same as the AIR Runtime version you are targeting. Even if your application is targeting AIR 3.0, the extension namespace must be http://ns.adobe.com/air/extension/2.5.

The node is extension id is defined. This is the same value that is passed into the ExtensionContext.createExtensionContext() method in ActionScript.

The is the version number of your extension.

The node is a list of nodes that define all of the platforms the extension supports.

The BlackBerry PlayBook supports 2 platforms, QNX-ARM for the PlayBook hardware, and QNX-x86 for the PlayBook Simulator.

One thing that is a really good idea is to implement a default platform for when application runs on a platform that is not supported. For, example you may create native libraries for both the PlayBook device and simulator, but what happens when you want to test your application locally on your development machine. If the API’s only exist on the PlayBook platforms your application will not run locally on Windows or OSX. To accomplish this you can create a “default” platform that is ActionScript only. This allows you to implement default behavior for your API and allow you to fail gracefully or provide alternate implementations.

For more details on the extension descriptor file check out the Adobe documentation here. http://help.adobe.com/en_US/air/extensions/WS901d38e593cd1bac-3004221412afa24c001-8000.html

Compiling the extension

In order to compile the extension you must use the adt command line tool that comes with the AIR SDK.

First you must un-zip the firstane.swc. SWC files are simply zip files that contain a library.swf and a catalog.xml. You will need the library.swf to be compiled with each platform, and it must be named library.swf. You can dispose the catalog.xml file, as it is not needed.

To make life easier I have placed the firstane.so, firstane.swc, library.swf, and extension.xml all in the same directory. Here is the command to compile your ane.

adt –package –target ane firstane.ane extension.xml –swc firstane.swc –platform QNX-ARM –C . firstane.so library.swf

For BlackBerry PlayBook ANE files it is not necessary to sign them and is optional.

Using a ANE

In order to use an ANE, it is best to simply follow the instructions in the Flash Builder 4.6 pre-release site. The only difference for the BlackBerry platform is an additional permission is needed in the apps blackberry-tablet.xml file.

run_air_native

Included in the source is a Flash Builder project called firstaneapp that shows how to use the application. You will most likely have to fix the path to the .ane in the project file, but it should give you an idea on how to use it.

Conclusion

Hopefully this gets you started in creating ActionScript Native Extensions for the BlackBerry PlayBook. All of the C API documentation from Adobe on ANE’s applies to the PlayBook. With all of the documentation out there, this article and the sample projects, hopefully it gets you well under way.

Continue reading » · Rating: · Written on: 10-25-11 · 7 Comments »

Sparkfun’s 7-Segment Red 6.5″ Display and Arduino

A little while ago I purchased 10 of Sparkfun’s 7-segment red 6.5″ displays.

http://www.sparkfun.com/commerce/product_info.php?products_id=8530

I had been wanting to purchase them for quite some time but they had been out of stock. When I was finally notified that they had received more I instantly bought them, without really thinking what I was going to use them for. Once they arrived I quickly opened them up and saw that it was going to be a little bit more of a challenge then I originally thought it would be. And I also thought they would come with some fancy schematic that I could just follow, but they didn’t.

So the first step was just to try and get a segment to light up by just supplying power. The digits use a common anode, which means it has one lead connection and 7 ground connection for each segment. So I started running it through a 5v power supply with not luck. Then a 9v, still no luck. Finally 12v did the trick. After I soldered wires to all of the connection I was able to get all 7 segments to light up by just running the common anode to the power and each segment to a ground.

Ok so step one complete now to try and get it talking with Arduino. Now I wasn’t really sure how to go about doing this since each segment was connected to a ground. So I started digging around on the Arduino forums and found some similar posts on what I was trying to do. My conclusion was that I need to get a shift register to turn each segment on and off. I found some people who had some luck with this display and the Allegro 6278EAT. You can pick some up for $1.55 at Digi Key. There are lots of different LED drivers out there but the reason I chose this one was because I needed to supply 12v to my displays and it sounded like some of the others that people where recommending wouldn’t work.

So after a lot of experimenting and researching I was finally able to get the display to turn on and off with Arduino. This tutorial on the Arduino site was the most helpful. And I used the following Arduino sketch which I got from this post on the forums.

int dataPin = 11;
int clockPin = 12;
int latchPin = 10;
 
//holders for infromation you're going to pass to shifting function
byte dataRED;
 
byte dataArrayRED[11];
 
void setup() {
 
  //set pins to output because they are addressed in the main loop
  pinMode(latchPin, OUTPUT);
 
  //Arduino doesn't seem to have a way to write binary straight into the code
  //so these values are in HEX.  Decimal would have been fine, too.
  dataArrayRED[0] = 0x3F; //00111111 - 0
  dataArrayRED[1] = 0x06; //00000110 - 1
  dataArrayRED[2] = 0x5B; //01011011 - 2
  dataArrayRED[3] = 0x4F; //01001111 - 3
  dataArrayRED[4] = 0x66; //01100110 - 4
  dataArrayRED[5] = 0x6D; //01101101 - 5
  dataArrayRED[6] = 0x7D; //01111101 - 6
  dataArrayRED[7] = 0x07; //00000111 - 7
  dataArrayRED[8] = 0x7F; //01111111 - 8
  dataArrayRED[9] = 0x67; //01100111 - 9
  dataArrayRED[10] = 0x80; //decimal point
}
 
void loop() {
 
for (int i = 0; i&lt;11; i++)
{
 
  dataRED = dataArrayRED[i];
 
    //ground latchPin and hold low for as long as you are transmitting
 
    digitalWrite(latchPin, 0);
    //move 'em out
 
    shiftOut(dataPin, clockPin, dataRED);
    //return the latch pin high to signal chip that it
    //no longer needs to listen for information
    digitalWrite(latchPin, 1);
    delay(300);
 
  delay(1000);
}
 
}
 
// the heart of the program
void shiftOut(int myDataPin, int myClockPin, byte myDataOut) {
  // This shifts 8 bits out MSB first,
  //on the rising edge of the clock,
  //clock idles low
 
  //internal function setup
  int i=0;
  int pinState;
  pinMode(myClockPin, OUTPUT);
  pinMode(myDataPin, OUTPUT);
 
  //clear everything out just in case to
  //prepare shift register for bit shifting
  digitalWrite(myDataPin, 0);
  digitalWrite(myClockPin, 0);
 
  //for each bit in the byte myDataOut…
  //NOTICE THAT WE ARE COUNTING DOWN in our for loop
  //This means that %00000001 or "1" will go through such
  //that it will be pin Q0 that lights.
  for (i=7; i&gt;=0; i--)
  {
    digitalWrite(myClockPin, 0);
 
    //if the value passed to myDataOut and a bitmask result
    // true then... so if we are at i=6 and our value is
    // %11010100 it would the code compares it to %01000000
    // and proceeds to set pinState to 1.
    if( myDataOut &amp; (1&lt;
    {
	pinState= 1;
    }
    else
    {
	pinState= 0;
    }
 
    //Sets the pin to HIGH or LOW depending on pinState
    digitalWrite(myDataPin, pinState);
    //register shifts bits on upstroke of clock pin
    digitalWrite(myClockPin, 1);
    //zero the data pin after shift to prevent bleed through
    digitalWrite(myDataPin, 0);
  }
 
  //stop shifting
  digitalWrite(myClockPin, 0);
}

And here is a final diagram for connecting it to Arduino.

NOTE: the diagram shows a 15kohm resistor but it may not be bright enough. If you put a 2.2kohm resistor it will be much brighter

And here is a video of the display counting – http://www.viddler.com/explore/julian/videos/14/

I am working on getting more then one display working and will write a new post when I do

Continue reading » · Rating: · Written on: 05-30-09 · 4 Comments »

Installing Subversion locally on OSX

I have been working on getting Subversion installed on my Mac for the last couple of days in preparation for my talk at Flashbelt on Automatic Build Systems.

<Intermission>

As a quick plug. Flashbelt is one of the best Flash conferences in the world and I highly recommend going if you are in the area. I have some discount codes if you are planning on getting tickets within the next couple of weeks. Just leave a comment and I will send you one.

</Intermission>

Ok back on topic. There are a couple great posts out there that do a great job at explaining how to install Subversion on your Mac, but unfortunately they are a little out of date. So let’s do a little homework first.

Step 1.

Check what version of Subversion you are running. To do that open a Terminal window and type

svn help

This is assuming you already have the Subversion binaries installed. If you don’t you can download them from here.

In the first couple of lines in the output from that command it should say what version you are running.

Step 2.

Step 2 is just to follow all of the instructions on the followingThought Stream post. This takes you through the simple process of getting Subversion set up with Web DAV and working with localhost. If you have Subversion 1.4 installed then you are finished after these instructions. If you have a newer version then 1.4 come back for Step 3 after you are done.

Step 3.

Now we have to update the SVN Apache modules with the current version you have installed. If you kept the default path when installing Subversion navigate to /opt/subversion/lib/svn-apache.

In this directory there are 2 new .so files. All you need to do is overwrite the current modules in apache. To do that simply copy those 2 files to the following directory – /usr/libexec/apache

It may be a good idea to backup the original files but you should be ok if you didn’t. Once the new files are copied over you have successfully updated the SVN apache modules.

Step 4.

Now there is 1 last thing you will need to do in order to get everything working correctly. I am not even going to try and explain it because this post on Thought Spark explains it way better then I could ever do.

Step 5.

Everything should be all set now. All you have to do is restart apache and you should be able to navigate to your http://localhost/svn/games or whatever you named your repository and see the current revision.

To restart apache you can either un-check and check the Web Sharing checkbox in System Preferences > Sharing or you can use the following command

sudo apachectl restart
Continue reading » · Rating: · Written on: 05-18-09 · No Comments »

Great Papervision3D tutorial

There is a great Papervision3D tutorial over at the Web Development Blog. I had the opportunity to work with Papervision3D on our Volksdragon website we did a couple of weeks back and it was pretty easy to get something up and running pretty quickly. We didn’t really use it for anything earth shattering, which had to do more with not having as much time as I would have liked to play around with it, but the tutorial should get you up and running pretty quickly. I am really looking forward to getting to play around with the AS3 version of it when Flash CS3 comes out in a couple of weeks. The Papervision team has done a awesome job and I encourage everyone to give it a try.

Continue reading » · Rating: · Written on: 03-26-07 · 1 Comment »