Example SMS receiver
def message_received msg_id box inbox.Inbox appuifw.note uNew message s box.content msg_id app_lock.signal box inbox.Inbox box.bind message_received print Waiting for new SMS messages app_lock e32.Ao_lock app_lock.wait print Message handled The Inbox object's bind function binds a callback function to an event that is generated by an incoming message. In this example, the function message_received is called when a new message arrives. The callback function takes one parameter, namely the ID of...
Capturing any Key Event on Your Phone
The keycapture module offers an API for global capturing of key events. With this module, you can react to key events even if some other S60 application is active and your PyS60 program is running only in the background. For instance, you could have a key combination that triggers an action regardless of the application that you are using on the phone. The keycapture module provides a KeyCapturer object that is used for listening to the events by way of a callback function. The callback is...
Updating Events using the Eventful API
The Eventful Web API is used to retrieve events according to the user's preferences. Titles of the retrieved events are presented in a list, like the one that is shown in Figure 9.2 b . The list is constructed by the function update_list that is presented in Example 92. lprefs 'app_key' APP_KEY, 'page_size' '10' appuifw.app.title uUpdating s prefs.get 'Location', url SEARCH_URL urllib.urlencode lprefs events json.read res 'events' 'eventl listbox.set_list titles appuifw.app.title prefs...
How to Use the Emulator
You download the PyS60 Interpreter installation files from http source forge.net projects pys60. You must download the correct version for 2nd or 3rd Edition of S60 . If you are not sure which one you need, check Table D.1 to find your phone model. You will also find a device overview at http forum.nokia.com. Here are the steps to take to use the emulator 1. Download and install the correct S60 Developer Platform Software Development Kit SDK which includes the emulator. The SDK can be found at...
Introspection
One of the great strengths of a dynamic programming language, such as Python, is that it is possible to examine and even manipulate the program code at run-time. The idea of introspective programs may sound esoteric and mind-bending, but on examination it provides a clean way to solve some rather mundane tasks. The core idea is simple given that your program includes a function or an object named xyzzy, you can use the string xyzzy to access that object, rather than specifying the name in your...
Examples 1
Hangman server 2 3 Hangman server 3 3 Text to speech MP3 player Blocking MP3 player MIDI player Sound recorder Animal sounds Binding a keycode to a callback function Key events Creating a directory for application data Retrieve the current GSM cell ID GSM location application 56 Send photos to another phone via Bluetooth 60 PySerial script running on PC 61 AppleScript interface running on Mac 72 Set the default access point SMS search using list comprehensions Input sanitization using list...
MobiLenin Mobile Client Code
Although you can't get this code to work since you are missing all the back-end applications, we want to give a rough explanation here to highlight how it was possible to rapidly prototype a project like MobiLenin with PyS60 in a matter of 2-3 days. The script is divided into two parts for better display Examples 110 and 111 . It might not contain the most elegant code, nevertheless it worked, served its purpose and shows you that you can program things in Python in many different ways. You are...
Example MobiLenin
import httplib, urllib, appuifw, e32, graphics, key_codes if event 'keycode' key_codes.EKeyLeftSoftkey win_state 0 def show_picture picture canvas.blit picture choices uClap, uResign, uGuitar, uSing, uCrazy, choice appuifw.popup_menu choices, uSelect press OK choice_conversion 0 'A1, 1 'B1, 2 'C1, 3 'D1, 4 'E1, 5 'F' params urllib.urlencode 'data' choice_conversion choice , 'eggs' 0, 'bacon' 0 headers Content-type Accept text plain conn 0 conn.request POST, params, headers conn.close tempfile E...
SMS Inbox
Even though a large number of today's mobile phones support various Internet protocols, from VoIP and instant messaging to HTTP, only SMS can guarantee smooth interoperability between all devices, including old models. It is reasonable to assume that every mobile phone user knows how to send and receive SMS messages. Because of this, SMS messages are still widely used to interact with various services, from buying bus tickets to television shows and online dating. Let your imagination free and...
Connecting to GPS over Bluetooth
In this section, we connect to an external Bluetooth GPS reader to acquire GPS data see Figure 7.4 . Some modern mobile phones, such as Nokia N95, come with an integrated GPS receiver. You can use PyS60 to obtain information from the internal GPS, as described in Section 6.4. Unfortunately, accessing the internal GPS requires some capabilities that are not available for the self-signed PyS60 interpreter see Appendix A for more information . In contrast, you can use an external GPS receiver...
Connecting a Phone to MaxMSP using Bluetooth RFCOMM
The patch of the Max MSP graphical programming environment is shown in Figure 11.8. An object with the text 'serial a 9600' handles the serial port communication in Max MSP. When you start Max MSP, this object opens one of the free serial ports of your computer. You might have to check some additional parameters in your computer's Bluetooth setting if it doesn't work straight away. We cannot explain here the full functionality of the patch in detail, but the basic idea is that when the serial...
Example Contacts
import contacts, appuifw, telephone name appuifw.query u'Call to', 'text' db contacts.open entries db.find name names index appuifw.selection_list names, search_field 0 num entries index .find 'mobile_number' if num appuifw.note u'Missing mobile phone number', 'error' Similar functionality was used in the Hangman SMS server in Section 4.5.
Python Tutorials and Documentation
Peters, T. 2004 'Zen of Python' at www.python.org dev peps pep-0020 Pilgrim, M. 2004 Dive into Python. Apress at www.diveintopython.org A free web book for experienced programmers Scheible, J. 2007 'Python for S60 tutorial' at www.mobilenin.com pys60 menu.htm van Rossum, G. 2001 'Python Style Guide' at www.python.org dev peps pep-0008 A comprehensive Python language lesson http docs.python.org tut Official Python Library Reference http docs.python.org lib This reference contains information...
Installation for Mac OS X Users
1. Install the downloaded .SIS files to your phone Connect your phone to your computer using the USB cable, then select 'Data transfer' or 'Mass storage' mode on the phone screen. The memory card of the phone is mounted as an external 'hard drive' and its content can be accessed by the Finder application on the Mac. You must have the memory card inserted into your phone. Copy the downloaded installation files to any folder on the memory card of your phone, for example, to the root. Safely...
Example Web downloader
The 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 use the urllib.urlopen function, which returns the file contents to your program so that they can be further processed. On the other hand, if you want to download a file from the web and save it locally, you can use the urllib.urlretrieve function to save the file directly to a given file name, as shown...
Example Retrieve the current GSM cell ID
You should see a tuple of four integers whose values depend on your current location. The first two integers correspond to the Mobile Country Code MCC and Mobile Network Code MNC . A comprehensive mapping of MCC and MNC codes to country and operator names can be found in the Wikipedia article 'List of GSM Network Codes'. The last two integers correspond to the GSM area code and the current GSM cell ID. Many different cell IDs may map to a single area code, which, in urban environments, may...
JSON Client
From Python's perspective, the TCP protocol only transfers strings between hosts. The HTTP protocol transfers strings as well, but it includes a simple method to encode key-value pairs, in practice a dictionary object, to a request string using the urllib.urlencode function. Technically speaking, this should suffice for all applications - assuming that every application finds a way to encode its internal data structures to strings and back. However, as there is only a small number of basic data...
Why Does Python Make a Difference
Only skilled and experienced programmers were previously able to build mobile applications using C or Java. As a result, many people often gave up early or never really started. The emergence of Python for S60 offers a crucial turning point, as it brings the Python programming language to the mobile space. This makes mobile development approachable for many new developers that were previously excluded. Python for S60 can drastically reduce development time it allows development with completely...
A Creating a Standalone Python Program
The Python for S60 SDK comes with a tool called py2sis that can be used to create SIS packages from PyS60 programs. To use py2sis, you need S60 C SDK, 3rd Edition, Maintenance Release The tool is installed in the directory epoc32 tools py2sis. To turn a simple 'hello world' program into a SIS package perform the following steps 1. Pick a UID for your program. A UID is a 32-bit number that identifies a given Symbian program and all programs installed in a device must have a unique UID. For use...
Event Form and Event Description
Figure 9.2 c shows the event form which is constructed by the function show_event see Example 93 . The form shows a subset, specified in EVENT_FIELDS, of event attributes that are returned by Eventful. Usually we hard-code the structure of UI elements in our applications but, as shown by this example, we can construct the elements on the fly as well as based on some external data. First, however, we make the attribute names more readable by converting their first characters to upper case and...
Example MaxMSP using Bluetooth
import appuifw, e32, graphics, key_codes, socket slidershaft graphics.Image.open e background.jpg makeMaskTemp jpg' makeMaskTemp.save e controller_mask.png, bpp 1 contrMask graphics.Image.new size 97,149 ,mode '1' contrMask.load e controller_mask.png contr graphics.Image.open e controller.jpg makeMaskTemp graphics.Image.open 'e button_mask.jpg' makeMaskTemp.save e button_mask.png, bpp 1 buttnMask graphics.Image.new size 111,78 ,mode '1' buttnMask.load e button_mask.png buttnOn...
Example Binding a keycode to a callback function
import appuifw, e32, key_codes def up appuifw.note uUp arrow was pressed appuifw.note uKey 2 was pressed canvas appuifw.Canvas appuifw.app.body canvas canvas.bind key_codes.EKeyUpArrow, up canvas.bind key_codes.EKey2, two appuifw.app.exit_key_handler quit app_lock e32.Ao_lock app_lock.wait Figure 5.3 Overview of keycodes and scancodes Figure 5.3 Overview of keycodes and scancodes The canvas.bind function binds a keycode to a callback function. For example, canvas . bind key_cod.es ....
Binding a Keycode to a Callback Function
In this approach, we bind a callback function to respond to a specific key event. The key is identified by a keycode. For each key on the keyboard there exists at least one keycode that corresponds to a particular character or action, as shown in Figure 5.3. Note that a single physical key may produce many different characters thus, many different keycodes may correspond to a single key. The keycodes are defined as constants in the module key_codes. You can find an overview of often used...
ArduinoBT MicroController Board
As mentioned in Chapter 7, it is possible to connect your phone to a micro-controller. The 'ArduinoBT board' Figure 11.7 is an example of a micro-controller board with Bluetooth extension chip that offers serial port communication. Arduino is an open-source physical computing platform based on a simple I O board and a development environment for writing Arduino applications www.arduino.cc . The Arduino programming language is an implementation of Wiring http wiring.org.co , based on Processing...
Example Telephone
If you start recording sound when a call is active, the phone call is recorded. See Example 26 for a simple sound recorder that can easily be combined with the telephone module. Ethical implications are left as an exercise for the reader. The contacts module offers an API to the phone's address book. Although in the simplest form the address book could be a dictionary, which has names as keys and phone numbers as values, the modern mobile phone provides a sophisticated database which can handle...
Python Language Lesson for loop
The for loop goes through the items of a list. In the example below, we define a list of foods. Then we loop through the food items one by one, printing each of them to the screen. The for loop goes through the items of a list. In the example below, we define a list of foods. Then we loop through the food items one by one, printing each of them to the screen. This almost reads like English 'For x every element in the list of foods, print the name of x'. When executing this for loop, the...
Using an event loop to control an application
At the beginning of Chapter 4, we noted that we have to use the e32.Ao_lock object to stop the execution and start waiting for the user input. However, in an action game something should be happening all the time, even if the user does nothing. Thus, instead of a lock, the game application is controlled by an event loop. An event loop is typically a simple while loop which takes care of advancing time step by step. Like Ao_lock, the loop prevents the application from exiting instantly. Whereas...
Example OBEX discovery
The output of the example is something like this Chosen device 0 0 12 d2 41 35 e4 uOBEX Object Push 9 In this case, the target device, whose address is contained in the string address, has only one OBEX service available, OBEX Object Push on channel 9. This service is used to transfer files between devices. If no services were available on the target device, the function would have raised an exception. The service names are standardized, so if you are interested in only the OBEX Object Push...
Example Send photos to another phone using Bluetooth
PHOTO ue lmages Ybt_photo_send.jpg address, services socket.bt_obex_discover except appuifw.note uOBEX Push not available, error return channel services u'OBEX Object Push' socket.bt_obex_send_file address, channel, PHOTO appuifw.note uphoto sent, info else appuifw.note uOBEX Push not available, error photo camera.take_photo canvas.blit photo, scale 1 photo.save PHOTO canvas appuifw.Canvas appuifw.app.body canvas appuifw.app.exit_key_handler quit appuifw.app.title uBT photo send...
A Capabilities
In a device that uses Platform Security, a program must have permission to access potentially sensitive features. In Platform Security jargon, these permissions are called capabilities. A program has to hold a certain capability to access a certain set of sensitive features. Not all features require capabilities - there are many things you can do without holding any capabilities at all. Almost all the examples in this book, except GSM locationing, do not require special capabilities. There is a...
Constants and Result Parsing
import urllib, appuifw, e32, graphics, key_codes, os, os.path APP_ID MAP_URL MAP_FILE uE lmages mopymap.png if not os.path.exists E lmages os.makedirs E lmages def naive_xml_parser key, xml key key.lower for tag in xml.split lt tokens tag.split if tokens and tokens 0 .lower .startswith key return tag.split gt 1 .strip return None Three constants are used by the appl ication app_id is the appl ication ID that you got from the Yahoo developer site. Replace the string in the example with your...
Example Bluetooth client
import appuifw, socket, e32 ECHO True def choose_service services names channels for name, channel in services.items names.append name channels.append channel index appuifw.popup_menu names, uChoose service return channels index def read_and_echo fd buf r while r n and r r r fd.read 1 if ECHO fd.write r buf r if ECHO fd.write n return buf address, services socket.bt_discover channel choose_service services conn socket.socket socket.AF_BT, socket.SOCK_STREAM conn.connect address, channel to_peer...
Example Arduino code LED onoff
int RESET 7 reset pin for bluetooth int val 0 initial serial port data Reset the bluetooth interface digitalWrite RESET, HIGH delay 10 digitalWrite RESET, LOW delay 20 00 void setup reset_bt pinMode LED,OUTPUT pinMode RESET,OUTPUT Serial.begin 1152 00 val Serial.read if val -1
Example SMS inbox
import inbox, appuifw box inbox.Inbox for sms_id in box.sms_messages 5 msg box.content sms_id appuifw.note msg Besides the familiar appuifw module, which is needed for showing notes, we need to import the inbox module that encapsulates access to the SMS inbox. All functions related to receiving SMS messages belong to the Inbox object which is created with the inbox.Inbox function. To read an individual SMS message, you need to know its message ID. The Inbox object's function sms_messages...
GSM Cell ID Mapper
We present a simple application that can be used to record positioning data and to retrieve your current location, based on GSM cell IDs. The example is based on the GSM cell IDs because of the ubiquity of the technique. Only a few phones have an internal GPS receiver as of 2007 but every GSM phone can be used to retrieve GSM cell IDs. This application allows you to collect cell IDs and give them names according to your actual location. The mapping from the detected cell IDs to their locations...
SingleField Dialog query
Syntax query label, type , initial value Example code appuifw.query uType a word , text, uFoo This function shows a single-field dialog. The dialog can include some instruction text that is passed as a string by putting the u in front of the string to the parameter, label. The type of the dialog is defined by the parameter, type. The value of type can be any of the following strings text, number, date, time, code, query or float see Figure 3.1 . Copyright c ' 2000 BeOpen.corn. All Right...
Example GSM location application
import appuifw, e32, location, time, os.path PATH uE Data gsm_loca if not os.path.exists PATH os.makedirs PATH CELL_FILE PATH known_cells.txt LOG_FILE PATH visited_cells.txt log file LOG_FILE, a timer e32.Ao_timer gsm_loc location.gsm_location return d d d d gsm_loc loc current_location if loc in known_cells here known_cells loc print You are currently at, here else print Unknown location, loc print gt gt log, time.ctime , loc, here timer.after INTERVAL, show_location name appuifw.query uName...
The Process of Rapid Prototyping with Python S
Python for S60 can be seen as an ideal prototyping tool. Turning an idea or concept into code for a working software prototype can be done in weeks, if not days. Many fully functioning code examples, such as the ones found in this book, can be used as a springboard to get started with the rapid prototyping process. Rapid prototyping with Python for S60 may save many development costs allow a developer team to turn several ideas into prototypes within budget and time limits, instead of building...
Mobile Game UFO Zapper
The concluding example of this chapter is a game. In contrast to the Hangman server that was presented in Section 4.5, this is a classic singleplayer action game with stunning graphics - just see Figure 5.9. Your job is to save the world from a squadron of invading UFOs with a moving pad that shoots laser beams ahem . You must shoot down as many UFOs as possible within a given time limit. You get points for each hit the smaller the UFO you hit the more points you get. Try to beat our highest...
Setting the Default Access Point
After trying out the previous examples, you have seen that PyS60 shows the access point selection menu, like the one in Figure 8.4, almost always when a new network connection is about to be opened. On some phone models, the menu is shown only the first time when a network connection is opened on the PyS60 interpreter and the interpreter must be restarted to choose another access point. PyS60 provides the necessary functions, as a part of the socket module, to set a desired access point...
Bluetooth Pairing
Security concerns mean that it is a good habit to pair any two devices before you connect them using Bluetooth. Pairing need be done only once for any two devices. The manual of your mobile phone contains instructions on how to do this. Typically, you can initiate pairing on the phone side in the Bluetooth configuration dialog. The basic idea is that the phone shows a dialog asking you to type a passcode for the device - you can type any code you like. The other device should also show a dialog...
Popup Menu popupmenu
Syntax popup_menu list , label Example code appuifw.popup_menu choices, uSelect The popup_menu function displays a list of items in a popup dialog. You need to give a list of Unicode strings in the parameter list. You can also define a label which is the text that appears at the top of the list. This function returns the index of the chosen item in the list. If the user cancels the dialog by pressing Back, None is returned. Create a script see Example 5 that displays a popup menu with three...
Example GPS reader
address, services socket.bt_discover print Discovered s, s address, services target address, services.values 0 conn socket.socket socket.AF_BT, socket.SOCK_STREAM to_gps conn.makefile r, 0 if msg.startswith GPGGA gps_data msg.split , lat gps_data 2 lon gps_data 4 break print You are now at latitude s and longitude s lat, lon This example is based on techniques that are already familiar to you from the previous examples. First, you choose the GPS receiver from the list of discovered devices. It...
Double buffering
Double buffering is a traditional method to prevent flickering when moving graphics are shown. This method was used to handle redrawing of the Canvas object. As in the previous examples, instead of drawing the game elements to the Canvas object directly, we have a separate image object, buf, to which all elements are drawn at first. Only when everything has been drawn to the image buffer are the contents of the second buffer shown on the canvas using canvas.blit buf . This way the user does not...
Example MaxMSP using Bluetooth 1
img.blit slidershaft, target 0,0,w,h img.blit contr, target 142,y_pos_contr , mask contrMask if sound 1 img.blit buttnOn, target 8,328 , mask buttnMask else img.blit buttnOff, target 8,32 8 , mask buttnMask canvas.blit img, target 0,0,w,h , scale 1 def choose_service services names for name, channel in services.items names.append name channels.append channel index appuifw.popup_menu names, uChoose service return channels index address, services socket.bt_discover channel choose_service services...
Example Using the eventcallback function
if event 'keycode' key_codes.EKeyUpArrow appuifw.note uUp arrow was pressed elif event 'keycode' key_codes.EKey2 appuifw.note uKey 2 was pressed canvas appuifw.Canvas event_callback keys appuifw.app.body canvas appuifw.app.exit_key_handler quit app_lock e32.Ao_lock app_lock.wait When the user presses a key, the canvas receives a key event and generates a dictionary object which is handed to the keys function through the parameter event. This object holds information about the key that produced...
Example Local database
DB_FILE uc python test.db db e32dbm.open DB_FILE, cf db uhost uwww.google.com db uport u80 db uMusernamej umusli db upassword umy secret db.close db e32dbm.open DB_FILE, r for key, value in db.items print KEY, key, VALUE, value db.close print Writing db write_db print Reading db read_db As you can see, the local database module, e32dbm, behaves like a mixture of a file and a dictionary it is opened like a file and accessed like a dictionary. Note that the database has native support for Unicode...
Storing Preferences
Choices in the preference form are saved in a local database, so the user does not have to type them in every time she starts the application. Local databases were first introduced in Section 6.3. They look and behave like an ordinary dictionary. However, in contrast to dictionaries, which are destroyed when the application closes, local databases are backed up to a file. Example 91 shows the function save_pref s that saves the current preferences. The function is given a dictionary new_pref s...
Example Manhattan Story Mashup custom list element
self.img.rectangle self.area, fill WHITE x self.area 0 10 y self.area 1 LIST_FONT 1 sel_y self.area 1 self.idx LIST_FONT 1 5 self.img.rectangle sel_x, sel_y, self.area 2 , sel_y LIST_FONT 1 4 , fill YELLOW self.img.text x, y , u empty list , font LIST_FONT, for item in self.list self.first_vis self.first_vis txt u s self.filter item self.img.text x, y , txt, font LIST_FONT, fill BLUE y LIST_FONT 1 5 if self.first_vis self.nof_visible lt len self.list x self.area 2 - 30 y self.area 3 - 30...
Set up the Arduino software
1. Download the Arbuino software from www.arduino.cc and install it on your computer. 3. Select 'microcontroller mcu ' and set it as 'atmega168'. 5. Select 'Serial port' and then the Bluetooth port that you created earlier, for example, dev tty.arduinobt-bluetoothseri-1. Now you need to write your code for the board using the Arduino software. There are plenty of tutorials available on how to do this, for example, at www.arduino.cc .





