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

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

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

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

The SDP specification should be consulted for the syntaxof the well-known attributes.And, as mentioned in section 4.1.6, you can create user-definedSDP attributes (with an ID above 0x0200) and assign any meaning youwish to them – however, it’s not uncommon to discover that you don’tactually need any of your own attributes at all, in which case there’sno need to use them.When registering an SDP record that advertises a service that canreceive connections you should register at least two attributes, although,as described above, the first is done for you as part of creating the servicerecord:• ServiceClass (attribute ID = 0x0001) (or Service (attribute ID =0x0003); though normally only ServiceClass is used).• ProtocolDescriptorList (attribute ID = 0x0004).The ProtocolDescriptorList contains information that allows a remotedevice to configure its Bluetooth protocol stack to connect to yourservice on the local device.

It consists of a list of protocols and protocol ‘details’. Each of the common protocols in Bluetooth has beenassigned a 16-bit UUID which can be used in the ProtocolDescriptorList. These values can be found on www.bluetooth.org/assignednumbers/service discovery.php; but the more common are shown below:• L2CAP: 0x0100• RFCOMM: 0x0003• OBEX: 0x0008.In the case where RFCOMM is used, the well-known L2CAP port onwhich RFCOMM runs is not required in the ProtocolDescriptorList.For an L2CAP-based service the developer would register the L2CAPport on which its service is running in the ProtocolDescriptorList as a16-bit value.106BLUETOOTHSo, as an example, let’s see what the basic SDP registration lookslike (in high level abstract terms) for a Symbian OS device acting as aBluetooth modem (i.e., implementing the DUN profile).The ServiceClass is {DialupNetworkingUUID, GenericNetworkingUUID}. This is a case where a list of service classes are used ratherthan just a single one.

In this case the GenericNetworkingUUID addsnothing of benefit to the ServiceClass, so could easily be excluded(indeed, it is marked as optional in the spec).The ProtocolDescriptorList could be, as an example, {L2CAP,RFCOMM, 13}, if the next available server channel at the time the DUNcode requested one happened to be 13.

In this case, we do not need togive a port for L2CAP, as the RFCOMM port is well known.It should now be fairly obvious which details you require aboutyour service to register a protocol descriptor list with the appropriateinformation in – either L2CAP port if you’re running over L2CAP, orRFCOMM server channel number, if you’re running over RFCOMM. Youcan see an example of how to do this in section 4.3.5.SDP agentNow we’ve covered registering a service in the local SDDB, it’s timeto cover searching for a service in a remote SDDB.

To avoid confusionbetween Symbian OS ‘clients’ (with respect to servers in Symbian OS)and the Bluetooth SDP ‘client’ of the specification, the term ‘agent’ isused to refer to the entity that can probe the SDDB of remote devices.The class that enables use of the SDP agent is CSdpAgent; of whichthe interesting methods are:IMPORT_C void SetRecordFilterL(const CSdpSearchPattern& aUUIDFilter);IMPORT_C void SetAttributePredictorListL(const CSdpAttrIdMatchList&aMatchList);IMPORT_C void NextRecordRequestL();IMPORT_C void AttributeRequestL(TSdpServRecordHandle aHandle,TSdpAttributeID aAttrID);IMPORT_C void AttributeRequestL(TSdpServRecordHandle aHandle, constCSdpAttrIdMatchList& aMatchList);IMPORT_C void AttributeRequestL(MSdpElementBuilder* aBuilder,TSdpServRecordHandle aHandle, TSdpAttributeID aAttrID);IMPORT_C void AttributeRequestL(MSdpElementBuilder* aBuilder,TSdpServRecordHandle aHandle, const TSdpAttrIdMatchList& aMatchList);To use CSdpAgent, a client must implement MSdpAgentNotifierto receive callbacks from the SDP agent as it retrieves information from theremote SDDB, and a Bluetooth device address.

The interesting methodsof MSdpAgentNotifier are:virtual void NextRecordRequestComplete(TInt aError, TSdpServRecordHandleaHandle, TInt aTotalRecordsCount)=0;BLUETOOTH IN SYMBIAN OS107virtual void AttributeRequestResult (TSdpServRecordHandle aHandle,TSdpAttributeID aAttrID, CSdpAttrValue* aAttrValue)=0;virtual void AttributeRequestComplete (TSdpServRecordHandle, TIntaError)=0;Once an SDP agent is constructed, an SDP query to a remote deviceinvolves the following steps:1.

Create a search pattern.2. Ask for the next record.3. When records matching the search pattern are found, ask for attributeson those records as necessary.4. Example code showing the use of the SDP agent APIs is in section4.3.5.CSdpSearchPatternThis class encapsulates a list of SDP UUIDs for which to search. Whensearching with a list of UUIDs, ‘AND’ search logic is used. However,there is an oddity in the SDP specification – when a client issues a servicesearch or service search attribute request with a set of UUIDs to a remoteSDP server, the remote server is allowed to return any service record inwhich all of the UUIDs appear in whichever attributes.

This is slightlyunsatisfactory since the client will usually wish to look for the UUID beinglisted in the ServiceClass attribute. Therefore, a two-phase approach isoften made: search for the UUID; receive the list of record handles, thenfor each record, query the attributes of interest to see if the UUID isindeed in that attribute.Attribute values in symbian OSAll SDP attribute values in Symbian OS are derived from CSdpAttrValue, a common base class which allows attributes of all types tobe used polymorphically.

You can use CSdpAttrValue’s Type()function to find the actual type being used and cast appropriately. Theinheritance tree is as shown in Figure 4.11.Useful methods on the base class are:virtualvirtualvirtualvirtualvirtualvirtualTUint Uint() const;TInt Int() const;TBool DoesIntFit() const;TInt Bool() const;const TUUID &UUID() const;const TPtrC8 Des() const;Only those that are meaningful to the derived class are overridden bythem; for example CSdpAttrValueBoolean will override virtual TIntBool().CSAttrValueNilcd Logical ModelCSdpAttrValueBooleanCSdpAttrValueStringCSdpAttrValueUUIDMSdpElementBuilderFigure 4.11 Class structure for representing SDP attribute valuesCSdpAttrValueDESCSdpAttrValueDEACSdpAttrValueUintCSdpAttrValueListCSdpAttrValueIntCSdpAttrValueCSdpAttrValueURL108BLUETOOTHBLUETOOTH IN SYMBIAN OS109CSdpAttrValueDES and CSdpAttrValueDEA encapsulate the dataelement sequence (DES) and data element alternate (DEA) types.

As previously stated, a DES is a list of values, all of which are relevant; aDEA is a list of values from which one should be chosen. Although theCSdpAttrValueList-derived classes are not abstract in C++ terms,they are conceptually abstract, as they are just lists of other CSdpAttrValueobjects.It can be seen from Figure 4.11 that CSdpAttrValueList implements the MSdpElementBuilder mixin. ‘Builder’ here refers to thebuilder pattern in the GoF book (Gamma, Helm, Johnson, Vlissides1995), and allows the construction of the complex list-based SDP values:the DES and DEA. SDP allows attributes to comprise of lists, which maythemselves contain lists, which may in turn contain another list, and soon – the builder pattern simplifies to some extent the construction of thepotentially complex SDP values.The SDP agent allows the client to specify a set of attributes that itwill retrieve from the remote device.

The attributes do not have to becontiguous. The CSdpAttrIdMatchList class should be used to buildthe set of attributes. The attributes or ranges of attributes are held inTAddrRange structs; and CSdpAttrIdMatchList is a container ofinstances of TAddrRange. The SDP agent does not possess an explicitconnect or disconnect API – SDP connections are transparently createdand destroyed as necessary.4.2.9 SDAPThe service discovery application profile (SDAP) is not directly supportedwith its own API in Symbian OS. One particular service present in SDAPis quite useful – the ability to search for a given service on multipleBluetooth devices.

In other words, you can choose to find a service,without caring which device it is running on: most Bluetooth usagescenarios involve the user nominating a device, and then finding theappropriate service on that device to which to connect.The example developed in this chapter of a multiplayer game usesSDAP.4.2.10 RegistrySymbian OS provides a permanent store to support the UI and theBluetooth stack, but also has some use for Bluetooth applications.

Thestore is called the Bluetooth registry. It has a number of internal tables:• One for persisting the state of the local Bluetooth device, so thatsettings such as discoverability and the name of the device arepreserved between reboots.110BLUETOOTH• One for details of remote Bluetooth devices, such as a ‘friendly’ namethat the user of the local device has assigned to a remote device, andsecurity tokens for remote devices.• One for settings of the virtual Bluetooth serial ports. All paired devicesare stored by the Bluetooth stack in the registry.The Bluetooth registry is a Symbian OS server – you can access itthrough a combination of the RBTRegServ and RBTRegistry APIs.Once connected, the client can find details of individual devices, orobtain a ‘view’ on the registry’s contents.

The view will contain 0 ormore devices, constrained by some search criteria. A view is created byusing the RBTRegistry class which forms a subsession on the registryserver. A view is created asynchronously – and the TRequestStatusused in the asynchronous request returns with either an error, or, in thesuccessful case, the number of devices in the view.Note that a value of ‘zero’ represents a successful view creation butwhich resulted in zero devices in the view.It is worth briefly surveying the classes that correspond to Bluetoothdevices in Symbian OS. The primary class is CBTDevice. If Bluetoothnames are not important – as is often the case in the Bluetooth stack – a‘cut down’ version of this class, TBTNamelessDevice is also available.It can be queried with an API that can provide a view onto the registry’sdatabase.

To retrieve all of the details of each device in the view, theCBTRegistryResponse class is used. It is an active object that willasynchronously create an array of CBTDevice classes. For example, aview of all trusted laptops can be obtained, thus:{// connect a session with Registry ServerUser::LeaveIfError(iRegistryServer.Connect());// Get a ‘View’ (subsession) with RegistryUser::LeaveIfError(iView.Open(iRegistryServer));// set view to be of Bluetooth laptops held in RegistryTBTDeviceClass laptop(0, EMajorDeviceComputer,EMinorDeviceComputerLaptop);// keep copy of the search pattern to go asynciSearchCriteria.FindTrusted(ETrue);iSearchCriteria.FindCoD(laptop.DeviceClass(),static_cast<TBTDeviceClassSearch>(EMajorDevice | EMinorDevice));iView.CreateView(iSearchCriteria, iStatus);SetActive();}// snip – in RunL...::RunL(){// the iStatus now contains an error, or the number of results in the// viewBLUETOOTH IN SYMBIAN OS111iResponseHandler = CBTRegistryResponse::NewL(iView);iResponseHandler->Start(iStatus);SetActive();}Example 4.10 Searching the Bluetooth registry for all devices with aminor device type of ‘laptop’4.2.11 Error CodesBluetooth applications should expect errors that are in both the systemwide error range of Symbian OS and a Bluetooth-specific range.

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

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

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

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