Wiley.Mobile.Python.Rapid.prototyping.of.applications.on.the.mobile.platform.Dec.2007 (779889), страница 48
Текст из файла (страница 48)
The resultsare displayed for 25 seconds and then a new voting interval starts.The six options in the voting menu correspond to the six tracks inthe multi-track music video. Only one track is visible at a given time,determined by the collective vote of the previous voting interval. Thechange of the video track results in a non-linear perception of the videoon the public display.The music video employed in the MobiLenin system comprises sixtracks each showing a different performance style of the musician:•clap: he claps hands to the rhythm of the music (no voice, only slimmusic version with no guitar sound and no singing);•resign: no voice, just gestures, still slim music version with no guitarsound and no singing;•guitar: he plays guitar (still no voice, reduced music version withguitar sound, but no singing);•sing: he sings and plays guitar (full music version with guitar soundand singing);248COMBINING ART AND ENGINEERING•crazy: ‘violent’ performance (voice and full music version are on);•skeleton: he turns into a skeleton (still playing guitar and singing withfull music version on).Although the performance style of the musician changes, the background footage stays the same.(a)(b)(c)(d)Figure 11.2 Screenshots of the client’s UI: (a) the voting interval has started; (b) casting a vote; (c) the voteis acknowledged; (d) a winning lottery coupon is receivedMOBILENIN249Figure 11.3 The public display11.1.2MobiLenin Mobile Client CodeAlthough you can’t get this code to work since you are missing allthe back-end applications, we want to give a rough explanation here tohighlight how it was possible to rapidly prototype a project like MobiLeninwith PyS60 in a matter of 2–3 days.
The script is divided into two partsfor better display (Examples 110 and 111). It might not contain the mostelegant code, nevertheless it worked, served its purpose and shows youthat you can program things in Python in many different ways. Youare already familiar with some lines of code, for example the functionkeys() for handling keyboard keys.The server side (external server) of the MobiLenin system consists ofa few PHP scripts and some data files; the mobile client communicateswith them over GPRS or 3G. At the startup of the application, a temporary id is requested from the external server by an HTTP request,conn.request("POST", "/fetch id.php"). The id returned bythe fetch id.php script is used for further communication with theserver. It stays valid as long as the mobile client is up and running.The basic principle of the mobile client is that it polls the externalserver every two seconds to know whether to display the voting menu tothe screen, fetch a winning coupon or simply remain waiting.
The poll isdone inside the while loop at the bottom of the script by a standard HTTPGET request, conn.request("GET", "/control"+id+".txt"), tofetch data from a file that resides on the external server. This data fileholds the letters ‘A’, ‘K’, ‘B’ or ‘P’. It is dynamically updated by theother back-end applications that control the voting cycle and run thevideo.
With r1 = conn.getresponse() and data1 = r1.read(),250COMBINING ART AND ENGINEERINGthe received content from the data file is read into the variable nameddata1.Let’s look at the actions that follow based on the received content:•‘A’ triggers a pop-up note to the screen saying ‘Voting is on’(Figure 11.2 (a)), then function voting() is called to display a popup menu with the voting choices (Figure 11.2 (b)) based on thelist choices=[u"Clap", u"Resign", u"Guitar", u"Sing",u"Crazy", u"Skeleton"].
Resulting from the user’s selection, aletter between ‘A’ and ‘F’ is sent to the external server to inform theoverall vote count. This is done by a standard HTTP POST request,conn.request("POST","/voting phone"+id+".php",params, headers). Then another pop-up note is triggered to theuser saying ‘Your vote is being processed’ (Figure 11.2 (c)). Once thisis done, the script keeps polling the server every 2 seconds.•‘K’ keeps the mobile client polling until a different letter comes in.•‘B’ (for beer) or ‘P’ (for pizza) notifies the user about being thewinner of the lottery. A coupon (Figure 11.2 (d)) is fetched insidethe function winning() from the server by the standard Pythonfunction urllib.urlretrieve(url, tempfile) and displayedto the screen.
When the user presses the left softkey, the coupondisappears and the script keeps polling the server every 2 seconds.Example 110: MobiLenin (1/2)import httplib, urllib, appuifw, e32, graphics, key_codesdef keys(event):global win_stateif event['keycode'] == key_codes.EKeyLeftSoftkey:win_state=0def show_picture(picture):canvas.blit(picture)def voting():choices=[u"Clap", u"Resign", u"Guitar", u"Sing", u"Crazy", \u"Skeleton"]choice = appuifw.popup_menu(choices, u"Select + press OK:")choice_conversion={0: 'A', 1: 'B', 2: 'C', 3: 'D', 4: 'E', 5: 'F'}params = urllib.urlencode({'data': choice_conversion[choice], \'eggs': 0, 'bacon': 0})headers = {"Content-type": "application/x-www-form-urlencoded", \"Accept": "text/plain"}conn = httplib.HTTPConnection("www.yourdomain.com:80")conn.request("POST", "/voting_phone"+id+".php", params, headers)conn.close()def winning(url):global win_state, coupon_shownMOBILENIN251if not win_state:if not coupon_shown:tempfile = "E:\\Python\\resources\\win.jpg"urllib.urlretrieve(url, tempfile)coupon_shown = 1win_state=1img_win=graphics.Image.open(tempfile)appuifw.note(u"Winner", "info")e32.ao_yield()show_picture(img_win)appuifw.app.screen='full'appuifw.app.body = canvas = appuifw.Canvas(event_callback=keys, \redraw_callback=show_picture)img_wait=graphics.Image.open(u'E:\\Python\\resources\\wait.jpg')keyboard_state={}downs={}running= 1show_picture(img_wait)voting_done = 0win_state= 0coupon_shown = 0id = ""Example 111: MobiLenin (part 2/2)if id == "":conn = httplib.HTTPConnection("www.
yourdomain.com:80")conn.request("POST", "/fetch_id.php")response = conn.getresponse()data = response.read()id = str(data)while running:if not win_state:show_picture(img_wait)e32.ao_sleep(2.0)conn = httplib.HTTPConnection("www.yourdomain.com:80")conn.request("GET", "/ control"+id+".txt")r1 = conn.getresponse()data1 = r1.read()conn.close()if data1 == 'A':if not voting_done:coupon_shown = 0appuifw.note(u"Voting on", "info")voting()show_picture(img_wait)appuifw.note(u"Your vote is being processed!", "info")voting_done=1coupon_shown = 0show_picture(img_wait)elif data1 == 'K':voting_done=0252COMBINING ART AND ENGINEERINGelif data1 == 'B':winning("http://www.yourdomain.com/canvas_beer.jpg")elif data1 == 'P':winning("http://www.yourdomain.com/canvas_pizza.jpg")e32.ao_yield()Example 112 lists the PHP script, voting phone"+id+".php,which the mobile client calls when sending the vote to the externalserver.
The PHP script receives the vote content in the parameter, data,and stores it in a file called phone1.txt which is read by the otherback-end applications of the MobiLenin system. Each mobile client connected to the MobiLenin system has its corresponding data files and PHPscripts on the external server.Example 112: MobiLenin server-side PHP script<?php$data = file_get_contents('php://input');$filename = 'phone1.txt';$handle = fopen($filename, 'a+');fwrite($handle, $data);fclose($handle);?>With this setup it is possible to run MobiLenin with many usersat the same time as a multi-user entertainment game.
A test with75 simultaneous users was successfully carried out. For those interested in reading more about this project there is a 10-page researchpaper ([Scheible and Ojala 2005]), some documentation and videos atwww.leninsgodson.com/mobilenin.11.2Manhattan Story MashupManhattan Story Mashup is an urban storytelling game, designed bythe authors of this book, that combines mobile phones, the web and alarge public display into interactive, collaborative street art. The game isbased on real-time interaction between mobile phone and web users. Astorytelling tool on the game’s website allowed anybody to write storiesthat were illustrated in real-time by almost two hundred street players inNew York, taking photos with Nokia N80 camera phones.
Once a storywas fully illustrated, it was presented on a large public display in TimesSquare (see Figure 11.4).The street players were given points according to how many individualnouns – which were extracted from the web stories – they could illustratesuccessfully. The success was validated by another street player whoMANHATTAN STORY MASHUPFigure 11.4253Manhattan Story Mashup in Times Squarewas asked to match the newly taken photo with the original noun in amultiple-choice test. If she was able to match the correct noun with thephoto, both the guesser and the illustrator were awarded points.The game proved to be fun and engaging. During 90 minutes ofplaying, the street players took 3142 photos and made 4529 guesses tovalidate each other’s photos.