Главная » Просмотр файлов » Wiley.Mobile.Python.Rapid.prototyping.of.applications.on.the.mobile.platform.Dec.2007

Wiley.Mobile.Python.Rapid.prototyping.of.applications.on.the.mobile.platform.Dec.2007 (779889), страница 26

Файл №779889 Wiley.Mobile.Python.Rapid.prototyping.of.applications.on.the.mobile.platform.Dec.2007 (Symbian Books) 26 страницаWiley.Mobile.Python.Rapid.prototyping.of.applications.on.the.mobile.platform.Dec.2007 (779889) страница 262018-01-10СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

Текст из файла (страница 26)

The application structure should be familiar to you from theprevious examples. Note that the viewfinder is not included in thisexample because of space constraints. You can easily add it by yourself,for instance based on Example 36.To send the photo, we find the target device with socket.bt obexdiscover(). If the target supports the OBEX Object Push protocol,we find the channel that corresponds to it from the services dictionary.Once we know the recipient’s address and the channel, we can send thephoto to the recipient with socket.bt obex send file().When the connection is established, the target device may showa popup asking ‘Receive message via Bluetooth from. .

.’ – you shouldanswer ‘yes’. Since we use the standard OBEX Object Push service,138BLUETOOTH AND TELEPHONE FUNCTIONALITYwhich is supported natively by the phone’s operating system, the recipientdoes not need any special application to receive the photos. Photosappear in the recipient’s standard inbox, in the same way as SMS or MMSmessages.7.3.2Using RFCOMMExample 56 relied on a standard OBEX service to transfer files from phoneto phone, which is easy, but somewhat restricted.

For instance, all datamust be sent from a file and received into a file. It is also a connectionlessprotocol, which means that you cannot know whether the other side isstill within your reach.In contrast, RFCOMM opens a pipe between two devices, which canbe used to send and receive any strings in your program – including files.In this respect, it is similar to a TCP/IP connection, so reading Chapter 8should deepen your understanding of RFCOMM.In this section, we create a simple chat application that lets you sendshort messages back and forth between two phones. Naturally, bothphones need to be running the chat application.

One phone must act asa server and the other as a client that initiates the connection.After the client has established a connection to the server, the phonesmay start sending messages to each other in turn. Synchronous communication such as this is easier to handle than asynchronous communication,where the parties may send messages whenever they want.

In Chapter 8,we show how to handle asynchronous communications as well.The application is divided into two parts. You should combine the partsinto one file to form the full application. Example 57 contains functionsfor both client and server. The chat server() function waits for anincoming connection and chat client() establishes a connection tothe chat server.Example 57: Bluetooth chat (1/2)import socket, appuifwdef chat_server():server = socket.socket(socket.AF_BT, socket.SOCK_STREAM)channel = socket.bt_rfcomm_get_available_server_channel(server)server.bind(("", channel))server.listen(1)socket.bt_advertise_service(u"btchat", server, True, socket.RFCOMM)socket.set_security(server, socket.AUTH | socket.AUTHOR)print "Waiting for clients..."conn, client_addr = server.accept()print "Client connected!"talk(conn, None)def chat_client():conn = socket.socket(socket.AF_BT, socket.SOCK_STREAM)PHONE-TO-PHONE COMMUNICATION139address, services = socket.bt_discover()if 'btchat' in services:channel = services[u'btchat']conn.connect((address, channel))print "Connected to server!"talk(None, conn)else:appuifw.note(u"Target is not running a btchat server", "error")The function chat server() may look a bit convoluted, but actuallyit just performs some housekeeping to prepare the system for clientsto arrive.

In other words, to be able to accept incoming Bluetoothconnections, the server side must call the following functions:1. socket() creates a new endpoint, or socket, for communication.2. bt rfcomm get available server channel() allocates anew channel for this service.3. bind() binds the channel to the socket.4. listen() informs the operating system that we are willing to acceptincoming connections.5.

bt advertise service() makes our service, btchat, discoverable.6. set security() sets the security settings for this service.7. accept() waits until a client establishes a connection with us.Life is much easier for the clients, who only have to perform thefollowing three steps in the function chat client():1. socket() creates the endpoint for communication.2. bt discover() discovers the service of the other phone. Theserver must be started before the client, otherwise the client cannotfind it.3.

connect() connects to the chosen server using the channel that isreserved for our btchat service.Do not worry if the meaning of some of these steps is still unclear toyou – the socket module is described more thoroughly in Chapter 8.After these functions have been executed, chat server() on onephone and chat client() on the other, a new RFCOMM connectionhas been established between the phones. Both the functions end with acall to the talk function that orchestrates the actual chatting. Dependingon whether talk is called from the server or the client side, the new140BLUETOOTH AND TELEPHONE FUNCTIONALITYconnection is passed to it either as a connection to the server or to theclient.Example 58: Bluetooth chat (2/2)def receive_msg(fd):print "Waiting for message.."reply = fd.readline()print "Received: " + replyappuifw.note(unicode(reply), "info")def send_msg(fd):msg = appuifw.query(u"Send a message:", "text")print "Sending: " + msgprint >> fd, msgdef talk(client, server):try:if server:fd = server.makefile("rw", 0)receive_msg(fd)if client:fd = client.makefile("rw", 0)while True:send_msg(fd)receive_msg(fd)except:appuifw.note(u"Connection lost", "info")if client:client.close()if server:server.close()print "Bye!"index = appuifw.popup_menu([u"New server", u"Connect to server"],u"BTChat mode")if index != None:if index:chat_client()else:chat_server()When the talk() function is called from the chat client()function, it gets a connection (socket object) to the server.

In this case,the function starts waiting for the first message from the server side. Onthe server side, a dialog is shown which asks the user to type in the firstmessage for the client.The functions receive msg() and send msg() are used to receiveand send messages. To use these functions, we convert the socket to ahandy file-like object using makefile("rw", 0). After this, we canread and write to the socket as if it was a normal file, in a similar way towhat we did in Chapter 6. The second parameter, 0, tells that we do notneed any buffering for communication.PHONE-TO-PC COMMUNICATION141This is the key to using RFCOMM: we can treat the Bluetooth connection as a file.

However, care must be taken that we do not attempt to readfrom the connection-file if there is nothing to read, that is, the sender hasnot sent anything, and that we do not write too much to the connectionuntil the reader has read at least some of it. In either case, the read orwrite function blocks and waits for the other side to act. If the other sidedoes not act for some reason, the function waits forever and the programgets stuck.Here we read and write only one line, or message, at a time. Sendingis easy: it uses the normal print command, directed to the connectionfd. Reading is performed with the file object’s readline() function.Chapter 8 introduces other ways to transfer data over connections suchas this.The actual chatting takes place in an infinite while loop in the functiontalk().

We alternate between receiving a message and sending one.Since the server-side is the first one to enter the loop, it may also sendthe first message which lets the client into the loop as well. This alternatecommunication continues until some exception occurs in the loop.There are many ways to close the connection either deliberatelyor accidentally – both of these cases are handled by the try–exceptblock that encloses the chatting functions. If one side cancels the messagedialog, the next print statement raises an exception that is caught bythe except clause and the connection is terminated. If the connectionbreaks for any other reason, sending and receiving fails and both phonesexit from the chatting loop.The last lines in Example 58 are executed when the example starts.Here a dialog is shown which lets you choose whether you want to be theserver or the client.

Depending on the choice, either chat client()or chat server() is executed and the chatting may begin.7.4 Phone-to-PC CommunicationIn this section, we describe how to connect your phone to your PC usingBluetooth RFCOMM (Figure 7.3). On the PC side, you can either use aPython script to communicate with the phone or any other applicationor programming language that can access the serial port. In Example 59,however, we rely on standard terminal emulator software, as describedin Appendix B, which provides a convenient way to test the connection.With the PC as a gateway or middleman, it is possible to control awide range of applications and devices using a mobile phone, althoughthe applications and devices do not have any native support for Bluetoothor mobile phones.

Basically anything that can be controlled by a customprogram on a PC, can be controlled by the mobile phone using the142BLUETOOTH AND TELEPHONE FUNCTIONALITYBluetoothFigure 7.3 Bluetooth from phone to PCBluetooth link. This way, it is possible to build a PC-based personal videorecorder, PowerPoint presentation or printer, which can be operated bya mobile phone interface.Naturally, this requires that your PC supports Bluetooth communication, either internally or with a USB Bluetooth dongle. We also expectyou to have installed Bluetooth drivers correctly; that is, Bluetooth mustbe fully working on the PC side.To use Bluetooth for RFCOMM communication, some configurationis needed on the PC side.

The process of setting up the RFCOMM serialport on Windows, Mac OS X, or Linux, is described in Appendix B. Onceyou can see the serial port service on your phone, you may proceed tothe next section.7.4.1 Communicating with the PCThe principles of RFCOMM communication with the PC are no differentfrom the chat example, in which two phones were talking to each other.On the phone end, the code could look pretty much the same. However,here we consider only the option where the PC acts as the server and thephone connects to it. Technically, it is possible to use the phone as theserver, but the Bluetooth configuration described in Appendix B holdsonly for the former case.First, we make a small test client (Example 59) for the phone whichcan send and receive individual lines of text.

Характеристики

Тип файла
PDF-файл
Размер
3,61 Mb
Материал
Тип материала
Высшее учебное заведение

Список файлов книги

Свежие статьи
Популярно сейчас
Зачем заказывать выполнение своего задания, если оно уже было выполнено много много раз? Его можно просто купить или даже скачать бесплатно на СтудИзбе. Найдите нужный учебный материал у нас!
Ответы на популярные вопросы
Да! Наши авторы собирают и выкладывают те работы, которые сдаются в Вашем учебном заведении ежегодно и уже проверены преподавателями.
Да! У нас любой человек может выложить любую учебную работу и зарабатывать на её продажах! Но каждый учебный материал публикуется только после тщательной проверки администрацией.
Вернём деньги! А если быть более точными, то автору даётся немного времени на исправление, а если не исправит или выйдет время, то вернём деньги в полном объёме!
Да! На равне с готовыми студенческими работами у нас продаются услуги. Цены на услуги видны сразу, то есть Вам нужно только указать параметры и сразу можно оплачивать.
Отзывы студентов
Ставлю 10/10
Все нравится, очень удобный сайт, помогает в учебе. Кроме этого, можно заработать самому, выставляя готовые учебные материалы на продажу здесь. Рейтинги и отзывы на преподавателей очень помогают сориентироваться в начале нового семестра. Спасибо за такую функцию. Ставлю максимальную оценку.
Лучшая платформа для успешной сдачи сессии
Познакомился со СтудИзбой благодаря своему другу, очень нравится интерфейс, количество доступных файлов, цена, в общем, все прекрасно. Даже сам продаю какие-то свои работы.
Студизба ван лав ❤
Очень офигенный сайт для студентов. Много полезных учебных материалов. Пользуюсь студизбой с октября 2021 года. Серьёзных нареканий нет. Хотелось бы, что бы ввели подписочную модель и сделали материалы дешевле 300 рублей в рамках подписки бесплатными.
Отличный сайт
Лично меня всё устраивает - и покупка, и продажа; и цены, и возможность предпросмотра куска файла, и обилие бесплатных файлов (в подборках по авторам, читай, ВУЗам и факультетам). Есть определённые баги, но всё решаемо, да и администраторы реагируют в течение суток.
Маленький отзыв о большом помощнике!
Студизба спасает в те моменты, когда сроки горят, а работ накопилось достаточно. Довольно удобный сайт с простой навигацией и огромным количеством материалов.
Студ. Изба как крупнейший сборник работ для студентов
Тут дофига бывает всего полезного. Печально, что бывают предметы по которым даже одного бесплатного решения нет, но это скорее вопрос к студентам. В остальном всё здорово.
Спасательный островок
Если уже не успеваешь разобраться или застрял на каком-то задание поможет тебе быстро и недорого решить твою проблему.
Всё и так отлично
Всё очень удобно. Особенно круто, что есть система бонусов и можно выводить остатки денег. Очень много качественных бесплатных файлов.
Отзыв о системе "Студизба"
Отличная платформа для распространения работ, востребованных студентами. Хорошо налаженная и качественная работа сайта, огромная база заданий и аудитория.
Отличный помощник
Отличный сайт с кучей полезных файлов, позволяющий найти много методичек / учебников / отзывов о вузах и преподователях.
Отлично помогает студентам в любой момент для решения трудных и незамедлительных задач
Хотелось бы больше конкретной информации о преподавателях. А так в принципе хороший сайт, всегда им пользуюсь и ни разу не было желания прекратить. Хороший сайт для помощи студентам, удобный и приятный интерфейс. Из недостатков можно выделить только отсутствия небольшого количества файлов.
Спасибо за шикарный сайт
Великолепный сайт на котором студент за не большие деньги может найти помощь с дз, проектами курсовыми, лабораторными, а также узнать отзывы на преподавателей и бесплатно скачать пособия.
Популярные преподаватели
Добавляйте материалы
и зарабатывайте!
Продажи идут автоматически
6451
Авторов
на СтудИзбе
305
Средний доход
с одного платного файла
Обучение Подробнее