Example AppleScript interface running on Mac

ALLOWED_SCRIPTS edit ser serial.Serial ' dev tty.pybook' print Waiting for message while True msg serial.readline .strip if msg exit print gt gt serial, bye break print Running script msg os.system osascript s.script msg print gt gt serial, Script ok The idea is that the phone client is used to choose one of the scripts to execute on the PC side. Once again, we can use Example 59 as the phone client. Again, echoing should be disabled by setting ECHO False in the client. In Python, the os.system...

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...

Simple PlugIn Mechanism

We may take automatic updating even further. Not only can you download PyS60 modules from the web using Python, but you can also decide which modules to import at run time. This makes your applications infinitely extensible. Depending on the user input, the physical environment or any other parameter, you can make your application request new functionality from the web. This leads to opportunities that come from science fiction, but, in simple terms, it allows you to easily make a plug-in...

Dictionary Constructor

Besides lists, another data type that can be found in almost every Python program is a dictionary. The most typical use for the dictionary is to get a value, given the corresponding key, in an efficient manner. However, sometimes you can just use the fact that the dictionary cannot contain duplicate keys. For example, you can count the number of distinct items in a list as follows a 1, 2, a, 1, b, 2, The output is 4 in this case. As with the lists above, it may feel unnecessarily verbose to use...

C Debugging Procedure

How 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. You should restart the program and repeat the steps that led to the problem to make sure that you have correctly recognized the context in which the bug occurs. You can repeat this many times if you like, maybe with slightly varying input to collect more information on the nature of the...

Robotics

With a little creativity, a modern mobile phone can be used as a compact and capable robot brain. Besides having respectable computing power for an embedded device, the phone has the basic sensory functions built-in the camera can function as eyes and the microphone as ears for the robot. Because of its small size, the phone can easily be mounted on various platforms for locomotion, which may be controlled, for instance, over Bluetooth. Nowadays, using cheap off-the-shelf parts, one can start...

Python Language Lesson list

A list is an ordered set of values. The values that make up a list are called its elements or items. The items can be of any type, such as strings or integers. Items of the list do not have to be of the same type, so you can have a list that contains both strings and integers. There are several ways to create a new list. The simplest is to enclose the elements in square brackets mylist uSymbian, uPyS60, uMobileArt Each item in the list can be accessed by its index in square brackets after the...

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 and GPS Positioning

Applications based on positioning are often claimed to be the most likely killer applications of the mobile platform. PyS60 gives you access to practically all public positioning techniques that are available for the current S60 mobile phones. As of 2007, the most typical positioning techniques are the following external GPS over Bluetooth, as described in Section 7.5 internal GPS, using the position module GSM cell IDs, using the location module SMS-based positioning using the messaging...

Reading and Writing Unicode Text

Both Symbian OS and the S60 platform are designed for world-wide use. Consequently, every part of the system that deals with text in any form, is designed to handle text written in any language, using any character set. Unicode is a standard that defines how the world's writing systems should be handled on computers. Unicode is natively supported by the Symbian and S60 platforms, as well as by PyS60. As you have seen, practically all functions in the PyS60 API that handle strings require that...

Capabilities available with a free developer certificate devcert are

capabilities with which you can experiment on a single phone using a devcert available from the Symbian Signed service for free. However, packaging a program that needs these capabilities into a SIS file that would install to any phone can only be done through the Symbian Signed process. Manufacturer-approved capabilities are highly sensitive capabilities that can only be obtained from the device manufacturer, even if it's just for experimenting on your own phone. Getting these capabilities...

JSON Gateway

We implement a server actually, a gateway that acts as a middle man between phones. Since the gateway runs on your PC or on some external server , you need to have Python installed there as well. Phones may send any JSON messages to each other, by way of the gateway. With this gateway, it is possible to implement peer-to-peer networking in PyS60. In technical terms, the gateway works as follows Each client maintains a persistent TCP connection to the central server. When a client opens a new...

Example MaxMSP using TCPIP

HOST '192.168.1.100' The remote host PORT 9000 The same port as used by the server s socket.socket socket.AF_INET, socket.SOCK_STREAM print data send , data s.close We create a TCP IP socket with s socket. socket socket. AF_ INET, socket. SOCK_STREAM and use it to connect with s . connect host, port to an IP socket on our computer identified by the IP address HOST . We choose port 9000 for communication. Sending the control strings '51', '52' and '53' is done through s.send data . In Figure...

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 ....

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...

Connecting a Phone to MaxMSP using Bluetooth RFCOMM

Graphical Slider

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...

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...

SMS Sorter

Besides the message content, it is possible to fetch the timestamp, the sender's phone number address and information on whether the message has been read already using the Inbox object. To show how to use these functions, we make an application that includes an Exit key handler, an application title and a menu. This application can be used to sort your SMS inbox according to various attributes of text messages. You can choose, using the application menu, whether the messages should be sorted...

MultiQuery Dialog multiquery

Syntax multi_query labell, label2 Example code appuifw.multi_query uFirst name , uLast name This function displays a two-field text input dialog. The input parameters label1 and label2 can be pre-defined by inserting Unicode strings. The multi_query function returns the values that the user inputs. The values of the upper and lower input fields are jointly returned as a tuple. In Python, a tuple is a comma-separated list of values, for example datal, data2 . We learn more about handling tuples...

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...

Recording Animal Sounds

animals udog, ucat, ucow def record_animal_sounds for animal in animals index appuifw.popup_menu animals, uSelect play_animal_sound u'e animals index funny_noise audio.Sound.open soundfile This time, you have to record sounds of the three animals when the script starts. This is handled by the function record_animal_sounds which loops over the list of animals, animals. After this, the function select_sound presents a menu that lets you choose a sound to play. Note that the sounds are saved to...

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...

Example Bluetooth chat

server socket.socket socket.AF_BT, socket.SOCK_STREAM channel server.bind , channel server.listen 1 server, True, socket.RFCOMM socket.set_security server, socket.AUTH socket.AUTHOR print Waiting for clients conn socket.socket socket.AF_BT, socket.SOCK_STREAM address, services socket.bt_discover print Connected to server appuifw.note uTarget is not running a btchat server, The function chat_server may look a bit convoluted, but actually it just performs some housekeeping to prepare the system...

Camera

cameras_available returns the number of cameras available in the device. image_modes returns the image modes supported by the device as a list of strings, for example RGB12, RGB16, RGB the last one corresponds to full-color images . image_sizes returns the image resolutions supported by the device as a list of w, h tuples, for example 640, 480 , 160, 120 . f lash_modes returns the flash modes supported by the device as a list of strings. max_zoom returns the maximum digital zoom value...

Authors Acknowledgments

We'd like to express our gratitude to all the people who played a part in developing this book. First, we'd like to thank the editors that worked on this project Satu McNabb at Symbian Hannah Clement, Andrew Kennerley and Rosie Kemp at Wiley and Shena Deuchars at Mitcham Editorial. We'd also like to thank Wiley and Symbian, in general, for supporting this book project. We are glad to be part of it. Thanks also to everyone who took part in the early review of this book Joe McCarthy, Panos...

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...

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...

OBEX and RFCOMM

There are two main ways to communicate over Bluetooth with PyS60. OBject EXchange OBEX is suitable for transferring files, such as photos or sounds, over Bluetooth. Radio Frequency COMMunication RFCOMM is useful for sending and receiving streams of text and raw data, including protocols of your own. To send anything over Bluetooth, you have to know the recipient's Bluetooth address, which is represented in a string, such as 00 12 d2 41 35 e4. You can find Bluetooth devices and their addresses...

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...

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 Key pressed or held down

global clicked, key_down if event type appuifw.EEventKey if key_down key_down event keycode , down else key_down event keycode , pressed elif event type appuifw.EEventKeyUp and key_down code, mode key_down if mode pressed def key_clicked code global clicked if code clicked clicked None return True return False if key_down and key_down code, down canvas appuifw.Canvas event_callback handle_event appuifw.app.body canvas appuifw.app.exit_key_handler quit if key_clicked key_codes.EKeyUpArrow...

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 Roombatics 1

print START DRIVING 250mm s WITH RADIUS 2000mm LEFT roomba.write intcmd 137,2 50,20 00 print GETTING SENSOR READING BYTES sensor_bytes time.sleep 1 keep driving for an extra second print STOPPING - DRIVING WITH VELOCITY 0 print BACK TO ROOTOOTH COMMAND MODE if roomba.read 6 r nOK r n raise Exception back failed Examples 125 and 126 include a simple PyS60 script that drives Roomba forward, requests some sensor readings from it and stops. Besides showing what the Roomba control code looks like in...

Installation for Windows Users

We assume you have the Nokia PC Suite application installed on your Windows computer. It connects your Nokia phone to your Windows PC for fast file transfer and smooth synchronization. If you have not installed it yet, we recommend doing so now. Most new phones come with the Nokia PC Suite software on a CD. You should download the latest version from Nokia's website, for example, at www.nokia.com A4144903. If you do not have Nokia PC Suite available or you have no USB cable, check Sections...

Example Inbox sorter

def show_list msgs msgs.sort items for msg in msgs items.append msg 1 15 appuifw.selection_list items msgs.append -box.time sms_id , box.content sms_id show_list msgs msgs.append box.address sms_id , box.content sms_id show_list msgs msgs.append -box.unread sms_id , box.content sms_id show_list msgs print INBOX SORTER EXITS app_lock.signal appuifw.app.exit_key_handler quit appuifw.app.title uInbox Sorter appuifw.app.menu uSort by time, sort_time , uSort by sender, sort_sender , uUnread first,...

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 Plugin mechanism

URL def download_plugin plugin_name filename plugin_name .py code urllib.urlopen URL filename .read f file uE Python Lib filename, w f.write code f.close plugin_name appuifw.query uGive plug-in name, text print Downloading plugin, plugin_name plugin download_plugin plugin_name Example 109 wraps the download functionality of Example 108 in the function download_plugin . As in the previous example, it downloads a PyS60 source code file from a specified URL on the web and saves it to a local...

Python Terminology in this Book

In this book, the term 'Python' may refer to three different concepts see Figure 1.2 . Figure 1.2 a shows the Python programming language, which is the same both on a PC and a phone, although the PC cannot access the phone's functionalities. Figure 1.2 b shows Python for S60, which runs, or interprets, the Python language on the S60 smartphone platform and provides interfaces to the phone's functionalities. Figure 1.2 c shows a Python interpreter that is used to run Python on a PC. In some...

Instant Messenger

A natural application for peer-to-peer communication is instant messaging. With this application, any number of phones can take and send photos and short text messages to each other over the Internet or a local wireless network. If all participants have WiFi-capable phones and they use a free wireless LAN, you can use this application to share an unlimited number of photos and text messages with your friends at no cost Technically, this example shows how to build applications on top of the JSON...

Using a Phone as a Web Service

Accessing the phone's resources by way of the web is a 'bleeding-edge' approach that might be used as a springboard for many kinds of unprecedented applications. We have already seen some examples where a PyS60 program fetches some information from the web. Many more examples along these lines follow in Chapter 9. In this section, however, we consider the opposite case the phone could serve information to the web see Figure 8.7 . Figure 8.7 Phone providing a web service Figure 8.7 Phone...

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 appuifw.app.menu...

Example Roombatics

def bytecmd cmd, args args are bytes urn struct.pack B dB len args , cmd, args def intcmd cmd, args args are big endian ints return struct.pack gt B dh len args , cmd, args print OPENING BLUETOOTH SOCKET TO ROOTOOTH sock socket.socket socket.AF_BT, socket.SOCK_STREAM address, services socket.bt_discover roomba sock.makefile rw,0 print PUTTING ROOTOOTH INTO COMMAND MODE if roomba.read 6 r nOK r n raise Exception in failed print ASKING ROOTOOTH TO TALK TO ROOMBA if roomba.read 6 r nOK r n raise...

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 the...

Example Viewfinder

img.point 100, 100 , outline 255, 0, 0 , width 10 canvas.blit img appuifw.app.body canvas appuifw.Canvas appuifw.app.exit_key_handler quit camera.start_finder viewfinder lock e32.Ao_lock lock.wait The function camera. start_viewf inder takes a single parameter, a callback function that handles the incoming images. In this case, the job is handled by the function viewfinder. To convince you that the viewfinder images are just normal Image objects, we draw a small red dot on each image before...

Example Vocabulector 1

lst.append native idx appuifw.selection_list choices lst, search_field 1 if idx None foreign trans idx 1 fname PATH lst idx show fname, foreign lst.append foreign idx appuifw.selection_list choices lst, search_field 1 if idx None native trans idx 0 fname PATH native show fname, native def show fname, translation global photo, text, snd photo None photo graphics.Image.open fname .jpg except pass handle_redraw None try snd audio.Sound.open fname .wav snd.play except pass The functions show_native...

Example Vocabulector

import os, os.path, audio, appuifw, camera, key_codes, graphics PATH E Data Vocabulector global trans, dict_file if not os.path.exists PATH os.makedirs PATH dict_file file PATH trans.txt, rw trans line line.decode utf-8 native, foreign line.strip .split global text, photo, fname text photo None native appuifw.query uNative word , text if not native return foreign appuifw.query uForeign word , text if not foreign return fname PATH native trans.append native, foreign line s s native, foreign...

Interactive Graphics

Opengl Python

In Example 33, we learn how to move a single black point, leaving traces, on a white background someone might call this a pen , as shown in Figure 5.6. This example combines earlier lessons learnt, namely drawing graphics primitives and handling keyboard events. Figure 5.6 Moving dot with its trace Figure 5.6 Moving dot with its trace import appuifw, graphics, e32, key_codes BLACK 0, 0, 0 WHITE 255, 255, 255 key_down None clicked None global clicked, key_down if event type appuifw.EEventKey if...