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

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

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

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

SDP can store this information in the service recordas a ProtocolDescriptorList (say for the L2CAP connection),and an AdditionalProtocolDescriptorList (for the RFCOMMconnection).4.2 Bluetooth in Symbian OS4.2.1 Overview in Symbian OSSymbian develops its own implementation of the Bluetooth host. Thisgreatly increases Bluetooth interoperability between any Symbian OSbased devices. It also increases the functional compatibility betweenthe applications and the underlying Bluetooth subsystem in the OS.The Symbian OS host is designed to run over any controller. Notethat different controllers have different feature sets; thus some featuresdiscussed within this chapter may not be available on all platforms.However, any unsupported features will fail gracefully at the API level.BLUETOOTH IN SYMBIAN OSBluetooth / SDPSDPDatabase.dllSDPServer.exeBluetooth / UserSDPAgent.dllBluetooth.dllSerComms::C32Bluetooth / BTComm83Bluetooth / ManagerBTDevice.dllCommsInfras::ESockBTManClient.dllBTManServer.exeBluetooth / StackBTComm.CSYBT.PRTBluetooth / HCIHCI.dllFigure 4.7The Bluetooth subsystem in Symbian OSThe Symbian OS Bluetooth host consists of a number of protocolsdescribed within the Bluetooth specifications: these are L2CAP, SDP,RFCOMM, OBEX, AVCTP, AVDTP and BNEP.

The profiles within Symbian OS (as delivered to licensees of Symbian OS) are GAP, SPP, AVRCP,GAVDP and PAN. These will be discussed in this chapter.A large part of the Bluetooth subsystem is available via ESOCKAPIs – details on the generic APIs are available in Chapter 3, but here weshow the Bluetooth-specific details.4.2.2 Discovering and Connecting to DevicesDiscoverability of the Local DeviceApplications within Symbian OS cannot set the discoverability of the localdevice. The reason for this is that it is a user-controllable, device-wideproperty that the user expects to set from a single location.

If applicationsinterfere with the discoverability of a device then the user can feel ‘out ofcontrol’. Symbian OS supports the limited discoverable mode; however,there are, at the time of writing, no UIs that take advantage of this feature:the UIs only present the general- and non-discoverable modes.The Bluetooth stack in Symbian OS actually has a more complexusage of the discoverability setting than the binary indication of most UIsimplies: the Bluetooth device is never made discoverable unless thereare Bluetooth services running to which connections can be made. In84BLUETOOTHpractice the SDP server is always listening for connections, so wheneverthe user requests the device be made visible then it occurs.

The usercan, of course, override this to become invisible – in this case they canlimit the devices that connect to those that they have connected withpreviously.7Device discovery using basic symbian OS mechanismsThere are two options for discovering other Bluetooth devices, dependingon whether you need user interaction or not.

First we’ll cover theunderlying device discovery system which can be used directly if required,and on which the device selection UIs are based, then we’ll go on to lookat the specific UIs provided by S60 and UIQ for performing this task.Bluetooth devices can be found using RHostResolver, along withTInquirySockAddr.Each protocol in Symbian OS can expose a ‘host resolver’: the semantics and functions of the host resolvers depends on the protocol exposingthem. Only the ‘BTLinkManager’8 protocol in the Symbian OS implementation of Bluetooth can create host resolvers.The TInquirySockAddr allows configuration by an application ofthe operations presented by RHostResolver. The TInquirySockAddr class is also used to retrieve the results from the Bluetooth devicediscovery.The important methods on TInquirySockAddr are:IMPORT_CIMPORT_CIMPORT_CIMPORT_CIMPORT_CIMPORT_CIMPORT_CIMPORT_CTInquirySockAddr();TBTDevAddr BTAddr() const;void SetBTAddr(const TBTDevAddr& aRemote);static TInquirySockAddr& Cast(const TSockAddr& aSockAddr);TUint16 MajorServiceClass() const;TUint8 MajorClassOfDevice() const;TUint8 MinorClassOfDevice() const;void SetIAC(const TUint aIAC);Notice that one of the methods allows the setting of the IAC, theinquiry access code.

Two values are specified: KGIAC and KLIAC. If thelatter is used then a limited discovery will be performed; specifying theformer will yield a general discovery. Since most user interfaces on mostdevices do not support being in limited discovery mode, it is rarely worthperforming a limited discovery.7Even in non-discoverable mode it is possible for someone to ‘brute-force’ a discoveryby attempting to connect to every single device that could possibly exist. Because of this,non-discoverable mode should not be considered a strong security measure, but rather away of making the device harder to find without a concerted effort.8This protocol is not defined in the Bluetooth specification.

Symbian OS implements alayer separate to, and below, L2CAP that manages and models the logical transports andphysical links being used. This ensures the implementation of L2CAP follows the L2CAPspecification much more closely.BLUETOOTH IN SYMBIAN OS85Example 4.1 shows how the two classes are used to begin a devicediscovery, and retrieve the results:class CBtDeviceDiscoverer : public CActive{public:...void DiscoverDevicesL();virtual void RunL();...private:RSocketServ iSocketServ;RHostResolver iHostResolver;TInquirySockAddr iInquiryAddress;TNameEntry iNameEntry;};void CBtDeviceDiscoverer::DiscoverDevicesL(){TProtocolDesc pInfo;_LIT(KLinkMan, "BTLinkManager");TProtocolName name(KLinkMan);// precondition: iSocketServer has been Connect()ed successfullyUser::LeaveIfError(iSocketServer.FindProtocol(name,pInfo));// Open an appropriate host resolverUser::LeaveIfError(iResolver.Open(iSocketServer,pInfo.iAddrFamily,pInfo.iProtocol));// Set up inquiry addressiInquiryAddress.SetIAC(KGIAC);iInquiryAddress.SetAction(KHostResInquiry);iResolver.GetByAddress(iInquiryAddress, iNameEntry, iStatus);SetActive();}void CBtDeviceDiscoverer::RunL(){if(iStatus.Int() == KErrNone){//We found another device, fetch the addressTBTDevAddr bdaddr = TBTSockAddr::Cast(iNameEntry().iAddr).BTAddr();// Do something with address here (eg.

add to an array of discovered// devices// Now get the next device from those foundiResolver.Next(iNameEntry, iStatus);SetActive();}else if(iStatus.Int() == KErrHostResNoMoreResults){// the search has finished}}Example 4.1Discovering devices without using a UIAlthough devices may be found using RHostResolver (mappingonto the device discovery procedure in the Generic Access Profile), thereis no guarantee that the device provides the service sought. For example,86BLUETOOTHa device such as a phone is unlikely to provide a printing service.

SDPallows devices to be queried to discover what services they provide. SDPalso allows the discovery of features within the services provided, settingsused by a service, and the parameters required to connect to a service.The Bluetooth stack also places devices in the host resolver at timesother than during the inquiry phase. This allows, for example, the classof device of a remote device that has never been found in a devicediscovery and that connects to the local device to be stored by thestack. The application, having received a successful connection at theL2CAP or RFCOMM level can then query the host resolver for details ofa single device (for example, a device which has just connected to thatapplication).To query the host resolver for details of a specific device the followingcode can be used – in this case we’re connected to a remote device andwant to know if it supports any object transfer services:// iSocket is connected to a remote deviceTBTSockAddr socketAddress;(void)iSocket.RemName(socketAddress);//hostResolver is a successfully opened Host ResolverTInquirySockAddr inqAddr(socketAddress);inqAddr.SetAction(KHostResCache);TNameEntry name;hostResolver.GetByAddress(socketAddress, name); // note we use thesynchronous version here as we are looking something up from the localdevice cache// Extract CoD informationTUint16 majorServiceClass = inqAddr.MajorServiceClass();// Now see if the device supports the object transfer major service classif(majorServiceClass & EMajorServiceObjectTransfer){// we should now perform an SDP query to see if it supports the type ofobject transfer (eg.

OPP) that we require}Example 4.2Checking CoD information for a connected deviceNote that we could have used much of the second half of this exampleto perform the same functionality on the results of a device discovery tofilter out devices that did not support the type of functionality we wereinterested in.Device discovery using standard UI mechanismsIn order to perform device discoveries where user interaction is requiredit is best to use the device discovery mechanism provided by the UI platform – in the case of S60 this is using a notifier through the RNotifierinterface, and in the case of UIQ it is CQBTUISelectDialog.BLUETOOTH IN SYMBIAN OS87Figure 4.8 S60 and UIQ device selection dialogsIn the S60 case, the implementation of device selection through thenotifier framework means that you can use the device selection routinesfrom any thread, whether it has an UI environment or not.

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

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

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

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