Wiley.Mobile.Python.Rapid.prototyping.of.applications.on.the.mobile.platform.Dec.2007 (779889), страница 25
Текст из файла (страница 25)
The function is simple: ifa photo is loaded, it is shown on the canvas. If the variable text containsa string, it is drawn on the screen as well. The rest of the lines correspondto standard UI boilerplate code, which should be familiar to you fromprevious examples.6.6 SummaryIn this chapter, we have gone through many new concepts, including:•the directory hierarchy on the S60 platform•making directories•handling error conditions•reading and writing files•reading sounds, photos and videos•the dictionary object•handling Unicode conversions•using a local database•positioning techniques•using a timer object.By no means do you have to learn all these techniques at once. Feelfree to use this chapter as a reference and come back to it whenever youneed to apply these concepts in practice.
Many of these ideas, such asreading and writing files and handling error conditions, are not specificto PyS60 but they apply to the Python language in general. Thus, you willfind plenty of help on the web regarding these subjects.Even though these techniques might not feel as intriguing at first sightas graphics and sounds, they form the basic scaffolding for any nontrivial application. Luckily, as you might have noticed, PyS60 makes thisscaffolding extremely lightweight and transparent, so you can really focuson the things that are important to you.7Bluetooth and Telephone FunctionalityThe mobile phone is a strong candidate for becoming the interactiondevice that bridges the physical and virtual worlds. Standard networkingtechniques, such as TCP/IP, are great for heavy-duty communication overlong distances.
However, the last five meters between the phone and itsphysical surroundings are better handled with a lighter approach. In thisrange, Bluetooth is the dominant means of communication.Lots of interesting things happen within that five-meter radius. Youcan use Bluetooth for social interaction by connecting to other phonesand their users near to you. You can use it to interact with physicalobjects, such as public screens, GPS receivers, sensors, robotic vacuumcleaners and even shop windows. Naturally, Bluetooth also connects youto nearby PCs.In this chapter, we explore most of these scenarios.
We show how tosend photos to and chat with other phones in Section 7.3. Then we getyou started with phone-to-PC communication, which really becomes funonce you can also build applications on the PC side. For example, weshow how to control your Apple Mac with your phone using AppleScript.In Section 7.5, we connect to an external GPS receiver and later, inChapter 11, we connect to a sensor board. This might be of interest, forinstance, to projects dealing with art installations, sensor networks andphysical and wearable computing or smart fashion.At the end of this chapter, we take a quick look at the telephonefunctionality of PyS60.
Paradoxically, the modern mobile phone is adevice of so many capabilities, that only a brief section is dedicated toits original purpose. Finally, we introduce a small but useful module,sysinfo, that contains lots of interesting trivia about the status of yourphone.134BLUETOOTH AND TELEPHONE FUNCTIONALITY7.1 Bluetooth PairingSecurity concerns mean that it is a good habit to pair any two devicesbefore you connect them using Bluetooth.
Pairing need be done onlyonce for any two devices. The manual of your mobile phone containsinstructions on how to do this. Typically, you can initiate pairing on thephone side in the Bluetooth configuration dialog.The basic idea is that the phone shows a dialog asking you to typea passcode for the device – you can type any code you like.
The otherdevice should also show a dialog asking you to type the same passcodethere as well. If your phone asks you to ‘Authorize device to makeconnections automatically’, you should answer ‘yes’ unless you want toauthorize each connection individually, on a case by case basis.7.2 OBEX and RFCOMMThere are two main ways to communicate over Bluetooth with PyS60.OBject EXchange (OBEX) is suitable for transferring files, such as photosor sounds, over Bluetooth. Radio Frequency COMMunication (RFCOMM)is useful for sending and receiving streams of text and raw data, includingprotocols of your own.To send anything over Bluetooth, you have to know the recipient’s Bluetooth address, which is represented in a string, such as00:12:d2:41:35:e4.
You can find Bluetooth devices and their addresses with Bluetooth scanning. Typically, you have to worry about theraw addresses only if you want to connect to the same device againwithout scanning.The Bluetooth address identifies a device. A single device may provideseveral services. For example, your phone can simultaneously receivefiles and communicate with a headset and a wireless keyboard overBluetooth.
Each of the services operates on a different channel so they donot interfere with each other. If you want to send a file to another phone,first you have to find out its address and then the channel that is used bythe file transfer service.This might sound a bit complicated and, in the background, it is.However, PyS60 wraps this functionality behind two simple functions:socket.bt obex discover() performs service discovery for theOBEX protocol and socket.bt discover() performs service discovery for RFCOMM. Note that all Bluetooth-related functionality can befound in the socket module, which is described in detail in Chapter 8.Note that to use these examples, you have to switch on Bluetoothon your phone.
In many Nokia models, Bluetooth settings can be foundunder the Connectivity panel.OBEX AND RFCOMMFigure 7.1135Bluetooth discoveryExample 54 performs Bluetooth scanning and shows a dialog such asthe one in Figure 7.1, which lets the user choose a device to connectto.
Once the user has made a choice, the function returns the Bluetoothaddress of the chosen device. It also returns a dictionary that lists availableservices on the device and the channels that correspond to them.Example 54: OBEX discoveryimport socketaddress, services = socket.bt_obex_discover()print "Chosen device:", address, servicesThe output of the example is something like this:Chosen device: 00:12:d2:41:35:e4 {u"OBEX Object Push":9}In this case, the target device, whose address is contained in the stringaddress, has only one OBEX service available, "OBEX Object Push"on channel 9. This service is used to transfer files between devices. Ifno services were available on the target device, the function would haveraised an exception. The service names are standardized, so if you areinterested in only the "OBEX Object Push" service, you can requestthat particular key from the services dictionary.If you know the recipient’s Bluetooth address beforehand, you can findout the services provided by it without showing the dialog of Figure 7.1.The discover functions accept an address string as an optional parameter:136BLUETOOTH AND TELEPHONE FUNCTIONALITYMY_PC = "00:12:d2:41:35:e4"address, services = socket.bt_obex_discover(MY_PC)We can discover available RFCOMM services in a similar manner.
We just use the function socket.bt discover() instead ofbt obex discover(), as in Example 55.Example 55: RFCOMM discoveryimport socketaddress, services = socket.bt_discover()print "Chosen device:", address, servicesAgain, if the chosen device does not provide any RFCOMM services,the function raises an exception.7.3 Phone-to-Phone CommunicationNow that we have seen how to find a target for Bluetooth communication,we can start to do something useful. This section requires that you invite afriend with a Bluetooth-capable phone to hack with you.
Bluetooth reallyenables social interaction.7.3.1 Using OBEXWe build an application that lets you take photos and share themwith people around you. Example 56 is a combination of the cameraapplication of Example 35 and the OBEX discovery Example 54. The onlyBluetoothFigure 7.2Bluetooth from phone to phonePHONE-TO-PHONE COMMUNICATION137new feature, sending a photo to a chosen recipient, can be performedwith a single function, socket.bt obex send file().Example 56: Send photos to another phone using Bluetoothimport camera, e32, socket, appuifwPHOTO = u"e:\\Images\\bt_photo_send.jpg"def send_photo():try:address, services = socket.bt_obex_discover()except:appuifw.note(u"OBEX Push not available", "error")returnif u'OBEX Object Push' in services:channel = services[u'OBEX Object Push']socket.bt_obex_send_file(address, channel, PHOTO)appuifw.note(u"photo sent", "info")else:appuifw.note(u"OBEX Push not available", "error")def take_photo():photo = camera.take_photo()canvas.blit(photo, scale = 1)photo.save(PHOTO)def quit():app_lock.signal()canvas = appuifw.Canvas()appuifw.app.body = canvasappuifw.app.exit_key_handler = quitappuifw.app.title = u"BT photo send"appuifw.app.menu = [(u"Take photo", take_photo),\(u"Send photo", send_photo)]app_lock = e32.Ao_lock()app_lock.wait()The application consists of two functions: take photo() and sendphoto().