Главная » Просмотр файлов » Issott_Common Design Patterns for Symbian OS-The Foundations of Smartphone Software_0470516356

Issott_Common Design Patterns for Symbian OS-The Foundations of Smartphone Software_0470516356 (779879), страница 59

Файл №779879 Issott_Common Design Patterns for Symbian OS-The Foundations of Smartphone Software_0470516356 (Symbian Books) 59 страницаIssott_Common Design Patterns for Symbian OS-The Foundations of Smartphone Software_0470516356 (779879) страница 592018-01-10СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

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

As with any software on amobile device, conserving battery power is an important considerationespecially if you will be processing large volumes of data packets.Reducing the number of CPU cycles needed to parse each packet notonly reduces the latency of your middleware component but also extendsbattery life. RAM efficiency can also help to conserve battery life byallowing RAM chips to be powered down or by indirectly reducing theCPU cycles used. Note that since your component will probably handlelarge volumes of data there is the potential for a mistake here to have alarge impact on RAM usage.In your packet-processing scenario, you’ll find that there are a numberof common factors that you can take advantage of to model the data andyour functionality in an organized way to make your code manageableand maintainable. Normally each packet has a well-known structure,perhaps specified in an industry standard, and your middleware component will need to perform one of a standard set of operations on it.

Theseoperations are normally very similar each time a new packet of data isDATA PRESS311processed. However, you need to design in the expectation that the rulesand standards governing the behavior of your middleware componentcould be changed or extended in future.Among the basic questions that will guide the design of the parsingalgorithm for a middleware component are these:• What is the format of the packet?• What will the parser change in the packet?• How will the parser change the packet?ExampleA number of examples of this problem come from individual protocolmodules needing to process data packets received by the Symbian OSCommunications Infrastructure.

In this situation, when a data packetis prepared for transmission, it is typically structured so there is aninformational header at the start of the packet and then the payloaddata. Hence, as a packet received from a remote device will have beenprocessed by a whole stack of communication protocols, it will have astack of headers above the payload data.As a received packet is processed through the inbound stack, eachprotocol identifies and analyzes the header set by its remote peer protocol;parses the data it finds there and then, if all is well, passes the data packeton up the stack, usually removing the header it has just parsed.

As suchit is common for the start of the data packet to get closer to the payloadat each higher layer in the stack.For this specific example, we focus on just one of the protocols inthe Symbian OS Bluetooth protocol stack – the Audio/Video DistributionTransport Protocol.10 This protocol allows audio and video data to bestreamed between two devices such as a mobile device acting as a musicplayer and a set of headphones. To do this, the protocol specificationdefines two separate channels:• a signaling channel for A/V stream negotiation and establishment• a transmission channel to carry the actual A/V data.AVDTP sits at the top of a protocol stack and receives data from theL2CAP Bluetooth protocol below which needs to be passed onto theclient above.The algorithm for parsing each packet received on the signalingchannel needs to first identify the protocol header and then parse andanalyze it.

The information in the header triggers state changes in whichother protocol tasks are performed, such as starting or stopping the10bluetooth.com/Bluetooth/Technology/Works/AVDTP.htm.312OPTIMIZING EXECUTION TIMEtransmission channel. In this example, the payloads of the packets arefairly small and, in some cases, not present so no transformations of thedata are needed before passing the packet on up the protocol stack.SolutionAn efficient solution for data parsing can be achieved using a pattern thatis analogous to processing sheet metal in a machine press.11 The machinestamps or molds each raw sheet of metal into a particular form accordingto whatever stencil12 has been attached to the press tool. The stencil canbe changed to produce a different effect on the metal – perhaps bending,trimming or punching holes in it.

The same press and stencil combinationmay well process a number of raw sheets of metal in a continuoussequence.As you can see this is a concept that resonates for our problem asfollows:• Each packet is formed of a section of raw data.• The well-known format of the packets is a stencil.• The parsing operations are performed using a stencil by the data press.Our solution can then be described as follows: the raw data is passedfrom a source to a class that encapsulates the data press operations.

Thisdata press passes the raw data to a stencil class whose sole responsibilityis to interpret a packet’s worth of data and then inform the data press ofwhat the packet means. It is the responsibility of the data press to act onthis information by, for instance, passing the data on to the destination,or sink, of the data.

The stencil object is then re-used to interpret the nextpacket’s worth of data until the stream has been consumed.StructureThe source component from which the data press receives raw data andthe sink component to which it routes data are usually already present,or at least defined, when this pattern is used to develop a middlewarecomponent so this pattern doesn’t focus much attention on these exceptfor how they interact with the other objects. Note that the RawData classis intended to represent some storage class such as a C class, a descriptoror perhaps an RMBufChain.The solution is expressed by the structural diagram in Figure 8.4.

Thedata press itself provides the main interface to the middleware componentas a whole and is alive the entire time the middleware component isbeing used to process a stream of data. It is responsible for creating the11 en.wikipedia.org/wiki/Machine12 en.wikipedia.org/wiki/Stencil.press .DATA PRESS313CSink+NewData(RawData*)«Event Mixin»MPacketEvents++MpePacketTypeEvent(CStencil&)MpeInvalidPacket(CStencil&, Tlnt)CStencilCData Press+NewData(RawData*)11−iRawData: RawData++++−−−−NewData(CRawData*)TransferPayload()PacketType()HeaderField()Process()ValidatePacketTypeL()HandlePacketTypeL()Reset()CSource+ SendResponse()Figure 8.4Structure of the Data Press patternother objects it depends on, such as the stencil.

There are a numberof choices for how this is done including the patterns described inChapter 3. However, a common choice for the lifetime of the stencilobject is Immortal (see page 53) so that it is created and destroyed withthe data press object. This is in the expectation that the stencil willalways be needed by the data press object as no data can be routed to itsdestination without first being interpreted by the stencil.This approach neatly avoids the need to allocate an object simply toparse the incoming data.

This is a significant benefit, as allocations arenormally costly and unbounded operations would otherwise negativelyimpact your latency and perhaps break any real-time guarantees yourcomponent has promised to maintain. A final consideration is that bydoing this you should be able to avoid any system errors whilst parsinginbound data which will make your design more robust. Of course you’llstill need to handle domain errors such as malformed packets.The data press uses Event Mixin (see page 93) to provide the stencilwith an interface through which it can pass the results of its interpretation314OPTIMIZING EXECUTION TIMEof each packet.

Commonly, this interface defines a method for each typeof packet that the raw data can be interpreted as, in addition to a functionsuch as MpeInvalidPacket() that is used to tell the data press thatthe raw data is corrupt in some way.The stencil is used to encapsulate the raw data in terms of a welldefined format. As such, the stencil models the header of the packet andprovides the data press with accessor functions for the various individualpieces of information in the header, also known as fields.

These accessorfunctions interpret the raw data on demand and return the required value.By accessing fields through these functions the caller can be entirelyunaware of how the header field is actually represented in the raw data.For instance, this allows you to confine the awareness of how the raw datais ordered, a concept known as endianess,13 to just the implementationof these functions.The stencil relies on the persistence of the raw data all the while it isprocessing it. In addition, it must have sole access to the data so that youdo not need to have the overhead of synchronizing access to the data toavoid corrupting it.Figure 8.4 assumes that only one type of stencil is needed in yourcomponent. This is perfectly OK if each of the different packet types youmight receive have a fairly similar structure.

In this case, a single stencilclass is appropriate and it will just have distinct functions to validate andhandle each specific packet type. However, you might find that a groupof distinct stencil types is more appropriate when you need to parse adiverse set of packet formats.DynamicsFigure 8.5 shows a single packet being processed. The functional objective is always to parse and process the raw data in a well-defined way.The data comes from some source object and is passed to some sinkobject.A pointer to the raw data is passed upwards from the sink to the stencilby way of the data press. A pointer is used so that we avoid having to copythe data.14 When the stencil receives the raw data it takes ownership of ituntil it has finished processing it. At that point the ownership passes backto the data press as that class is responsible for routing the data.

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

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

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

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