Bluetooth communication in Flash is not possible natively (yet), so using Java (with Bluecove library) you can achieve this by using Native Process in AIR.

It works like this: FlashApp < — > AIRApp< — > Java. Of course, the AIRApp needs to be working on the background, and the FlashApp will be you main application (or it can be another AIR application).

I created an API to let Flash send commands to bluetooth, by the way it uses AS3 Signals for events dispatching. This is a code sample for searching devices:

If the image looks a bit blurry, then you need glasses, nah just kidding, it actually looks like that


“Yeah that’s cool, but how do I set everything up to create my app?” ok here it goes:

The first thing you need to do is to install BluecoveAIR

When you run it for the first time, select the path to javaw.exe by clicking the “Hey! Select Javaw.exe” button, the location is stored (via SharedObject) so you don’t have to set that again.

A window will aid you to navigate to choose the exe file.

Once it’s done you can see the “hello, Java stared” text (and a blue light indicator) that confirms that Java is good and ready to go.

That’s pretty everything you need to do in order to start using API. You can notice some options for Local Connection, these are default settings, if you wanna change them, type the new connection names in the input fields, but also remember to change them in the FlashBluetooth constructor in your Flash app.

constructor params

Local Connection default settings in the constructor (you may want to click the image).

This is a demo application to show how it works. You don’t have to worry much about the java output, it just displays what’s going on.

Note: First, place an mp3 file called “myFile” on drive C:\

Let’s start by doing a device inquiry, for that click “Search devices”. When finished, copy an address and paste it in the input text.  Then press the Download button.

When transfering the file, you’ll receive some permission notifications in your device, just accept them. Also will ask you to type PIN or code, it is 0000 (four zeros). The PIN code is hardcoded in the Java app, but yes, I will add the option to change that.

Download: AS3 API (with a few docs), sample app, BluecoveAIR and Java executables and source codes here

This was tested on Windows XP, Vista and 7, 32 bit. When I tried it on a Win7 x64 it didn’t work, so beware. (On that x64 machine, I later removed  Win7 64 and then installed a 32 bit Win XP and it went ok)

It breaks my heart not being able to generate a .dmg since I don’t have a Mac =P but if someone creates it, let me know. Also if you wanna clean and/or optimize the Java source code.. please do.

Here’s a video showing it in action

(sorry for my bad english :X lol, not that “bad english”, I mean my pronunciation)

Flash CS5 on Linux! (using Wine)

Posted: February 9, 2011 in Uncategorized

I recently started moving to Linux as my main O.S., I’m using Mint 10 (Julia) and I’ve been liking it so far. Of course there are obvious difficulties when making the transition, since how to change the mouse pointer to how to install a program, but once you get familiarized with that stuff you feel like home.

As a developer I want my tools working on my new shiny Linux, there are great ActionStript code editors that work on it, Realaxy, FDT, IntelliJ and some other that are AIR based (which are free). I chose IntelliJ, and coming from FlashDevelop it’s a bit hard to make the transition, but not impossible. Ok so I got a good code editor, but one of the most important things I need to do is to export swc files from Flash (animated Movie Clips, custom buttons and stuff). As you may know, there’s no Linux support for the CS products, so you need to do some funny stuff.

“Yeah yeah, just tell me how to run Flash CS5 on Linux”.

It’s very simple proccess which is decribed here http://int3ractive.blogspot.com/2010/08/how-to-run-flash-cs5-on-ubuntu-with.html a very cool blog by @trongthanh (quality tweets!). In another post he also explains how to use Flash Builder on Ubuntu in case you are interested.

hurray!

Here’s how CS5 look running on Mint, quite fine.

 

Yeah a glitchy thing but it's ok to meh

Yes maybe there are some tiny glitches that make your content look cropped, but it’s still intact

 

I tested exporting a swc from there, and then imported it into IntelliJ and worked as expected :)

Hi! Today I’m going to show you how to “mix” Java and ActionScript (I would call it JavaScri—umm no) with the help of the awesome Native Process class.
What exactly does this example app do?
It “magically” (tired of hearing that word actually) types text into a TextInput, yes types, I mean not setting the TextInput.text property, it’s done using the Java Robot class. When you click the “Hello” radio button, that word is typed, the same happens with the “Bye” radio button.

The app looks like this

The Java code is very simple, it just writes a text simulating key presses using the Robot class, if the java program receives as a parameter “Hello” it will type “Hello” in an Textfield of our application, also outoputs a string that will be read by the AIR app, making possible a two-way communnication (sorry for not having syntax highlight and formating):

public void checkForInput()

{

BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

String text = “”;

try

{

text = in.readLine();

if (text.equals(“Hello”))

{

try

{

Robot robot = new Robot();

robot.keyPress(KeyEvent.VK_H);

robot.keyPress(KeyEvent.VK_E);

robot.keyPress(KeyEvent.VK_L);

robot.keyRelease(KeyEvent.VK_L);

robot.keyPress(KeyEvent.VK_L);

robot.keyPress(KeyEvent.VK_O);

}//robot try

catch (AWTException e)

{

e.printStackTrace();

}// robot catch

}//if = hello

if (text.equals(“Bye”))

{

try

{

Robot robot = new Robot();

robot.keyPress(KeyEvent.VK_B);

robot.keyPress(KeyEvent.VK_Y);

robot.keyPress(KeyEvent.VK_E);

}//robot try

catch (AWTException e)

{

e.printStackTrace();

}// robot catch

}

}// try in.readLine

catch(IOException e)

{

System.err.println(“Exception while reading the input. ” + e);

}// in.readLine Catch

try

{

String stringToConvert = “Lolz from Java”;

byte[] theByteArray = stringToConvert.getBytes();    

DataOutputStream dataOutputStream = new DataOutputStream(System.out);

dataOutputStream.write(theByteArray);

dataOutputStream.flush();    

}

catch(IOException e)

{     System.err.println(“Exception while reading the input. ” + e);

}

}

Now the Flexy part:

First lets set the JRE location in our machine, in this example the URL is hardcoded, and may vary depending on your OS or your JRE installation settings, you can also make the app to open a window and let you browse to the location.

(All the following is executed when the “Start Java” button is clicked)

var file:File = new File(“C:\\Program Files\\Java\\jre6″);
file = file.resolvePath(“bin/javaw.exe”);

Next we need to set te arguments in a Vector, with this, we tell JRE to execute our JAR file

var arg:Vector.<String> = new Vector.<String>;
arg.push(“-jar”);
arg.push(File.applicationDirectory.resolvePath(“MyJar.jar”).nativePath);

Now we create an instance of NativeProcessStartupinfo, this will contain our arguments vector and the location of the javaw.exe

var npInfo:NativeProcessStartupInfo = new NativeProcessStartupInfo();
npInfo.executable = file;
npInfo.arguments = arg;


We have our parameters ready, now lets create a native process and start it with the npinfo that contains the necesary data to run our jar, and an event listener to receive data from Java.

nativeProcess = new NativeProcess();

nativeProcess.addEventListener(ProgressEvent.STANDARD_OUTPUT_DATA, onStandardOutputData);

nativeProcess.start(npInfo);


There we go!, but don’t get excited this won’t do anything LOL so lets send some parameters:

(This code is executed when one of the radio buttons is clicked)

nativeProcess.standardInput.writeMultiByte(e.currentTarget.label+”\n”, “utf-8″);

Note: The “\n” is necessary since The in.readLine() in java considers a line when a text ends with “\n”

And w00t! That sent the parameter to Java and the text is automatically written.

Okay, but what do we do if we want to read data sent from java? easy, inside the onStandardOutputData function write:

trace(nativeProcess.standardOutput.readUTFBytes(nativeProcess.standardOutput.bytesAvailable));

And you will be able to see a message in the console everytime you click a radio button.



I’ve added the source (both FB and Java) files here

And here are some other post and articles related to Native Process:

I had this idea of a trick for integrating Unity (web) with a Flash-based GUI. The main concept was to put the SWF in front of the Unity game kinda like this:

Yeah kinda like this
I have  the theory that the SWF movie will “cancel” the mouse events in Unity, just like Flash, when you place a MovieClip in front of a button, disabling the events for that button. But obviously I had to load a Flash movie of the same size of the Unity game to make it unplayable (like a selection screen or pause menu), to deal with that I could unload the SWF or call another with a smaller size (like a score displayer.. or something that Unity could not do with the fanciness of Flash)

Since I’m not very experienced in HTML/JavaScript/CSS I searched for ideas on the web.

My first try was using the <div> tag. Within the tag I could set the z-index of the Flash HTML container the Unity game would be in the main HTML, and then load the HTML containing Flash. I used z-index, to force the Flash container to be infront of the main page.

My next try was loading Flash and Unity into separate IFrames, and forcing each IFrame to have a specific z-index so I could be sure both of them having a strict order, but Unity was still on top.

Using separate iFramesThat yellow label’s actually from Flash, and should not be  cropped


Other try was a trick used by some annoying flash banners (those ones that pop out in front of the main content), the example I found was using FlashObject (yeah when it was called like that). The result was not succcessful.

annoying ad techniqueSame problem

I tested it in Firefox, Opera, Chrome and IE.
Technically everything went well about placing “my Flash” over the main HTML (the “Unity container”). If you take a closer look at the second image in this post, the SWF is in front of the red background (HTML Unity container) BUT the Unity game keeps being at the top… and I don’t know what else to do, I see that as some kind of “bug” on graphics processing (I don’t even know what I’m talking about). So… if someone has some idea about a workaround or something for placing Flash on top of Unity content please let me know :)

I’ll upload my source files soon (so you can have  a look).

Thanks!

Update: Seems like someone had this problem too and no solution was found (except the one sayin “don’t place stuff on top of plugin rects” but that’s not quite a solution) :\ http://forum.unity3d.com/viewtopic.php?t=9989

Communicating Flash and Unity

Posted: December 9, 2009 in Uncategorized

This is a very simple example of connecting Flash and Unity through JavaScript. I did this example like 2 weeks ago but didn’t blog it (just tweeted it :-P)
Like Flash, Unity also has it’s own “ExternalInterface.call()” function called “Application.ExternalCall()“, since both Flash and Unity can call a function in JavaScript, communication between them (inside a browser) is easy.

For this example I just made a cube in Unity named “UnityCube”, added it to the scene, then created a new C# script and attached it to the cube. The important function in the CubeScript.cs is OnMouseDown, which invokes the JavaScript function called “resizeSquare” that will make a square to resize in Flash. It also has a function called “moveCSharp” which moves UnityCube in different directions.

On the Flash side, with ExternalInterface.call(“moveJS”, param) the function “moveJS” in JavaScript will be called and the cube in Unity will move in different directions dependig on the parameter sent (left, right, forward, backwards and jump). And function “resizeSquare” changes the size of the red square in the SWF.

Now for JavaScript, there are of course two functions, the one called from Unity (resizeSquare), and the one called from Flash (moveJS):

//This function is called from Flash (when one of the buttons is clicked) via ExternalInterface.call();
function moveJS(direction)
{

//sendMessage(); calls a function that belongs to an instance
//the firts parameter is the name of the target instance in Unity, next the name of the function we want to call, and finally, the parameter to send.

GetUnity().SendMessage(“UnityCube”, “moveCSharp”, direction);
}

//This function is called from Unity (when the cube is clicked) via Application.ExternalCall();
function resizeSquare()
{

//check how to call the ActionScript function depnding on the OS
if (navigator.appName.indexOf(“Microsoft”) != -1)
{
FlashUnity.resizeSquare();
}
else
{
window.document.FlashUnity.resizeSquare();

}

}

You can check the example (and source) here.

Now that UDP is supported in AIR, communication with a Nintendo DS is no big deal.  Let’s start with the requirements:

-  NDS (with WFC already configured)

- A Flashcard (I have an R4, but Ezflash or M3 would be ok too)

- DS2Key (for sendig data from DS to your computer)

- Know your DS and computer’s IP.

- Of course a computer, a router, Flex (or FDT, FlashDevelop, whatever) and AIR sdk 2 beta (and runtime).

The code is very simple actually for this example, it just reads the coordinates where the stylus is pressing the touchscreen, I’m just showing the important parts:

//IP & port for this computer
private var localIP:String = “xxx.xxx.xxx.xxx”;
private var localPort:int = 55555;

//IP & port for NDS
private var targetIP:String = “yyy.yyy.yyy.yyy”;
private var targetPort:int = 55555;

private function init():void
{

datagramSocket = new DatagramSocket();
datagramSocket.addEventListener(DatagramSocketDataEvent.DATA, dataReceived);

datagramSocket.bind(localPort, localIP);

datagramSocket.receive();

//Need to actually send comething to receive data… don’t know why, sorry
var data:ByteArray = new ByteArray();
data.writeUTFBytes(“Some data”);
datagramSocket.send( data,0,0, targetIP, targetPort);
}

private function dataReceived(event:DatagramSocketDataEvent):void
{

//get the data, X and Y position of the DS stylus
var pos:String = event.data.readUTFBytes(event.data.bytesAvailable);

// we receive for example “/m120.90.3″
// 120 is the value in the X axis, and 90.3 the value for Y

var separate:String = StringUtils.beforeFirst(pos, “.”);
var firstPart:String = StringUtils.remove(separate,”/m”);

var secondPart:String = StringUtils.afterFirst(pos, “.”);

//Your stuff

}

(As you can see I used Grant Skinner’s StringUtils which is here).

That’s all we need to receive and handle data from the NDS.

Now, to send data from the NDS, the DS2Key is needed (grab it here), to install it we just copy the DS2key.nds to the flashcard. Insert the flashcard into the NDS, run DS2Key to set the target computer’s IP and the port (55555 in this case).

And that’s it! Very easy. Of course, this is not limited to just reading the X and Y values of a point in the touchscreen being pressed with the stylus, button (x, y, b, a, etc. ) states can also be read. At first I had problems getting the data from the DS, so make sure the port you are using is open, that solved it for me.

I did a simple drawing application:

You can download the source here.



Yay, Hello world!

Posted: November 29, 2009 in Uncategorized

Ok so.. i’ll start blogging all my Unity and Flash stuff here. This is like the 3rd attempt of doing a “serious” blog (I have another one, but its just randomness, and it’s in Spanish). Since English its not my native languaje, please try to use your imagination to understand what I’m trying to say hahah.