Multicast UDP socket in Adobe AIR with Python

In my last project I solved a big issue that I needed to receive notification from an hardware via a Multicast UDP socket.
If you want to know more about Multicast and Unicast in Flash Platform I really suggest to read Flashrealtime blog.
Like you know the Flash Platform can use multicast with RTMFP protocol so you can use it Flash to Flash or Flash to Flash Media Server but not Flash to hardware for example.

In my case I needed a Multicast UDP socket in a local application that communicate with an hardware that was my server, so I thought to realize a Python application for Mac OS X and Windows that could help me to solve this problem.
Python is my second favorite programming language after ActionScript (obviously) and this time Python saves me to accomplish my project.
I want to start with Python side, my goal is to connect to a multicast socket and get all data and then send them to a unicast UDP socket server that we will create in Adobe AIR in next example.

#!/usr/bin/env python
# encoding: utf-8

import socket, select

ANY = '0.0.0.0'
MCAST_ADDR = '239.0.1.1'
MCAST_PORT = 10300

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
sock.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
sock.bind((ANY,MCAST_PORT))
sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 255)
status = sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP,
socket.inet_aton(MCAST_ADDR) + socket.inet_aton(ANY));

sock.setblocking(0)
print 'socket UDP multicast ready'

udp = socket.socket(socket.AF_INET, socket.SOCK_DGRAM);

while 1:
	ins, outs, errs = select.select( [ sock ] , [], [], 1.0)
	try:
	    data, addr = sock.recvfrom(1024)
	except socket.error, e:
	    pass
	else:
	    print data
	    udp.sendto(data, (socket.gethostbyname('127.0.0.1'), 10303))

socket.close()

First few lines we define the multicast socket server ip (that in my case is pointing to the hardware) and the socket port to communicate with.
Then I create the UDP multicast socket and the UDP unicast socket (udp var); in the while loop I set the socket timeout and if I receive data trough the multicast socket I send everything to unicast one.
After that to create an application without any dependency in Windows or Mac OS X, you need to use a couple of Python libraries called py2app and py2exe.
Both allow you to create an executable file from your Python script for mac or win without any dependencies, in Windows side you have only to remember which kind of Python dll you have to incapsulate in your AIR application but we take a look at that in a while.
To create the executable file you have to create a setup script in Python for both operating systems, I suggest to create something like that:

FOR WINDOWS:

from distutils.core import setup
import py2exe,sys,os

origIsSystemDLL = py2exe.build_exe.isSystemDLL
def isSystemDLL(pathname):
        if os.path.basename(pathname).lower() in ("msvcp71.dll", "dwmapi.dll"):
                return 0
        return origIsSystemDLL(pathname)
py2exe.build_exe.isSystemDLL = isSystemDLL

setup(windows=['myPythonScript.py'])

FOR MAC:

from setuptools import setup

APP = ['myPythonScript.py']
DATA_FILES = []
OPTIONS = {'argv_emulation': True}

setup(
    app=APP,
    data_files=DATA_FILES,
    options={'py2app': OPTIONS},
    setup_requires=['py2app'],
)

Then if you want to create your executable files you have only need to launch the command on command prompt or terminal (you can find more informations on how to customize those setup scripts in each library’s website):
FOR WINDOWS:

python setup.py py2exe

FOR MAC:

python setup.py py2app

Now we can start with the AIR part, like you know with AIR 2 you can work with Native Process and this is the case to use them:

const WIN_PATH:String = "win/socket.exe";
const OSX_PATH:String = "socket.app/Contents/MacOS/socket";

var nativep:NativeProcessStartupInfo = new NativeProcessStartupInfo();

var finalPath:String;

var f:File
if(Capabilities.os.substr(0, 3) == "Win"){
   finalPath = WIN_PATH
}else{
   finalPath = OSX_PATH
}

f = File.applicationDirectory.resolvePath(finalPath);

nativep.executable = f;

var process:NativeProcess = new NativeProcess();

process.addEventListener(ProgressEvent.STANDARD_OUTPUT_DATA, onOutputData);
process.addEventListener(NativeProcessExitEvent.EXIT, onExit);
process.addEventListener(IOErrorEvent.STANDARD_OUTPUT_IO_ERROR, onIOError);
process.addEventListener(IOErrorEvent.STANDARD_ERROR_IO_ERROR, onIOError);

process.start(nativep);

var udp:DatagramSocket = new DatagramSocket();
udp.addEventListener(DatagramSocketDataEvent.DATA, getData);
udp.bind(10303);
udp.receive();

function getData(e:DatagramSocketDataEvent):void{
	trace(">>>>>" + e.data.readUTFBytes( e.data.bytesAvailable ))	
}

function onOutputData(event:ProgressEvent):void{
   trace(process.standardOutput.readUTFBytes(process.standardOutput.bytesAvailable)); 
}

function onErrorData(event:ProgressEvent):void{
    trace(process.standardError.readUTFBytes(process.standardError.bytesAvailable)); 
}

function onExit(event:NativeProcessExitEvent):void{
   trace(event.exitCode);
}

function onIOError(event:IOErrorEvent):void{
  trace(event.toString());
}

In this simple script I’m choosing the right executable file for the operating system where my AIR application is working on and then I launch the native process to start the multicast socket.
Finally I listen for the unicast socket and I trace on the output panel the messages that I receive from the hardware.
I think this is an interesting way to extend Adobe AIR with Python that open new possibilities on the desktop side, think for example to create a Python bluetooth extension for Adobe AIR, it could be so interesting add this feature to AIR apps isn’t it?

Advertisement

Presentation Model design pattern: multiple screen solution – part 1

Today I’d like to talk about Presentation Model design pattern because it’ll be so useful for anyone that is working on multiple screen project with Flash or Flex.
In latest months we lived in phrenetic mobile world where we have tons of new and powerful devices on the market with different screen sizes, different hardware and so on, on the other hand we have clients that are looking for new business opportunities and they are seeking a way to spend less but earn more.
So, one way to solve those problems could be find a way to deploy with the same technology in different devices (tablets, smartphones, computers…) saving time with great results!
That’s not a dream, it could be made with knowledge, architecture and a good developer or a team!

Our goal

For a developer find a way to have a good project architecture to maintain it’s so important, usually when you start a project you try to define the parts that could be re-usable in different part of the same project or in different project too.
So our aim is find a way to write less code but it will cover the project needs and that could be portable in different screens / operating systems easily.

What is Presentation Model design pattern?

My mentor Martin Fowler describes it with those words: “Represent the state and behavior of the presentation independently of the GUI controls used in the interface”  (here the full article of Martin Fowler).
In fact with this pattern we divide UI (components, movieclips, sprites…) from their behaviors; each view will have one and only that one presentation model and only the presentation model will interact with the whole architecture (like with model or proxy…).
Probably with this image you can easily understand better this concept (from Martin Fowler website):

Like you can see we have 3 class, AlbumTitle that is a view with a textfield, AlbumPresentationModel that is the presentation model of AlbumTitle and it has the copy of the view but storing datas inside and finally the main model Album where we have the data that could be used for the whole application.
There aren’t any connection trough the views and the application model because only the presentation model has access to the whole project, so the view is only a bunch of components and custom graphics, this it means that if you have to change UI on a mobile project for a different device, changing the views and anything else, you will have done your job.
In fact with this easy technique you perfectly solve our problem and you should create the same content for different devices changing only the views.
Probably your application in different devices will have the same functionalities but with a different UI dedicated for the OS is running on.
With this sample design pattern you’ll have a solid infrastructure that will solve the big problem to port the same application in different screen sizes.
So in next paragraph we can take a look on how to organize our files project.

Manage a project for different screen sizes

Another important thing before starts the project is understand how to organize the project for different OS, in fact if you work with Adobe AIR on Android you’ll have only the XML descriptor with Android permissions described in this file, on Playbook you’ll have another XML file dedicated to this platform and so on.
So, my suggestion is to organize the project in different projects that work together.
In this image you can see how I organize it for our final scope, I’ve a common project (Runtime Shared Libraries in this case but you can use also an Actionscript or AIR project if you work with Flash for example) where I’ll put all classes that are common for different target, so in my case all the presentation models, main models, utils classes, my notification bus and views that are common for different projects like components for example.

In the target device projects I add only what I need for that device, in this case only a couple of views and assets but in big projects could be more stuff that those one:

When you have a specific behavior only for a target device, you can easily extends the common presentation model and add new functionalities or create a side class that you’ll add in the specific view.
So with this infrastructure you can solve bugs and change stuff directly on the common project and all the platforms will be ready to package the project and upload to their store. That’s cool, isn’t it?

Summary

So in this post I hope to give you some ideas on how to solve the big problem to create a common base code that could be useful for different purpose.
In next post I’ll show you how to implement it in practice, for now if you have any feedback or suggestions for the second part of this article please add a comment to this post.

Flash Camp Milan review

Yesterday in Milan we had the Flash Camp about Mobile topics and then we had the Flash Camp Party at NH Hotel… really wonderful time.
Like you know, in Italy it’s not so easy to organize those kind of events because usually people don’t move to another city like other foreign countries but Flash Camp had a great success.
This camp was organized in the same place of WhyMCA the mobile revolution, an italian conference focused on mobile topics.
We had 50/60 people per session and I’m glad to say that my session had 80 people so I’m happy about this little success.
All the sessions surfed in deep about CG, design patterns, video optimization for mobile, flex on mobile and so on, so I was really excited to take part in this event.
My session was about Design Pattern for Mobile, I talked about 3 design patterns: Singleton, Observer and Presentation Model.
With a couple of samples (that you can download from this link) and few slides I made an application that run with the same base code on tablet and smartphone; this is an hot topic now on mobile world in particular on Flash Platform side.


In next few weeks I’ll make a post about Presentation Model to share my thoughts about this argument and how to use it in your project , but if you want to start with this topic, take a look at this great post on RIArockstars.

Finally I’d like to thanks the Flash Mind, Adobe Flash Platform User Group Italy, to give me this opportunity, WhyMCA staff for the amazing organization, other speakers of Flash Camp for great time spent together and people that came to talk with us during the Flash Camp and to the beer party too.
I leave also a link to some photos took during Flash Camp in Milan.

Flash Camp in Milan

I’m glad to announce an interesting Flash Camp that will take place in Milan this month at 20 and 21.

All the topics of the Flash Camp will be focused on mobile side, so Flex for mobile device, iOS, Android and Playbook development, code technique for mobile applications, optimizing video content for mobile, design pattern and architecture for mobile project.
Flash camp will be hosted by the whymca the mobile developer conference, that for the second year will show the mobile opportunities not only with Flash Platform but with any technology could be use for mobile purpose.
The event will be in Milan in Milanofiori (Assago), you can find more information on whymca web site.

Back on the Flash Camp side, speakers will be:

Mihai will talk about Flex on mobile devices and how to deploy a content on multiple devices, in the afternoon he has a live coding session where show how to create a mobile application with Actionscript 3.
My good friend Fabio will talk about video encoding optimization for mobile devices, Andrea will show how to create a game cross-platform with Flash Platform and Piergiorgio will give us great suggestions on how to optimize our code and improve the performance of mobile solutions.
Finally me, I’ll talk on how to organize a multiple screen development with Design Pattern and Architecture to re-use code and have great performance on mobile solutions.
For a limit number of people we are organizing a post event for the evening so try to come from the beginning of the Flash Camp and you’ll receive more information about it or keep update reading this blog.
See you there Flashers!!!

Playbook development with Flash Platform

First of all a big THANKS to Mihai Corlan, Adobe Evangelist, that is helping me during this “journey”.
Everything start last year during MAX when I saw for the first time the new BlackBerry tablet: the Playbook 😀
It looked so nice, I thought that it was really amazing.
So after few months I decide to try… and now, I finally can announce that with Mihai we are working on a book on Playbook application development with Flash Platform!

It’ll be an hard job but I want to do it, I hope to receive useful suggestions and questions about this topic and believe me that I’ll be free to talk with you about that.
It will be a book made by developers for developers so I hope that you’ll enjoy it when will be released this september (more or less).
This book will cover following topics:

  • Build, port and optimize apps for the BlackBerry PlayBook tablet device
  • Work with the PlayBook OS APIs, ActionScript, Flex, AIR and other Flash tools/APIs for PlayBook
  • Build a simple app and consuming data
  • Create multimedia and gaming apps for the BlackBerry PlayBook
  • Debug and optimize your PlayBook app

For any news about this book and about Flash Platform development follow this blog and my twitter or facebook account.

Working with Adobe AIR FileSystem API on iPad

Recently I made some test on iPad to test how to update contents of my mobile applications.
I tried some new AIR 2 API like open default program with PDF or XLS files but I get error #3000 (privileges error).
My idea is to create a routine where I’ll be able to update all contents on my application without passing trough Apple store.
So I tried with URLStream and AIR filesystem API, everything works well.
Code is so easy, take a look here:

//RETRIEVING IMAGE FROM ANY WEBSERVER
var urlS:URLStream = new URLStream();
urlS.addEventListener(Event.COMPLETE, downloadComplete);
urlS.addEventListener(ProgressEvent.PROGRESS, showPerc);
urlS.load(new URLRequest("http://192.168.1.9:8888/oliviaWilde.jpg"))

//DOWNLOADED IMAGE BYTEARRAY AND LOADING IN LOADER
function downloadComplete(e:Event):void {

  perc_txt.text = "";
  fileData = new ByteArray();
  urlS.readBytes(fileData,0,urlS.bytesAvailable);
  bytes = urlS.bytesAvailable;
  l.loadBytes(fileData);
  l.addEventListener(MouseEvent.CLICK, saveIt);

}
//SAVE IMAGE INTO APPLICATIONSTORAGEDIRECTORY
function saveIt(e:MouseEvent):void{

  f = File.applicationStorageDirectory.resolvePath("a.jpg");
  var fs:FileStream = new FileStream();
  fs.open(f, FileMode.WRITE)
  fs.writeBytes(fileData);
  fs.close();

}

//LOAD IMAGE FROM APPLICATIONSTORAGEDIRECTORY 
function loadLocalImg(e:MouseEvent):void{

  var finalBA:ByteArray = new ByteArray();
  var fs:FileStream = new FileStream();
  fs.open(f, FileMode.READ);
  fs.readBytes(finalBA, 0, bytes);
  fs.close();
  l.loadBytes(finalBA);

}

Using applicationStorageDirectory, you can save data into your application and retrieve it with AIR API.
In the video below, you can see a little demo where I load an image from a server, I save it, I unload click on the black right button and finally I load again but from ApplicationStorageDirectory, with the black left one, instead of loading from webserver.

mPresenter, flash platform presentation tool

mPresenter is a new tool that my company develop in last few months, finally is available to download.
Going in deep about this new solution, what is it mPresenter?

mPresenter is a cross-platform software composed by 2 different tools: a mobile manager and a desktop viewer.
It helps you during own presentation to your boss or clients, during a public talk or only when you want to show your holidays photos to your friends.
With mPresenter you can manage your presentation directly from your mobile device, you can draw or highlight on a slide, photo or flash file, change with next or previous content, receive comments that you add in content and so on.

You can download AIR version on mPresenter official website and Android controller directly on Android Marketplace.In next few days (I hope) you can find mPresenter mobile on Apple store too, so stay tuned for news about it!

Do you want watch mPresenter in action? Take a look at youtube video.

Do you want to have a free copy?! It’s easy, go to official website, add mPresenter banner to your blog or website and the first 10 people that add a comments to this post with a link at own website with mPresenter banner automatically win a free mPresenter copy!
Remember to leave in the comment your name, email and link to the site where I can find mPresenter banner.

Finally, if you are going to MAX in L.A. and you want to know more about mPresenter, you can find me there, so feel free to drop me a line to meet there.

I’m waiting for feedbacks and have fun guys with mPresenter!

Android development with Flash Platform

First of all I’d like to say thank you to JUG Padova that give me opportunity to talk about Flash Platform in own Java User Group.
Saturday morning I got a talk about Android development with Flash Platform in a school in Padova.
There were 40/50 people more or less, students, Flash Platform devs and Java devs, so I’m glad about the final result.

I talked about my experience on working with Flash Platform on Android, suggested some tips & tricks to improve own applications made with AIR or web site for Flash Player on Android and finally I reported latest news from Flash on the Beach general session.

Adobe has just released Adobe AIR for Android so from last weekend you can download it and start to develop your own Flash Platform contents for Android devices.

You can download my presentation slides with some samples directly here, for now slides are in Italian but if someone is interesting in an English translation feel free to add a comment here.

UPDATE
Here you can watch the seminar: http://www.archive.org/details/AndroidDevelopmentWithFlashPlatform

mPresenter: new tool for speakers

I become speaker 4/5 years ago, after 30/40 talks in Italy and around the globe and tons of lessons like instructor, after study how to prepare slides for presentations, after a couple of courses about public speaking and so on, finally this January I started to think about how can I help speakers during own presentation?

When I answered to this question I started to think about mPresenter.

mPresenter is composed by 2 different applications: a mobile application and a desktop one.
Obviously everything is build with Flash Platform: AIR 2, Flex 4 and AIR for Android.
The mobile one allow you to manage your presentation, pointing or drawing on slide, changing them.
Also, it allows you to read notes added in each slide during preso composition.

AIR application allows speakers to make own presentation: moving slides in right position, adding notes to a slides and zooming on it.
You can easily drag and drop images from your OS to mPresenter and create the perfect presentation.
We are working to add new features on this software but for now you can see a preview video on youtube.
I really love if you can give us your feedbacks and suggestions to improve this software and become a really useful utility for all speakers.
We believe in you!

Flash Platform Geeks: new community is born

And YESSSSSS!

In this hot summer, I’m really glad to announce Flash Platform Geeks, a new Flash Platform community made in collaboration with Peter Elst!
Flash Platform Geeks is dedicated to all flash platform lovers like us!
Soon you can see online our website, our forum and so on, I’m really excited about this new adventure

It will be crazy, totally insane and if you go to Flash on the beach this year, believe  me, when I say that you’ll remain astonished!

So please, start to follow us on Twitter, Facebook and Flickr too!
See you around guys and thank you in advance to spread the word and follow Flash Platform Geeks