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

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

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

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

We’ll briefly recap the modes of thephysical link that we discussed in section 4.1.3.92BLUETOOTHHold mode is used internally by the Symbian Bluetooth stack to freeup capacity when discovering new devices. Hold mode is not meaningfulto individual applications – therefore there is no API for applications toplace a link into hold mode.Since Symbian OS v8.0, the Bluetooth stack does not automaticallytransition links from active to sniff mode or vice versa.

Instead it requiresinformation from applications about their requirements for the powermode of the physical link as the stack itself cannot know the nature ofthe traffic flow on that physical link. These requests are then arbitrated todetermine the actual mode of the physical link. Applications should beaware that data can be sent over a link which is in sniff mode, but thatthe latency experienced will be higher than for a link in active mode.However, as discussed earlier, there is a cost in terms of battery life tousing active mode – therefore it is advantageous to transition links to sniffmode whenever possible.Thus well-written Bluetooth applications should contain some logic toindicate their preference for the power mode of the link. If an applicationwishes to exchange a ‘large’ amount of data quickly, then it should requestthat the Bluetooth stack prevents the link going into sniff mode.

If theapplication gets to a state where it has finished its high volume data transfer then it can cancel the request to the Bluetooth stack for active mode,and may optionally indicate that sniff mode is now its preferred option.Of course, some applications may not wish to contain this level ofBluetooth-specific logic. In this case the physical link may transition intoany state, including sniff mode. The application may notice an increasein latency, or a reduction in bandwidth, of the link when this occurs.Various properties of the physical link can be adjusted using RBTPhysicalLinkAdapter. This allows an application to request variousmodifications to the underlying Bluetooth physical link to improve batterylife, performance, etc. Here’s the API:IMPORT_C TInt PreventRoleSwitch();IMPORT_C TInt AllowRoleSwitch();IMPORT_C TInt RequestMasterRole();IMPORT_C TInt RequestSlaveRole();IMPORT_C TInt PreventLowPowerModes(TUint32 aLowPowerModes);IMPORT_C TInt AllowLowPowerModes(TUint32 aLowPowerModes);IMPORT_C TInt ActivateSniffRequester();IMPORT_C TInt ActivateParkRequester();IMPORT_C TInt CancelLowPowerModeRequester();IMPORT_C TInt RequestChangeSupportedPacketTypes (TUint16 aPacketTypes);IMPORT_C void NotifyNextBasebandChangeEvent (TBTBasebandEvent&aEventNotification, TRequestStatus& aStatus, TUint32 aEventMask =ENotifyAnyPhysicalLinkState);IMPORT_C void CancelNextBasebandChangeEventNotifier();As discussed, the various calls are ‘request’-based, rather than mandatory – all current requests are arbitrated by the Bluetooth stack, withBLUETOOTH IN SYMBIAN OS93the ‘overall’ mode being determined by considering the best possible mode for the link given the requests made.

Note that a requestis considered current until the corresponding deactivation is received(e.g. PreventRoleSwitch() is cancelled by AllowRoleSwitch());the appropriate cancel method is called (e.g. ActivateSniffRequestor() is cancelled by CancelLowPowerModeRequester()); orthe request is superseded by more recent request (e.g. PreventLowPowerModes(EAnyLowPowerMode) is replaced by PreventLowPowerModes(ESniffMode)).The RBTPhysicalLinkAdapter provides a link-state observationmethod, NotifyNextBasebandChangeEvent(). This allows clientsto observe the state of the physical link, although it is not recommendedthat applications try and take any action as a result of this – applicationsshould make their requests for link configuration in all cases, ratherthan trying to monitor the link state and alter it if necessary.

Apart fromanything else, this makes the application coding much easier!In particular, we recommend that applications do not try to ‘police’the state of the physical link – for example, an application should not failto provide a service if the local device does not become the master, orthe link cannot transition to active mode.

This is because the link statecannot be guaranteed – other applications may well be running over thesame physical link, or the remote device may disallow any change to thelink. Attempts to enforce link state often end in interoperability problems,as there is no one point that has all the information required to configureall the possible links in use between interconnected devices. Thereforethe best way to maximize the chances of successful interoperability is toleave the final decision on link state to the lower levels of the softwareand hardware.4.2.5 L2CAPSymbian OS presently implements only the (far more common)connection-oriented L2CAP. Despite it being connection-oriented, it is asequenced packet protocol – which means it works slightly differently tothe connection-oriented protocol most people are familiar with – TCP.As discussed in section 4.1.5, version 1.2 of the Bluetooth Core Specification added flow control, error control and segmentation and reassembly(SAR) features to L2CAP.

All of these features are implemented in SymbianOS v8.1 and later. However, to enable their use, the remote Bluetoothdevice must also have implemented this improved version of L2CAP (thusBluetooth connections between recent Symbian OS devices are likely touse the improved L2CAP). Each of the features added in this version ofL2CAP improves the performance of L2CAP when running more than oneprotocol or profile to a remote device.L2CAP is accessed via a socket API – either RSocket or CBluetoothSocket (CBluetoothSocket is covered in section 4.2.7).94BLUETOOTHL2CAP OptionsAn advantage of using L2CAP instead of RFCOMM is that the configuration of the channel is far more flexible than with RFCOMM.L2CAP sockets are datagram-based; the client therefore has to beaware of the L2CAP packet sizes in use on the link, especially as they canbe different in each direction.

Whilst exchanging data, the applicationhas to ensure that the descriptors they send and receive will fit into themaximum transmission unit (MTU) that L2CAP has negotiated.L2CAP specifies a default MTU of 672 bytes in each direction. Notethis default is a ‘default default’ – some Bluetooth services may expecta different, default MTU which must be supported (for example, theBluetooth PAN profile requires that all implementers negotiate an MTU ofat least 1691 bytes). Finally, the L2CAP specification specifies a minimumMTU that all Bluetooth devices are required to support – 48 bytes.10Although there are various specified defaults, the application mustmake the call to check the actual negotiated MTU – at least in the sendingdirection.

If a client sends data that is too large to fit inside an L2CAPpacket, the send operation will be completed with KErrTooBig. Thenegotiated MTUs for the link are available once the L2CAP connectionto the remote device, and hence the Connect() call on the RSocketAPI, has completed.The class with which to configure L2CAP channels is TL2CapConfig.TL2CapConfigPckg is a useful typedef that uses the TPckgBuf template class in Symbian OS to assist in the transfer of a TL2CapConfiginstance to and from a socket.

Both are published in bttypes.h.The SDU the application intends to use for transmission is configured using SetMaxTransmitUnitSize(), and for the receive path,SetMaxReceiveUnitSize().The reliability of L2CAP channels can be configured: the applicationcan request an L2CAP channel be unreliable or reliable using ConfigureReliableChannel() and ConfigureUnreliableChannel().Of course, ‘unreliable’ in this case means that data will be dropped whenit has been waiting for transmission longer than the specified time, ratherthan any deliberate attempt to make the channel unreliable!An application can also influence the scheduling of L2CAP usingConfigureChannelPriority(). This allows an application that may10L2CAP (in all versions of the specification) provides a service to higher layer protocolsand applications which effectively allows the application layer to notify its peer aboutits packet sizes.

This is the MTU of the L2CAP ‘SDUs’ (the application’s packets). InBluetooth 1.1 this MTU is also the size of L2CAP packets (‘PDUs’). Although the SDU MTUnotification service is retained in Bluetooth 1.2 and later, the SDU size is not necessarilythe L2CAP PDU size (due to the SAR service). In these later versions of L2CAP the PDU sizeL2CAP negotiates is hidden from the application, although the application must still checkthe negotiated MTU even in these cases, as the remote application, rather than L2CAPimplementation, will also have restrictions on the maximum packet size it can handle.BLUETOOTH IN SYMBIAN OS95have two sockets – one for ‘commands’ and one for ‘data’ – to indicateto L2CAP that the ‘command’ socket should be scheduled with a higherpriority than the ‘data’ socket.When configuring a reliable channel the application must specify atime for which L2CAP will retry sending data packets.

If this time expiresL2CAP will disconnect the logical channel.When configuring an unreliable channel the application must specifya timeout for the data – when data is submitted to L2CAP for delivery overan unreliable channel, L2CAP starts a timer for each application SDU.When the SDU age reaches the specified value, it is dropped by L2CAP.Each of the time values just discussed is in milliseconds.IMPORT_CIMPORT_CIMPORT_CIMPORT_CIMPORT_CIMPORT_CTL2CapConfig();TInt SetMaxTransmitUnitSize(TUint16 aSize = 0xffff);TInt SetMaxReceiveUnitSize(TUint16 aSize = 0xffff);TInt ConfigureReliableChannel(TUint16 aRetransmissionTimer);TInt ConfigureUnreliableChannel(TUint16 aObsolescenceTimer);TInt ConfigureChannelPriority(TChannelPriority aPriority);The following snippet shows how to configure an unreliable channelwith a maximum transmit SDU size of 1500 bytes, a maximum receiveSDU size of 100 bytes and schedule as high priority:// iL2CapConfig is of type TL2CapConfigPckgiL2CapConfig().SetChannelPriority(TL2CapConfig::EHigh);iL2CapConfig().SetMaxReceiveUnitSize(100);iL2CapConfig().SetMaxTransmitUnitSize(1500);iL2CapConfig().ConfigureUnreliableChannel(200); // milliseconds beforedata expiresresult = iSocket.SetOpt(KL2CAPUpdateChannelConfig, KSolBtL2CAP,iL2CapConfig);Example 4.6Configuring L2CAP to provide an unreliable channelAs mentioned earlier, for any L2CAP connection, the application mustretrieve the actual negotiated SDU MTU:TInt mtu = 0;TInt err = iSocket.GetOpt(KL2CAPGetOutboundMTU, KSolBtL2CAP, mtu);Example 4.7 Retrieving the negotiated outbound MTU after an L2CAPsocket has been connectedOther L2CAP servicesOne other L2CAP service to mention is the echo request.

Similarly tothe echo-request type in ICMP, this service allows an application to testwhether the L2CAP entity at the remote device is ‘alive’, and allows theapplication to provide data that will be sent to the remote device. This96BLUETOOTHis of limited use to applications because the L2CAP specification doesnot provide guarantees about the delivery or return of any data suppliedin the echo packet. Furthermore, the Symbian OS implementation doesnot indicate to a receiving application that an echo has been receivedor replied to – the Bluetooth stack silently replies to the incoming echo.Therefore it is not suitable for application-level keep-alive services.4.2.6 RFCOMMIn Symbian OS RFCOMM can be accessed through three alternateAPIs – RSocket, RComm and CBluetoothSocket.

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

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

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

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