Главная » Просмотр файлов » Symbian OS Communications

Symbian OS Communications (779884), страница 55

Файл №779884 Symbian OS Communications (Symbian Books) 55 страницаSymbian OS Communications (779884) страница 552018-01-10СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

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

Operations should be kept short and asynchronousin order for other messaging requests to be serviced in good time.CFlickrRestAPI::IssueImagePostL() is an asynchronous callwhich makes a callback to FlickrRestOperationComplete() whencomplete.The instance variable iReportStatus keeps track of the client-siderequest status passed in from the client MTM and is completed oncompletion of the image upload.THE FLICKR SERVER MTM267voidCFlickrServerMtm::FlickrRestOperationComplete(MFlickrRestAPIObserver::TOperationType aOpType, TInt aError){User::RequestComplete(iReportStatus,aError);TMsvId id = iServerEntry->Entry().Id();iServerEntry->SetEntry(iServerEntry->Entry().Parent());iServerEntry->DeleteEntry(id);}On completion of the upload operation, the message is deleted fromthe store. The Flickr MTM has no notion of retry and so the message mustbe deleted – the user must try to send the image again.An entry can only be deleted from its parent, so iServerEntry is setto the parent and the message deleted.Reporting progressThe messaging architecture provides for polling of progress on an asynchronous object and final status of an operation.Most messaging operations are asynchronous and, following standardpractice, the value in the TRequestStatus on completion indicatessuccess or failure.A single integer is rarely enough to describe the full context of theerror and so the messaging APIs provide a way of passing intermediateprogress for an operation.

All client-side messaging operations derive fromCMsvOperation, which encapsulates support for reporting progress.When a client requests progress on a pending CMsvOperation, an8-bit package buffer is copied from the server side MTM to the client.This package contains progress information in a format understood byboth the server and client MTMs, but opaque to the message server.The client callsvirtual const TDesC8& CMsvOperation::ProgressL()=0;And the server MTM suppliesvirtual const TDesC8 &Progress()=0;The common format between client and server MTMs is usuallyachieved by defining the progress data structures in a shared header file.A type-safe package buffer is defined to pack and unpack the progressstructure as an 8-bit descriptor.

The package buffer has a maximum sizelimit of 255 bytes – larger progress buffers will cause an ‘MSGS Client11 panic.268SENDING MESSAGESHere is the progress structure used for the Flickr MTM:class TImageUploadProgress{public:TInt iErrorCode;TBuf8<150>iErrorMessage;};typedef TPckgBuf<TImageUploadProgress> TImageUploadProgressBuf;The client polls for progress periodically and so the server operationshould keep the progress structure valid and up to date, in the knowledgethat the message server may copy the structure to the client at any time.The progress structure should contain any information that chartsprogress and could be useful for the UI to display; it should also containcontext about any error conditions encountered during the operation.Any buffer used by the client for receiving progress needs to remainin scope for the duration of the asynchronous operation – you shouldtherefore store progress structures as a member of the CActive -derivedclass making the request rather than using a local variable, as the localvariable will be out of scope before the asynchronous operation completes.

Getting this wrong is a common source of hard-to-diagnose bugs inasynchronous programming, as the point at which the memory formerlyused by any stack-based buffer is overwritten, is timing dependent.9.12MTM DLLs and PlatsecThe required platsec capabilities differ between UI platforms. In generalthe DLLs containing the client, UI and UI Data MTMs may be loadedinto any application using messaging services and so are similar to anyDLL providing a platform-wide service. In the case where the MTMs areonly designed to implement a new SendAs message type, they can havea more restricted set of capabilities in UI platforms that implement thearchitecture shown in Figure 9.4.

Today this includes UIQ but not S60.However, expecting DLLs to be signed with All-TCB is unreasonable,so instead our recommendation is to test with a variety of applications ona device to discover a reasonable capability set for the client-side MTMs.The ‘private’ MTM component, that is the server MTM, requires capabilities equal to the loading process – the messaging server process. Yourserver-side MTM component should be given the following capabilities:NetworkServices, LocalServices, ReadUserData, ReadDeviceData,WriteDeviceData, ProtServ, NetworkControlINSTALLATION OF AN MTM269Of these, ReadDeviceData, WriteDeviceData, ProtServ andNetworkControl are all from the extended capability set – thereforeit is likely that additional information will need to be provided whensubmitting the MTM suite to any signing process stating the reasons forrequiring these capabilities – namely that you are providing messagingserver plugins.An MTM going through the signing process will need all UID3sfor EXEs and DLLs to be assigned from the protected UID range (0 ×20000000–0 × 2FFFFFFF) – UIDs from this range can be obtained viathe Symbian Signed website (www.symbiansigned.com).9.13 FlickrMTM Shared SettingsAs discussed in the section ‘Reporting progress’, some data structuresneed to be shared between the four MTM layers.Usually a utility DLL is created in order to store any shared constants,data structures and common utility functions.The Flickr MTM uses FlickMtmsettings.dll to store message type UIDs,constants, operation IDs and progress structures.

The DLL contains functions to set and retrieve the default service. In a more complex MTM, theshared DLL may serve to share code between the client and server forsaving and retrieving messages from the store.9.14 Installation of an MTMWriters of MTMs need to inform the message server of the properties ofthe MTM by supplying a registration file. This is a compiled resource fileplaced in the \resource\messaging\mtm\ folder.In versions of Symbian OS before v9, the resource file is placed in\system\mtm\.The resource file should define the MTM’s properties using theresource structures MTM_INFO_FILE, MTM_CAPABILITIES, and fromv9.0, MTM_SECURITY_CAPABILITY_SET.When installing a new set of MTMs on a phone, you must take theadditional step of calling CMsvSession::InstallMtmGroup() tonotify the message server that a new MTM is available.

When this isdone, all running message server client processes are also notified thata new MTM is available. Typically you would do this by running anadditional program at the end of the installation process.270SENDING MESSAGESUninstallation also requires running a simple exe to unregister theMTM by making a call to CMsv Session::De Install Mtm Group.Running clients are then dynamically notified that the MTM is no longeravailable.RESOURCE MTM_INFO_FILE{mtm_type_uid = 0x20009972; // Specifically allocated for the Flickr MTMtechnology_type_uid = 0x20009972;components ={MTM_COMPONENT_V2{human_readable_name = "Flickr";component_uid = KUidMtmServerComponentVal;entry_point = 1;version = VERSION_V2 {};filename = "FlickrMtmServer.dll";},MTM_COMPONENT_V2{human_readable_name = "Flickr";component_uid = KUidMtmClientComponentVal;entry_point = 1;version = VERSION_V2 {};filename = "FlickrMtmClient.dll";},MTM_COMPONENT_V2{human_readable_name = "Flickr";component_uid = KUidMtmUiComponentVal;entry_point = 1;version = VERSION_V2 {};filename = "FlickrMtmUi.dll";},MTM_COMPONENT_V2{human_readable_name = "Flickr";component_uid = KUidMtmUiDataComponentVal;entry_point = 1;version = VERSION_V2 {};filename = "FlickrMtmUiData.dll";}};}// flags to indicate that can send messages, and handle body textRESOURCE MTM_CAPABILITIES{send_capability = 1;body_capability = 0;}////////Additional capabilities required by clients of theflickr MTM.Since we are sending data over an IP network, werequire the client to have the same capabilities asSUMMARY271// if they were going to do it themselvesRESOURCE MTM_SECURITY_CAPABILITY_SET{capabilities = {ECapabilityNetworkServices};}9.15 SummaryIn this chapter we have learnt how to:• use the SendAs API to send messages in a bearer-independent wayfrom our application• use the send dialogs provided by the UI platforms in the case wherewe want to offer the user a choice of bearer over which to send themessage• extend the SendAs functionality by implementing a new set of MTMs,in this case to allow the upload of photos to Flickr.10OBEXThis chapter starts with an introduction to the OBEX protocol – not beinga mainstream protocol, we go into a fair amount of depth to give you afeel for the feature set of OBEX.

After this, we explore the APIs offeredby the Symbian OS OBEX implementation. We also illustrate the use ofthese APIs using examples drawn from an example implementation of aBluetooth FTP server.1The chapter also shows how the OBEX API has developed from itsorigins in ER5 to the current implementation in Symbian OS v9.1, andhighlights the most recent changes for Symbian OS v9.2.10.1 OBEX OverviewThe OBEX (or OBject EXchange) protocol was originally developed aspart of the Infrared Data Association’s infrared protocol suite. It has sincebeen adopted by the Bluetooth Special Interest Group as the basis ofthe Generic Object Exchange Profile (GOEP) family of Bluetooth profiles,and by the USB Implementers’ Forum as part of the Wireless MobileCommunications Device Class (WMCDC) specification. It is intended toprovide an easy to use, lightweight and flexible means of transferring‘objects’ from device to device, where an object can be almost anyconceivable data entity from a vCard to a multi-megabyte media file.OBEX performs a very similar function to HTTP, and both have verysimilar features at a high level.

However, OBEX is targeted at deviceswith limited resources, so it omits some of HTTP’s functionality in order1Two things are worth noting here – firstly, whilst this example application is a gooddemonstration of what you can do with OBEX, Bluetooth FTP servers are already implemented in shipping devices.Secondly, the implementation has not qualified by the Bluetooth SIG, but has beentested using a Windows-based Bluetooth FTP client, running USB TDK Bluetooth adapterand Ezurio Bluetooth Software 1.4.2 Build 18.274OBEXto focus on providing a service that can be implemented relativelyeasily on resource-constrained devices.

Concentrating on similarities fora moment – both protocols transfer arbitrary data in a request–responsefashion, both use the concept of ‘headers’ to describe that content and‘body’ to contain the content itself. Both have the concept of PUTing andGETting objects.However, OBEX differs in some key areas – it is a binary-based protocolrather than a text-based protocol like HTTP. Unlike HTTP, which usescookies to maintain session state (as the protocol is inherently stateless),OBEX handles state at the protocol level. And finally, whilst HTTP is mostoften run over TCP (although other bindings do exist), the most popularbindings for OBEX are Bluetooth RFCOMM, IrDA TinyTP and USB.The following sections give a brief overview of OBEX itself, beforegoing into the specifics of the Symbian implementation.

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

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

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

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