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

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

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

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

The flip side of this is that latency willincrease, so for interactive communications the buffers mustn’t be toobig.Latency is largely a feature of the network and outside your directcontrol, but can be improved by sending data in smaller packets. Thisallows urgent data to be sent faster as it doesn’t have to wait for largeoutgoing packets to clear, however, this often increases the protocoloverhead, as the amount of data in each packet is smaller whilst thepacket header length stays constant. So an improvement in latency ismatched by a reduction in (user-visible) bandwidth.62AN INTRODUCTION TO ESOCKUser-visible bandwidth can be improved by keeping the network fullyutilized.

To do this, it’s important to start a new send or receive operationas soon as the previous operation completes. If your program needs toprocess the incoming data, then a double-buffering strategy is often useful,where one buffer is being filled by ESOCK whilst you process the other,then, once both sides have finished processing their current buffers, youcan switch them over. This can result in substantial performance gains.Closing downThe normal way to close a CSocket is simply to delete the object. Thisautomatically cleans up and cancels any outstanding reads or writes andshuts any ESOCK handles.If you need the shutdown behaviors provided by RSocket::Shutdown() then you can use the CSocket::Socket() call to retrieve theunderlying RSocket and call Shutdown() on this, before deleting theCSocket.It’s not possible to reconnect a CSocket after it’s been disconnectedas not all protocols support this.

Rather than code round this, it is simplerto just delete and recreate the CSocket object.3.3 SummaryIn this chapter we’ve covered:• an overview of ESOCK’s services• the different types of socket – stream, sequenced packet and datagram• the differences between connection-oriented and connectionless protocols• the main ESOCK API classes: RSocketServ, RSocket, RHostResolver, RNetDatabase RConnection and RSubConnection• how to use the sockets API to make connections and to receiveincoming connections• sending and receiving data over a socket• a basic framework for writing your own socket-based communicationsprograms.4BluetoothThis chapter starts with a description of Bluetooth technology. Even ifyou have some experience with Bluetooth it may still be worth skimmingthrough the technology part of the chapter just to understand how all theparts fit together.Each section in the technology part has a corresponding sectionin the description of how Bluetooth is implemented in Symbian OS.Thus you can rapidly move between concepts and implementation tounderstand how Symbian OS is presenting the underlying Bluetoothfunctionality.There is a lot of detail in this chapter as we cover many different areasof Bluetooth.

For building basic Bluetooth services, we recommend youread:• discovering and connecting to devices (sections 4.1.2 and 4.2.2)• service discovery and SDP (sections 4.1.6 and 4.2.8)• L2CAP (sections 4.1.5 and 4.2.5).4.1 Bluetooth Technology OverviewBluetooth is a general-purpose short-range wireless technology, whichpresently operates in the industrial, scientific and medical band at2.4 GHz, although in future it may run over other radio bands. It isdesigned with resource-constrained devices in mind. In particular, Bluetooth optimizes battery consumption – a key issue with mobile devices.Originally Bluetooth was seen as replacing two common cables – theRS-232 serial cable and the cable linking a mobile phone and a headset.Increasingly, Bluetooth is now replacing other cables: stereo audio, video,parallel, USB and Ethernet.64BLUETOOTHOne of the key axioms of Bluetooth is to assume that devices have asimilar underlying level of functionality,1 rather than assuming one ‘smart’host and many, relatively ‘dumb’ devices – contrast this with USB, whichwas designed with the ‘one host, many peripherals’ approach.

This is nowbeing rectified in USB with the On-The-Go (OTG) standard; however, itrequires additional implementation in all devices that wish to support it.One benefit of the more symmetric Bluetooth approach is that aBluetooth connection can be initiated by either device, and used forany purpose – allowing use cases, such as peer-to-peer messaging, to besupported that would be much harder to implement and configure usingmore host-centric technologies.Another major strength of Bluetooth is the support for ‘profiles’. Theseconsider end-to-end use cases, such as connecting a headset to a mobilephone, and specify standard ways of achieving them. The benefit of thisis that a Bluetooth device does not require individual drivers to performa task: if it did, then all Bluetooth devices would need some store ofdrivers for each other potential Bluetooth device with which they wishedto communicate.

The profile concept is similar to the USB concept ofdevice class, although typically Bluetooth profiles go further in describinga use case than the USB device class specifications.Bluetooth profiles also provide a benefit over technologies such asWLAN, which concentrates on providing a wireless version of Ethernettechnology only – higher level specifications are set by other standardsgroups, such as the IETF. As a result, assembling the stack of protocolsand defining a configuration required to implement a use case can be farharder when using WLAN technologies, and equipment using differenttechnologies for implementing the same use case can be on the marketat the same time – leading to user confusion.

The wide range of devicesenabling voice-over-IP is evidence of this – some use SIP, some useproprietary protocols, and all are forced to interoperate using the lowestcommon denominator of the PSTN.The Bluetooth standards comprise a number of protocols and profiles – currently around 8 and 12, respectively – that describe how to usethe protocols in an interoperable way to fulfil various use cases such asprinting, networking, exchanging files, listening to audio, watching videoand connecting mice and keyboards.1By this we mean there is nothing in the Bluetooth specifications that requires onedevice always to act as a service provider.

Instead any device could potentially act inany role – this is purely a function of the software support above the L2CAP layer. So,for example, a single mobile phone could simultaneously be acting as a modem for aconnected laptop, and utilizing the services of a Bluetooth headset for making a phone call.Such an arrangement would be extremely difficult using USB (aside from the tangle of wiresit would cause!).BLUETOOTH TECHNOLOGY OVERVIEWA2DPVOIPUMA‘IP Modem’GamingPPPSDPAVDTPAVCTPBNEPATPBAPBIPBPPFTPOPPSAPHSP/HFPDUNLAPPANRTPFECHCRPRTP RTCPHIDIPAVRCPGAVDPSDAPSBCcodec65OBEXRFCOMMFlow & Error ControlL2CAPACL(e)SCOHCIFigure 4.1Bluetooth protocols, indicating those discussed in this chapterFigure 4.1 shows the profiles and protocols that make up the Bluetoothspecifications – the box indicates the areas that are discussed in thischapter.

Bluetooth is such a wide-ranging technology that it would beimpossible to cover all areas, especially as some of the profiles are notof particular interest to developers: often they are implemented entirelywithin the OS and do not present any user-visible APIs – PAN, HID andA2DP are examples of such profiles which are hidden behind existinggeneral-purpose APIs.4.1.1 Architectural OverviewBluetooth devices are usually implemented in two parts: the host and thecontroller. Effectively, the controller consists of the Bluetooth hardwarealong with the lowest levels of the Bluetooth stack such as the physicallink manager; and the host is a set of higher level protocols and profilesand other supporting libraries that interact with the controller. The hostand the controller communicate via the host controller interface, HCI(which may not be physically present, but always exists in Symbian OSdevices, and is worth at least modelling logically).

The controller liesunder the HCI in Figure 4.1 but is not shown as it is discussed only brieflyin this chapter because all functionality is accessed through the higherlevel Symbian OS APIs.Within the controller, a number of entities control the power of theradio, the frequencies on which it transmits and receives at any particular66BLUETOOTHApplication channelsAVDTP, RFCOMM etcLogical ChannelL2CAPLogical LinkACL-C, ACL-U,SCO, eSCOLogical TransportACLSCO, eSCOHostControllerPhysical LinkPhysical ChannelInquiry scan, page scan,piconetRF ChannelsPseudo-randomlyselected, 1MHz wideFigure 4.2 Bluetooth channel architecturetime, communication with the host, and direct communication with thepeers in other Bluetooth hardware. Figure 4.2 introduces the types oftransport entities at the lowest layers in Bluetooth; and shows where thehost/controller split lies.

The left-hand side of the diagram is the classof transport, the details of which we’ll explore later in the chapter, theright-hand side enumerates the instances available of that type – again,we’ll discuss these in more detail later.Most of the protocols are implemented within the host, along with theprofiles. The lowest level of the host protocols is L2CAP, which presentslogical channels to higher level protocols, applications and profiles.L2CAP is roughly analogous to a hybrid of TCP and UDP in terms offunctionality. Unlike TCP and UDP, where the requirement for reliabilityvs. timely delivery forces you to choose between the two protocols,L2CAP, when operating with the optional flow-and-error control feature,can be configured to choose between the two options within the sameprotocol.4.1.2 Discovering and Connecting to DevicesWireless devices must provide some ‘association model’ to allow theuser to select other devices with which to interact.

For wired devicesthe model involves physical interaction with the other device, typicallythe insertion of a cable. In the wireless case there is obviously no cableinvolved, so what is the alternative?The usual method is to make the local device ‘visible’ when it wishesto be discovered by other devices. Devices are usually visible via theBLUETOOTH TECHNOLOGY OVERVIEW67technology that will ultimately be used to exchange data with them, i.e.,visibility is handled ‘in-band’.2In Bluetooth, a number of concepts are used when referring to the stateof two devices that require association:• discoverable• connectable• pairable.DiscoverabilityIf a device is discoverable it will respond to searches made by otherBluetooth devices.

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

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

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

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