Главная » Просмотр файлов » 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), страница 47

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

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

If the program must react to externalevents, typically by way of callbacks, we say that the program isevent-driven. Examples include the game of Hangman in Section 4.5that reacts to incoming SMS messages and the Instant Messenger inSection 8.6.2 that reacts to network events.•Game: here, the crucial feature is an event loop that keeps theprogram active even without any external events.

This pattern wasthoroughly described in Section 5.5 and first exemplified by thedrawing application in Example 33.•Client–server: many examples in Chapters 7 and 8 are based oncommunication between a client and a server. The idea is that twoindependent programs communicate and thus affect each other’s state.SUMMARY241The Bluetooth client in Example 59 and the server in Example 60 areillustrative of this pattern.•Concurrent: in many real-world settings, a program must performmany things at the same time. The use of callback functions relies onthe fact that some mechanism is listening to events in the background,although your program may simultaneously be busy doing somethingelse.

Thus, many examples we have seen actually work concurrentlybehind the scenes.In this book, we have deliberately avoided touching this issuetoo much, since it is notoriously difficult to program well-behavedconcurrent programs. Fortunately, PyS60 often provides a way toavoid using threads and other concurrent programming techniques,such as active objects, used by Symbian OS, explicitly. However, inSection 8.6 we presented a message handler (Example 83) that showsa clean pattern of concurrency using threads.Once you start building more complex applications of your own,seeing and using these patterns might prove useful.

Before coding a singleline of code, you can decide which of these patterns your applicationcode should follow – often the choice is really evident. After this, youcan browse through the examples that use that particular pattern. In thebest case, you might be able to use one of the examples as a skeleton foryour application and get past the ‘empty editor’ syndrome.10.5 SummaryPython is a great language in which to write elegant and clean code.Writing clean code is the best way to avoid bugs in the first place andit gives you a feeling that you know what happens in your program atall times. Consequently finding any bugs is easier and fixes are simpler.Naturally the sense for elegant code is something that needs lots ofhands-on practice and failures, to develop.If you feel adventurous, you could take a look at the Python source codeand find out how API calls are implemented.

This is not as intimidatingas it may first sound, since the code is typically understandable and, evenif you do not understand it fully, it can point you in the right direction.Luckily PyS60 is open source so this is a real option!There are often many different ways to accomplish one goal in programming.

To get to your goal, you have to make a great number of smalldecisions. Often, alternatives are technically similar and the difference ismostly a matter of aesthetics. However, style does matter in programming.It makes sense to keep some rules of thumb in mind that may help youwrite better code.242EFFECTIVE PYTHON FOR S60It may be enlightening and entertaining to read the following shortarticles:•‘Zen of Python’ at www.python.org/dev/peps/pep-0020•‘Python Style Guide’ at www.python.org/dev/peps/pep-0008These articles give deeper insights into issues of coding style in Python.Besides those articles, which discuss the Python language in general, wewould like to present some thoughts that seem to be especially appropriatefor PyS60:•Make sure you understand itDon’t write or use code which you do not fully understand.

Debuggingalien code is no fun. By keeping this principle in mind, you willbecome a master of PyS60 in no time.•Don’t copy and paste codeRelated to the previous advice, you should understand every line ofcode in your program. If you type in each line manually, you forceyourself to think what you type.•Be prepared for the real worldMany bugs are caused by unexpected input values from the outsideworld. Try to keep the diversity of possible contexts in mind whendesigning your code.

This is particularly important with mobile code,which is often used in many different environments. However, do notaim at universal solutions since they rarely exist. Also, remember tovalidate data before you use it and handle exceptions properly.•Make it modularComplex programs can be kept simple if they are modularized properly. Separate your code logic into small functions and divide yourcode into modules.•Keep it simpleUse as few lines of code as possible, no fewer, no more.

In Python,terseness is a virtue but not at the price of understandability.•See patterns in your code and in that written by othersFollow patterns that you have seen to work in practice. This way youcan avoid debugging the same problems every time. Note, however,that patterns are just conceptual tools. Do not try to force your programto follow a pattern, if it doesn’t feel natural.

Also, do not use patternsas an excuse to copy and paste code.SUMMARY•243Be pragmaticAs we said in Chapter 1, PyS60 is all about having your head inthe clouds, your hands in mud and your feet on the ground. Thatis, come up with, implement and test working prototypes in rapidcycles. Only dinosaurs spend years thinking about grandiose softwarearchitectures – other reptiles have already evolved past that stage.11Combining Art and EngineeringThis chapter brings together many of the concepts and techniques shownin the previous chapters.

We provide a series of real-world applicationexamples that combine art and engineering. They are all built anddeployed using PyS60. Most of them have their origins in the fieldof digital art and are implemented by following the rapid prototypingapproach with PyS60.We hope to illustrate here that by having an application idea or aconcept at the core of your actions, you can turn it into a fully workingapplication by adopting and combining many of the previously introducedcode examples. The applications we explain span from participatoryand collaborative games to mobile multi-user applications controllinglarge displays, from interacting with a robot to physical computing usingsensor boards and applications for controlling remote sound applications.Finally we show how you might turn your phone into a tool for creatingmobile art.Again we want to repeat here our message to all you creative andinnovative people out there: use your talent, skills, ideas and energy toinspire the world! May this chapter and the entire book help you to do so!11.1 MobiLeninThe MobiLenin system allows a group of people to interact simultaneouslywith a multi-track music video shown on a large public display usingtheir personal mobile phones, effectively empowering the group withthe joint authorship of the video.

The system was implemented with aclient–server architecture that includes server-driven, real-time controlof the client UI written in PyS60 to guarantee ease of use. A lotterymechanism was built in as an incentive for interaction.246COMBINING ART AND ENGINEERINGThe MobiLenin system was a research project of one of the authors andhis motivation as a music and new media artist and engineer was to createan interactive technology system that gives the audience the possibilityof engaging in a new way in his live show – simply by interacting withthe music and video on a large screen.

The idea is to enhance people’sconcert experience by allowing them to interact with the artist in thevirtual domain on the display.11.1.1 System ArchitectureThe MobiLenin system comprises four components:•a PyS60 client application running on a mobile phone•an application running on a PC connected to the Internet•an external server•a large public display showing the music video.There are several reasons why personal mobile phones are suitableuser devices for this purpose. First, they are ubiquitous, as practicallyeveryone has one.

Second, they allow anonymous, wireless and mobileparticipation in a joint social and public group interaction. Third, themobile phone provides a reliable return channel for delivering confidential user-specific information back to the user, such as a winning lotterycoupon.The PC application is implemented in Macromedia Director to countvotes, operate the lottery mechanism, initiate the delivery of winningnotifications and control the QuickTime player with its multi-track videoas well as handling all the graphic elements on the public display and thesound.

An external server component consisting of simple PHP scripts isplaced on the Internet to act as a mediator between the public mobile datanetwork and the PC running the main application. The communicationbetween the two is done by HTTP. The external component also hoststhe pictures for the lottery coupons to be fetched by the mobile devicesupon initiation by the main application.The large public display serves as the main interface for the user’sinteraction. Besides showing the music video, it indicates the start andend of a voting interval and the voting results and notifies the audienceof somebody winning the lottery.Figure 11.1 shows the state diagram of the system. When the voting interval starts, it is indicated in the client by an S60 popup note(Figure 11.2 (a)) and shown on the public display (‘Vote now!’).

Theserver opens the voting menu in each client, so that a vote is cast byselecting one of the given menu choices (Figure 11.2 (b)). If a vote is cast,MOBILENINServerClient(Mobile Phone)StartVote on!noteVote now!Menu opensSelect choice25 sec.Vote endsCounting votes247Public DisplayVideo:Track 1 onTrack 2 offTrack 3 offTrack 4 offTrack 5 offTrack 6 off6 sec.Winning!noteCouponpicture opensFigure 11.1Show ResultsSwitch Videotrack25 sec.State diagram of the MobiLenin systemit is acknowledged by the client (Figure 11.2 (c)) and sent to the server.

Ifthe user wins in the lottery, a winning coupon is pushed to the client bythe server and presented to the user (Figure 11.2 (d)).After a 25-second voting interval is over, ‘Counting votes!’ is shown onthe public display. The server counts the votes and, after six seconds, theresult of the vote is displayed on the large display in form of six graphicbars, one for each voting option. The length of each bar corresponds tothe proportion of votes each option received (Figure 11.3.).

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

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

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

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