Wiley.Mobile.Python.Rapid.prototyping.of.applications.on.the.mobile.platform.Dec.2007 (779889), страница 29
Текст из файла (страница 29)
Ifusing an emulator, value 0 is always returned.• imei() returns the IMEI of the device as a Unicode string. If using anemulator, the hardcoded string u"000000000000000" is returned.SYSTEM INFORMATION153•active profile() returns the current active profile as a string,which can be one of the following: ‘general’, ‘silent’, ‘meeting’,‘outdoor’, ‘pager’, ‘offline’, ‘drive’, or ‘user <profile value>’.•display pixels() returns the width and height of the display inpixels.• display twips() returns the width and height of the display intwips (screen-independent units to ensure that the proportion of screenelements are the same on all display systems).
A twip is defined as1/1440 of an inch, or 1/567 of a centimeter.•free drivespace() returns the amount of free space left on thedrives in bytes.•max ramdrive size() returns the maximum size of the RAMdrive on the device.• total ram() returns the amount of RAM memory on the device.•free ram() returns the amount of free RAM memory available onthe device.•total rom() returns the amount of read-only ROM memory on thedevice.• ring type() returns the current ringing type as a string, which canbe one of the following: ‘normal’, ‘ascending’, ‘ring once’, ‘beep’, or‘silent’.•os version() returns the operating system version number of thedevice.• signal bars() returns the current network signal strength rangingfrom 0 to 7, with 0 meaning no signal and 7 meaning a strong signal.If using an emulator, value 0 is always returned.•dbm() returns the current network signal strength in dBm.
If using anemulator the returned value is always 0.•sw version() returns the software version as a Unicode string. Ifusing an emulator, it returns the hardcoded string u"emulator".Example 65: Sysinfoimport sysinfoprint "Battery level: %d" % sysinfo.battery()154BLUETOOTH AND TELEPHONE FUNCTIONALITY7.8 SummaryIn this chapter we have covered the Bluetooth functionality of the phone.We shared photos with a nearby phone and made a chat application fora pair of phones. We showed how simple it is to communicate with a PC,either with a standard terminal emulator or server software of your own.Traditionally, people have connected their mobile phones to PCs tosynchronize contact information or calendars – considering the plethoraof possibilities, this just scratches the surface.
The mobile phone can takefull control of the PC using simple methods, which was shown by theAppleScript example.We also demonstrated how to use the telephone programmaticallyand how to find people in the address book. Even though telephone isnot the most trendy communication method nowadays, it is undoubtedlythe most ubiquitous and most compatible, which makes it still highlyrelevant. In Section 7.7, we gave an overview of the sysinfo modulewhich is a treasure trove of information about the system state.Now that you can fully control everything in the five meters aroundyou, or at least everything that understands Bluetooth, it is time to lookfurther. The next two chapters introduce you to networking, which givesyou the necessary tools to communicate with practically any server in theworld.You should keep in mind that, even on the Internet, your greatest assetmay be the five meters around you: when anyone on the Internet needsinformation from that area, you and your mobile phone may be the onlygateways that can provide the desired information on the spot.8Mobile NetworkingThe modern mobile phone is a personal computer whose primary purposeis to keep its user connected with the outside world.
This is where PyS60becomes most fun: you can innovate and experiment with the mostinsane, amazing and productive combinations of you and others, ourphysical environment and all the digital information in the world.After these grandiose motivational words, we can crawl back to thetechnical details. Writing distributed applications, including the ones discussed in this chapter, are more difficult to get to work right than programsthat do not communicate.
The reason is simple: you have to keep threeindependent components synchronized instead of a single program.The client, the server and the network between them are all runningindependent, complex pieces of software that are only kept togetherby the force of protocols.
In addition, with mobile phones, one of thecomponents keeps changing all the time. Depending on your location,the network may be non-existent or anything between a low-bandwidthGSM connection to a broadband wireless LAN. Fortunately for us, adynamic programming language, such as Python, makes it possible toadapt to changing environments with relative ease.Even better news is that the most typical networking tasks are madereally simple in PyS60.
You can download anything from the web withone line of code and you can upload anything to your own websitealmost as easily. These basic tasks are introduced first in Section 8.1.If you are primarily interested in interacting with various web services,you do not have to bother about the underlying techniques too much.You can read only Section 8.1 and then proceed directly to Chapter 9,which deals with cool web-based applications without being heavy ontechnical details.
Note that, in this case, you still need to install the JSONextension module as instructed in Section 8.2.2.We give a guide on how to set up a development environmentfor mobile networking in Section 8.2. Then a toolbox of protocols is156MOBILE NETWORKINGintroduced in Section 8.3, which forms the basis for networking. A briefintroduction to server-side code is given in Section 8.4, which helps youto get started on that side as well.Finally, Sections 8.5, 8.6 and 8.7 describe three patterns of advancednetworking for mobile phones. Each pattern is explained using a fullyworking and non-trivial example, which can be used as a basis for furtherprototyping.Examples in this chapter are stand-alone and platform-agnostic: youcan use them as they are or you can easily adapt them to work with yourplatform of choice, whether it be Django, Ruby on Rails, .NET or Erlang.8.1 Simple Web Tasks8.1.1 Downloading Data from the WebYou can download any HTML page, image, sound or any other file fromthe web in one line of code.Example 66: Web downloaderimport urllibpage = urllib.urlopen("http://www.python.org").read()print pageThe script prints out the HTML contents of the Python home page.The module urllib contains functions related to web communication.Whenever you need to download something from the web, you can usethe urllib.urlopen() function, which returns the file contents toyour program so that they can be further processed.On the other hand, if you want to download a file from the web andsave it locally, you can use the urllib.urlretrieve() function tosave the file directly to a given file name, as shown in Example 67.
Ifthe URL contains unusual characters, such as spaces, you can use theurllib.quote() function to encode them properly.This example downloads the Python logo from the Python website andshows it using the phone’s default image viewer.Example 67: Web file viewerimport urllib, appuifw, e32URL = "http://www.python.org/images/python-logo.gif"dest_file = u"E:\\Images\\python-logo.gif"urllib.urlretrieve(URL, dest_file)SIMPLE WEB TASKS157lock = e32.Ao_lock()viewer = appuifw.Content_handler(lock.signal)viewer.open(dest_file)lock.wait()This example uses the function urllib.urlretrieve() to download data from a URL to a local file. When the data has been saved, thedefault viewer associated with the URL’s file type is used to open the file.You can change the URL to point at JPEG images, web pages, MP3 filesor any other file type supported by your phone.The Ao lock object is needed to keep the script alive until theviewer is finished.
You can easily extend this example into a generic webdownloader that asks the user for a URL to download and then shows thefile using the default viewer. You can implement it as an exercise.8.1.2 Uploading Data to the WebSometimes you want to upload photos, sounds or other files from yourphone to your website.
Example 68 presents a simple PyS60 script thattakes a photo and sends it to a website. On the server side, we show howto receive the photo in PHP. You can easily adapt the example to theweb back end of your choice.Example 68: Photo uploaderimport camera, httplibPHOTO = u"e:\\Images\\photo_upload.jpg"def photo():photo = camera.take_photo()photo.save(PHOTO)def upload():image = file(PHOTO).read()conn = httplib.HTTPConnection("www.myserver.com")conn.request("POST", "/upload.php", image)conn.close()photo()print "photo taken"upload()print "uploading done"The function photo() takes a photo and saves it to a file.
Then, thefunction upload() reads the photo (JPEG data) from the file and usesHTTP POST to send it to the server. Here we use the module httplibinstead of urllib. This module gives a lower-level access to HTTP andmakes fewer assumptions about the data sent.158MOBILE NETWORKINGOn the server side, you can use whatever method you want to receivethe data. Here, we give a minimal example in PHP that receives the photoand saves it to a file:<?php$chunk = file_get_contents(’php://input’);$handle = fopen('images/photo.jpg’, 'wb’);fputs($handle, $chunk, strlen($chunk));fclose($handle);?>There are many possible ways to send files to a server, although thismight be the simplest one.