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

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

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

If your mobile phone receives OSC data, allyou have to do is to use string handling (described in Chapter 4) todecode the OSC message and handle the OSC message contents further.To use OSC over TCP sockets for a mobile multi-user scenario, you couldreplace the code of function sending() in Example 123 with the codeof Example 124.11.7RoboticsWith a little creativity, a modern mobile phone can be used as a compactand capable robot brain. Besides having respectable computing power foran embedded device, the phone has the basic sensory functions built-in:ROBOTICS275the 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 variousplatforms for locomotion, which may be controlled, for instance, overBluetooth.Nowadays, using cheap off-the-shelf parts, one can start experimentingon robotics without any soldering.

This approach was taken by a course onArtificial Intelligence that was organized by the Department of ComputerScience at the University of Helsinki in 2007. In this course, a NokiaN80 mobile phone, which served as an eye for the robot, was mountedon a Roomba robotic vacuum cleaner – the resulting chimera is shownin Figure 11.12. Since one can control Roomba remotely by sendingcommands to it over a Bluetooth serial port, it is possible to build a fullyautonomous, visually guided robot based on these two widely availablecomponents.Figure 11.12 Nokia N80 mounted on a Roomba robotic vacuum cleanerStudents on the course were given a task to write a program that drivesthe robot through two gates, around a single pole and return through thegates back to the home base. To make the task easier for the students, thecontrol program for the robot ran on a PC, which got a constant stream ofphotos from a PyS60 script running on the N80.

Based on these visuals,the program was supposed to control the robot so that it stayed on track.276COMBINING ART AND ENGINEERINGIn further experiments, Roomba was controlled by the N80 and aPyS60 program in a totally autonomous manner. The phone controlledRoomba by Bluetooth using Roomba’s proprietary, binary protocol forcommunication. The PyS60 program was able to take full control ofthe robot, as the protocol includes commands for driving the robot andcollecting data from its sensors (see Examples 125 and 126).Example 125: Roombatics (1/2)import socket, time, structdef bytecmd(cmd,*args): # args are bytesurn struct.pack("B%dB" % len(args), cmd, *args)def intcmd(cmd,*args): # args are big endian intsreturn struct.pack(">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()sock.connect((address,1))roomba = sock.makefile("rw",0)print "PUTTING ROOTOOTH INTO COMMAND MODE"roomba.write("+++\r")time.sleep(0.1)if roomba.read(6) != "\r\nOK\r\n":raise Exception("+++ in failed")print "ASKING ROOTOOTH TO TALK TO ROOMBA"roomba.write("ATMD\r")time.sleep(0.1)if roomba.read(6) != "\r\nOK\r\n":raise Exception("ATMD failed")print "SETTING ROOMBA TO SAFE MODE"roomba.write(bytecmd(128))time.sleep(0.1)roomba.write(bytecmd(130))time.sleep(0.1)Example 126: Roombatics (2/2)print "START DRIVING 250mm/s WITH RADIUS 2000mm LEFT"roomba.write(intcmd(137,250,2000))time.sleep(0.1)print "GETTING SENSOR READING BYTES"roomba.write(bytecmd(142,0))time.sleep(0.1)sensor_str = roomba.read(26)sensor_bytes = ",".join(map(str,map(ord,sensor_str)))time.sleep(1) # keep driving for an extra secondSUMMARY277print "STOPPING – DRIVING WITH VELOCITY 0"roomba.write(intcmd(137,0,0))time.sleep(0.1)print "BACK TO ROOTOOTH COMMAND MODE"roomba.write("+++\r")time.sleep(0.1)if roomba.read(6) != "\r\nOK\r\n":raise Exception("+++ back failed")print "ROOTOOTH HANGUP"roomba.write("ATDH\r")time.sleep(0.1)roomba.close()print "THE END"Examples 125 and 126 include a simple PyS60 script that drivesRoomba forward, requests some sensor readings from it and stops.

Besidesshowing what the Roomba control code looks like in practice, they alsoillustrate how one can use a binary protocol to communicate with a Bluetooth device. This is done using the module struct, which convertsPython values to byte sequences according to the given format. You canfind more information about this module in the Python Library Reference.11.8 SummaryWe hope that by going through these diverse real-world examples that areinspired by artistic approaches, we have motivated you to enable, releaseand nurture your creativity, so you can rapidly create mobile applicationsbased on your own ideas and get ahead of most mobile users and evenmarket trends.You are experiencing technology needs today that will probably beexperienced by many other users in the coming years. You know andunderstand well your own needs, local habits and traditions and theyare close to the ‘real situation’.

This gives a big chance for you to comeup with innovative ideas and develop products that will be appealing toothers too. Put them out, share your innovations and see how happy youand other developers will be using your applications or developing themfurther.PyS60 is a toolkit at your hand that can help you succeed. Surpriseyourself and others with the applications you build.Appendix APlatform SecurityA.1 IntroductionThere are several releases of the S60 platform and they have someimportant differences.

The most important division in the S60 platform isthe division between S60 versions older than S60 3rd Edition (also knownas S60 3.0) and versions after S60 3rd Edition.Before S60 3rd Edition, a program written in native code was free toaccess any functionality available on the phone without asking confirmation from the user or being certified in any way. All programs wereconsidered fully trusted. Once a program was running, it had the opportunity to do anything it wanted, including make the phone inoperable, givethe user a large phone bill or spy on the user without their knowledge.In S60 3rd Edition, the situation has changed with the introduction ofa security framework known as Symbian OS Platform Security that limitswhat software running on the phone can do.Platform Security is a complex topic and we cannot hope to coverit fully in this appendix.

Instead, we will try to gather together in aunified form the parts that are most relevant to the Python for S60programmer, with emphasis on independent prototype developmentand experimentation. Readers interested in more details are recommended to consult the documentation on the Symbian Signed website,www.symbiansigned.com and the definitive guide on the topic, [Heath2006].The policies followed by device manufacturers and Symbian in matterssuch as types of developer certificates granted and the actual securitysettings on the devices can vary across manufacturers, countries anddevice variants. The information on security settings in this appendix wascorrect at the time of writing, but the policies and processes may change.From the viewpoint of the PyS60 programmer, the following limitationsimposed by Platform Security are the most relevant:•Accessing potentially sensitive features now requires capabilities.280PLATFORM SECURITY•Certain files and directories are now considered protected and can beaccessed only in a limited way.

This is known as data caging.•Installing new native applications to the device is only possiblethrough the operating system’s own software installer from a signedSIS file.A.2 CapabilitiesIn a device that uses Platform Security, a program must have permissionto access potentially sensitive features. In Platform Security jargon, thesepermissions are called capabilities. A program has to hold a certaincapability to access a certain set of sensitive features. Not all featuresrequire capabilities – there are many things you can do without holdingany capabilities at all. Almost all the examples in this book, except GSMlocationing, do not require special capabilities.There is a small, fixed set of capabilities and each capability grantsaccess to a specific set of functionality. The capabilities defined in S603rd Edition are listed in Table A.1.From the viewpoint of a PyS60 programmer, the capabilities can beroughly divided into three groups, based on the difficulty of accessingthem:•User-grantable capabilities are capabilities that the user who isinstalling a program can grant to the program at install time.

A programthat needs only user-grantable capabilities can be self-signed, meaning that it can be signed with a random untrusted key that anyone cangenerate.•Capabilities available with a free developer certificate (devcert) arecapabilities with which you can experiment on a single phone using adevcert available from the Symbian Signed service for free. However,packaging a program that needs these capabilities into a SIS file thatwould install to any phone can only be done through the SymbianSigned process.•Manufacturer-approved capabilities are highly sensitive capabilitiesthat can only be obtained from the device manufacturer, even if it’sjust for experimenting on your own phone. Getting these capabilitiesrequires you to justify why you need them, and to have an ACSPublisher ID from Verisign.The good news is that most of the things that you’ve learned to doin PyS60 so far need only user-grantable capabilities and none of themCAPABILITIES281Table A.1 Capability groupsCapabilityDescriptionReadUserDataRead access to user’s confidential data such as contactsand messagesWriteUserDataWrite access to user’s confidential data such as contactsand messagesUserEnvironmentAccess to confidential information about the user’senvironment by way of sensors such as microphone orcameraNetworkServicesAccess to communications that may cost money such astelephone calls or SMSLocalServicesAccess to local communications that don’t cost money touse, such as Bluetooth and infraredLocationLocation information, such as GPS coordinatesTrustedUiCreating trusted user interface componentsProtServRegistering server processes with a protected nameSwEventGenerating simulated key events and capturing key eventsfrom any applicationPowerMgmtKilling processes or turning off the deviceReadDeviceDataRead-only access to sensitive system settingsWriteDeviceDataWrite access to sensitive system settings such as systemtime, time zone and so onSurroundingsDDAccess to device drivers that provide information about thesurroundings of the phoneCommDDAccess to communication device drivers (for example,WLAN driver)MultimediaDDAccess to multimedia device driversNetworkControlRead or modify network protocol settingsDiskAdminLow-level disk administration functions such as formattingdrives or mounting and unmounting partitions(continued overleaf )282PLATFORM SECURITYTable A.1 (continued )CapabilityDescriptionAllFilesFull access to private directories; read-only access to \sysDRMAccess to unprotected forms of DRM-protected contentTCBWrite access to \sys and \resource directoriesTable A.2 Applications that need capabilities granted by a devcertDescriptionFunction or moduleRequired capabilitiesGlobal key capturekeycapture moduleSwEventReading the cell IDlocation.gsm location()ReadUserData,Location,ReadDeviceDataReading the GPSlocationposition moduleLocationSetting the systemtimee32.set home time()WriteDeviceDataneed manufacturer-approved capabilities.

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

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

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

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