Wiley.Mobile.Python.Rapid.prototyping.of.applications.on.the.mobile.platform.Dec.2007 (779889), страница 56
Текст из файла (страница 56)
For example, in theexamples above a major bug is lurking. Both the examples are missingthe import appuifw statement in the beginning of the script, which isneeded to call appuifw.query(). The examples just happen to worksince the Python shell imports the appuifw module internally. If yourun the examples above as stand-alone programs, they would fail withoutany meaningful error message.298DEBUGGINGC.2 Debugging ProcedureHow should you proceed when a program does not work as expected?After you notice that something is wrong, you have at least some information, namely, at which point the program does not work as expected. Youshould restart the program and repeat the steps that led to the problemto make sure that you have correctly recognized the context in whichthe bug occurs.
You can repeat this many times if you like, maybe withslightly varying input to collect more information on the nature of theproblem.You should be able to locate the function which does not workcorrectly. Add some print statements in the code and try to find outwhat the erroneous values look like. Sometimes, examining the values isenough to reveal the actual cause. If you are debugging an applicationwith a user interface, it might be easier to show the values in a pop-updialog instead of using print statements and the console.Once you have spotted the erroneous values, you should start backtracking to find out how they are produced in the first place. Usually, youdo this by adding print statements along the program’s path of execution,that is you add them to functions which were called before the functionthat manifests the problem.Print out all intermediate values to check whether they match yourassumptions as to what they should be. Once you have found the functionwhich gets correct input but produces incorrect output, you are closerto identifying the actual cause of the problem.
After you have foundthe cause, fixing it is often straightforward. Before you remove all printstatements used for debugging, it makes sense to test the new functionand ensure that it produces correct values. This makes the debugging ofother errors easier.If the incorrect function seems to be a PyS60 API call, that is, a functionwhich is used to access the device’s features, you should proceed asfollows. First, double-check the documentation to make sure that youhave understood the input and output of the API call correctly. Eventhough PyS60 documentation is typically written in a clear, technical,unambiguous way, sometimes the descriptions leave room for differentinterpretations. Try to find some example code using the particular APIcall in question, for instance from the web.If you are sure that the function should work as you expect, make asminimal a test script as possible, which you can use to test the functionin isolation.
If you cannot get the function to work even in isolation, theproblem is not likely to be in your program. Either the API function hasbugs (not totally unlikely) or it is meant to be used in a different manner.In either case, you might ask for help in the Python for S60 mailing list,IRC channel, Forum Nokia discussion board or the PyS60 wiki.DEBUGGING PROCEDURE299If you feel adventurous, you could take a look at the Python sourcecode and find out how the API call is implemented. This is not asintimidating as it may first sound, since the code is typically written in aclean and understandable style. Even if you do not understand it fully, itcan point you in the right direction. Luckily Python is open source so thisis a real option!If the problem is not related to a device feature but to a Python languageconstruct or to a function in its standard library, you can experiment withsimilar code on your PC.
It is practical to have the standard Pythoninterpreter, which is available at www.python.org, installed on yourPC – note that PyS60 is based on Python 2.2 and not the newest version,which is 2.5 as of July 2007. You can have a Python shell running onyour PC on which you can try out different expressions and functions onthe fly. This is often faster than sending the code to your phone to try outdifferent expressions.Appendix DHow to Use the EmulatorYou download the PyS60 Interpreter installation files from http://sourceforge.net/projects/pys60.
You must download the correct version (for2nd or 3rd Edition of S60). If you are not sure which one you need, checkTable D.1 to find your phone model. You will also find a device overviewat http://forum.nokia.com.Here are the steps to take to use the emulator:1. Download and install the correct S60 Developer Platform SoftwareDevelopment Kit (SDK) which includes the emulator. The SDK canbe found at Forum Nokia (http://forum.nokia.com).2. Download and install the Python plug-in that comes as part of theappropriate SDK file, which can be found on the SourceForge PyS60project website (http://sourceforge.net/projects/pys60).3. Load your script into the emulator by copying your .py file to theappropriate folder (see the Python plug-in documentation).4.
Open the emulator and start the Python application using the iconon the emulator’s desktop window or a subfolder of it.5. Select Options, Run script. Choose your script from the list thatappears and press OK. Your script should now start up.302HOW TO USE THE EMULATORTable D.1 PyS60 installation filesS60 EditionPyS60 Install files3rd EditionNokia 3250, Nokia 5500Nokia 5700, Nokia 6110Nokia 6120, Nokia 6121Nokia 6290, Nokia N71Nokia N73, Nokia N75Nokia N76, Nokia N77Nokia N80, Nokia N91Nokia N92, Nokia N93Nokia N93i, Nokia N95Nokia E61, Nokia E61iNokia E65, Nokia E50Nokia E60, Nokia E62Nokia E70, Nokia E90PythonForS60 1 4 0 3rdEd.SISPythonScriptShell 1 4 0 3rdEdselfsigned.SIS2nd EditionNokia 3230, Nokia 6600Nokia 6260, Nokia 6620Nokia 6670, Nokia 7610PythonForS60 1 4 0 2ndEd.SISPythonScriptShell 1 4 02ndEd.SIS2nd Edition Feature Pack 2Nokia 6630, Nokia 6680Nokia 6681, Nokia 6682PythonForS60 1 4 0 2ndEdFP2.SISPythonScriptShell 1 4 02ndEdFP3.SIS2nd Edition Feature Pack 3Nokia N70, Nokia N72Nokia N90PythonForS60 1 4 0 2ndEdFP3.SISPythonScriptShell 1 4 02ndEdFP3.SISReferencesBelow, we have highlighted the most important sources of information inboldface.Book ReferencesHeath, C.
(2006) Symbian OS Platform Security: Software DevelopmentUsing the Symbian OS Security Architecture. Chichester: John Wiley& SonsLutz, M. (2001) Python Pocket Reference. O’ReillyLutz, M. and Ascher, D. (2003) Learning Python. O’ReillyScheible, J. and Ojala, T. (2005) ‘MobiLenin – Combining a multi-trackmusic video, personal mobile phones and a public display into multiuser interactive entertainment.’ at www.leninsgodson.com/mobileninVon Hippel, E. (2005) Democratizing Innovation. MIT PressOther Book-Related InformationWebsite for this book: www.mobilepythonbook.comMobiLenin Python for S60 tutorials: www.mobilenin.com/pys60/menu.htmMobileArtBlog: www.mobileartblog.comOfficial Python for S60 page: http://opensource.nokia.com/projects/pythonfors60Python for S60 wiki: http://wiki.opensource.nokia.com/projects/Python for S60This is the best source for PyS60 material.304REFERENCESForum Nokia Wiki: http://wiki.forum.nokia.com/index.php/Category:PythonPython for S60 API documentation: http://sourceforge.net/projects/pys60The PyS60 documentation can be downloaded in PDF format.Python for S60 IRC channel: #pys60 at freenode.netPython for S60 discussion forum: http://discussion.forum.nokia.com/forum/forumdisplay.php?forumid=102Python Tutorials and DocumentationPeters, T.
(2004) ‘Zen of Python’ at www.python.org/dev/peps/pep-0020Pilgrim, M. (2004) Dive into Python. Apress at www.diveintopython.orgA free web book for experienced programmersScheible, J. (2007) ’Python for S60 tutorial’ at www.mobilenin.com/pys60/menu.htmvan Rossum, G. (2001) ‘Python Style Guide’ at www.python.org/dev/peps/pep-0008A comprehensive Python language lesson: http://docs.python.org/tutOfficial Python Library Reference: http://docs.python.org/libThis reference contains information about all standard modules that arenot described in the PyS60 documentation. Note that only functionsthat are available for versions of Python before version 2.3 are availablein PyS60 now.Python Imaging Library (PIL): www.pythonware.com/products/pilTwisted: http://twistedmatrix.comA Python framework for building custom server softwareJabber: www.jabber.org and www.xmpp.org/rfcs for protocol documentationBeautiful Soup: www.crummy.com/software/BeautifulSoupA Python HTML/XML parserGlossaryApplicationA program including a user interface that allowsrich interaction with the userCarrierA mobile network operatorCell phoneA mobile phoneConsoleUser interface of the Python for S60 scriptshell – either on the phone or on the PC overBluetoothEventAn external event, such as the user pressing a keyor an SMS message arriving, that causes theprogram to react, typically by way of a callbackfunctionInterpreterA computer program that executes Python code;you have to install the Python for S60 interpreteron a phone to run Python programsLibraryEquivalent to a module or a collection of modulesMMSMultimedia message service; an extension to SMSthat allows sending of images and sounds or otherrich types of dataMobile networkoperatorA company that provides services for mobilephone subscribersMobile phoneA personal handheld communication device;modern mobile phones, especially smartphones,provide many functionalities, such as webbrowser, email, camera and music player, inaddition to normal telephone functions306GLOSSARYModuleA file that contains a collection of relatedfunctions and data grouped together; a programmay import a module (unlike an object) only onceand cannot handle several instances of the samemoduleObjectA basic building block of programs that containsboth data (variables) and functions that are used tomodify the data; practically everything in Pythonis an object, including strings, lists and functionsProgramA generic term for executable Python for S60code; scripts and applications are types ofprogram; modules are not programs, since theycannot be executed as suchPyS60Abbreviation for Python for S60PythonA high-level programming language whichemphasizes the importance of programmer effortover computer effort and prioritizes readabilityover speed or expressiveness; comes with a largelibrary of extension modules; Python programs areexecuted by the Python interpreterPython for S60The Python programming language on the S60smartphone platform; includes the core Pythonlanguage, many of Python’s standard modules anda wide range of additional modules for accessingthe phone’s features, such as camera andnetworkingS60A software platform for mobile phones based onthe Symbian operating system; handles manyhigh-level tasks, such as building user interfaces,on top of Symbian OS; all current high-end Nokiamobile phone models are based on the S60platform.ScriptA small program that is typically used to automatea single task; performs little or no interaction withthe userSmartphoneA mobile phone that uses the S60 platform; moregenerally, a smartphone is a mobile phone withPC-like functionalitySMSShort message service, often called textmessaging; a way to send 160 characters of textfrom one mobile phone to anotherGLOSSARY307Symbian OSAn operating system designed by Symbian formobile devices; all current Nokia high-endmobile phone models are based on Symbian OSThreadA way to execute several tasks at the same time ina program; for example, one thread may listen tonetwork events while another handles the userinteractionUIUser interface, made up of graphical elements,such as buttons, dialogs, menus and so on, thatallow the user to affect program behaviorUnicodeAn industry standard allowing computers toconsistently represent and manipulate textexpressed in any of the world’s writing systems; inPython, Unicode strings are prefixed with theletter u, for example, u'käärmekännykkä'; inPython for S60, interfaces to the phone’s featuresexpect Unicode strings instead of normal stringsExamples1First PyS60 program2Various dialogs3Various notes4Multi-query dialog5Popup menu6Selection list7Multi-selection list8Shopping list assistant9Two dialogs10First function11First application12Application menu13SMS voter14SMS inbox15Inbox search16Inbox sorter17SMS receiver18Filtering SMS gateway19Hangman server (1/3)310EXAMPLES20Hangman server (2/3)21Hangman server (3/3)22Text to speech23MP3 player24Blocking MP3 player25MIDI player26Sound recorder27Animal sounds28Binding a keycode to a callback function29Key events30Key pressed or held down31Graphics primitives32Screenshot33Moving graphics34Viewfinder35Minimalist camera36Taking photos with a viewfinder37UFO Zapper (1/3)38UFO Zapper (2/3)39UFO Zapper (3/3)40Creating a directory for application data41Basic file operations42Read a sound43Read an image44Read a video45Read and write text46Writing a dictionary to a file47Read a dictionary from a file48Local database49Retrieve the current GSM cell ID50GSM location applicationEXAMPLES51Vocabulector (1/3)52Vocabulector (2/3)53Vocabulector (3/3)54OBEX discovery55RFCOMM discovery56Send photos to another phone via Bluetooth57Bluetooth chat (1/2)58Bluetooth chat (2/2)59Bluetooth client60PySerial script running on PC61AppleScript interface running on Mac62GPS reader63Telephone64Contacts65Sysinfo66Web downloader67Web file viewer68Photo uploader69Test server70TCP client71Yahoo! Web service test72Set the default access point73JSON photo client74JSON photo server75HTTP server (1/2)76HTTP server (2/2)77Phone’s IP address78Voting server79Voting client80Generic JSON gateway (1/2)81Generic JSON gateway (2/2)311312EXAMPLES82Instant messenger (1/3)83Instant messenger (2/3)84Instant messenger (3/3)85Phone–web proxy86Phone–web server87MopyMaps! (1/3)88MopyMaps! (2/3)89MopyMaps! (3/3)90EventFu (1/5)91EventFu (2/5)92EventFu (3/5)93EventFu (4/5)94EventFu (5/5)95InstaFlickr (1/6)96InstaFlickr (2/6)97InstaFlickr (3/6)98InstaFlickr (4/6)99InstaFlickr (5/6)100InstaFlickr (6/6)101List comprehension102SMS search using list comprehensions103Input sanitization using list comprehensions104Dictionary constructor105Symbol table106Introspective web service107Importing a custom module108Updating PyS60 code from the web109Plugin mechanism110MobiLenin (1/2)111MobiLenin (2/2)112MobiLenin server-side PHP scriptEXAMPLES113Manhattan Story Mashup custom list element114MobileArtBlog (1/3)115MobileArtBlog (2/3)116MobileArtBlog (3/3)117Server-side PHP script118PHP script for MySQL database insert119LED on/off120Arduino code LED on/off121Max/MSP using Bluetooth (1/2)122Max/MSP using Bluetooth (2/2)123Max/MSP using TCP/IP124OSC for mobile phones125Roombatics (1/2)126Roombatics (2/2)127See the error?128Syntax error313Python Language LessonsThese lessons teach basics of the Python programming language in anutshell.Python FeatureSectionCallback function4.2Catching exceptions6.1Dictionary6.2For loop3.2Function4.1If statement3.2List3.2Local and global variables4.5Module3.1Object4.2Print statement3.2Tuple4.2Variable3.2While loop and break3.2Python for S60 ModulesThe following modules are used in this book.