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

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

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

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

Theexported header bt_sock.h shows the values that are possible. Thefollowing are particularly important:Page timeout, KHCIErrorBase-EPageTimedOut, -6004This indicates that the device to which a connection has been requestedis either not in range, or is not listening for connections. Some servicesmay wish to treat this as a non-fatal error, and move on to attempt toconnect to the ‘next’ device (it is up to the service to deduce what ismeant by ‘next’ device).Link disconnection, KErrHCILinkDisconnection, -6305This error is returned if the physical link is unexpectedly lost.

This canindicate that the remote device has moved out of range (rather than theuser of the remote device instructing it to gracefully close a higher layerprotocol connection, in which case the error seen by the local socketuser would be KErrDisconnected).Access Denied, KErrL2CAPAccessRequestDenied, -6311This error indicates that during a connection attempt the remote devicerejected the connection due to the user of that device either rejecting anauthorization or the user type a passkey that did not match that enteredat the local device.Reflexive link, KErrReflexiveBluetoothLink, -6452The application is attempting to connect to itself: this indicates thatthe application has got the remote and local Bluetooth device addressestransposed.

At present the Symbian OS Bluetooth stack does not support‘loopback’ connections, so the stack errors the connection with this value.112BLUETOOTH4.3 Example Symbian OS Bluetooth Application4.3.1 OverviewWe’ll now discuss an example application of Bluetooth; that of an ad-hocnon-star-topology transport that can be reused for games, messaging, etc.The example here demonstrates use of searching for devices and services; forming connections, exchanging data; and managing the Bluetoothtopology and using sniff mode.• CBluetoothSockets (and therefore demonstrates how RSocket andRBTPhysicalLinkAdapter can be used)• SDP server• SDP agent• Device discovery (coupled with SDP to form SDAP).The intent of the application is to enable ‘long-distance’ Bluetoothconnections; longer than the regular 10 or 100 m Bluetooth link.

Usecases for this might include:• Repeater stations, for example to form a link to a remote printer whichis of a distance greater than that reachable by a direct link; but can bereached by making use of intervening Bluetooth stations.• Gaming – multiplayer ‘very wide screen’ game – for example a ratruns ‘along’ all of the devices’ and is rendered on each device in turn;the owner of each device has to attempt to trap the rat before it movesonto the next station.• Messaging – enumeration of all of the Bluetooth devices forming theconnection ‘substrate’ would allow the sending of a message fromone station to another.The example provides the connection topology – the ‘bus’.

The busis composed of L2CAP connections over alternating master → slave andslave → master physical links. Over this substrate is the most basicmultiplexing protocol – this allows a multiplicity of higher protocolsto share the bus. Some of these protocols might provide forwardingfunctionality, bus enumeration etc.4.3.2 ImplementationAs we have seen in this chapter the basics of a Bluetooth service are to:1.Register the service record – RSdp, RSdpDatabase, CSdpAttrValueEXAMPLE SYMBIAN OS BLUETOOTH APPLICATIONDevicen−1DevicenDevicen+1113Devicen+2Cross-bus connectionL2CAP logical channelMaster → slave physical linkFigure 4.12 Bluetooth link architecture for example application2. Open listening sockets – CBluetoothSocket, TBTServiceSecurity3.

Find a remote device that can take part in the service – RHostResolver, TInquirySockAddr, CSdpAgent4. Connect to the remote – CBluetoothSocket, TL2CAPSockAddr5. Transfer data – CBluetoothSocket,6. Modify the physical link as appropriate – CBluetoothSocketStep 3 is exactly the ServiceSearch feature of the SDAP profile;which can be made into a useful, reusable combination of RHostResolver and CSdpAgent. The example code provides a standaloneSDAP DLL, and this is used by our example service to find partnerdevices.4.3.3 DesignThe design yields a reusable ‘Bluetooth bus’ library, an example multiplexing protocol, and an example application protocol (see Figure 4.13).4.3.4 Service RegistrationRecognizing that the service that we have implemented allows incomingconnections, the first stage is to register details of the service with the SDPserver. This then allows any remote device to see that we have the serviceavailable on the local device (remember that we cannot use well-knownport numbers in Bluetooth), and discover some dynamic details about theservice.When creating a new service, that is not an implementation of a newBluetooth profile, a 128-bit UUID is required.

For this we just used an114BLUETOOTH<<interface>>MBluetoothBusObserver++++++++CBaseMlbtoUpstreamConnectionComplete (unsigned int): voidMlbtoDownstreamConnectionComplete (unsigned int): voidMlbtoError(int): voidMlbtoUpstreamData(const TDesC8&): voidMlbtoDownstreamData(const TDesC8&): voidMlbtoUpstreamDisconnection(): voidMlbtoDownstreamSendComplete(): voidMlbtoDownstreamDisconnection(): void<<interface>>MSDPHelperNotifyCSDPHelperTL2CAPSockAddrCBluetoothBusEngine-RSocketServiDownstream: CIdentifiableSocketiRxBuf: RBuf8iUpstream: CIdentifiableSocketiDownstreamMTU: unsigned intiUpstreamMTU: unsigned intTBusState1<<interface>>MIdentifiableSocketNotifier<<interface>>MBluetoothSocketNotifier2<<Proxy>>CIdentifiableSocketCBluetoothSocketFigure 4.13UML class diagram for example applicationInternet site (for example, see http://www.itu.int/ITU-T/asn1/uuid.html) togenerate one.

After creating a session and subsession with the SDP server,this UUID is then stored in the service record as shown below:// connect to SDP ServerUser::LeaveIfError(iSdpSession.Connect());User::LeaveIfError(iSdpRecords.Open(iSdpSession));// Set Attribute 1 (service class list) to list with UUIDiSdpRecords.CreateServiceRecordL(TUUID(KBluetoothBusUUIDHH,KBluetoothBusUUIDHL,KBluetoothBusUUIDLH,KBluetoothBusUUIDLL),iRecordHandle);EXAMPLE SYMBIAN OS BLUETOOTH APPLICATION115The next important attribute to consider is the ProtocolDescriptorList.

The example application runs directly over L2CAP, so thevalue is relatively simple:// Protocol Descriptor List// attrValDES is a CSdpAttrValueDES*attrValDES = CSdpAttrValueDES::NewDESL(0);CleanupStack::PushL(attrValDES);attrValDES->StartListL()//this begins the list of protocols->BuildDESL()//each of which is a DES->StartListL() //which is of course a list->BuildUUIDL(TUUID(TUint16(KL2CAPUUID))) // L2CAP->BuildUintL(TSdpIntBuf<TUint16>(aUpPSM))->EndListL() //finished the list for L2CAP->EndListL(); //finished the whole protocol stack//store this attribute onto the service recordiSdpRecords.UpdateAttributeL(iRecordHandle,KSdpAttrIdProtocolDescriptorList, *attrValDES);CleanupStack::PopAndDestroy(attrValDES);Finally, we use the ServiceAvailability attribute to allow a remote toquery whether it is worth connecting to the local service:// when registering there is full availabilityTUint16 availability =0;attrVal = CSdpAttrValueUint::NewUintL(TSdpIntBuf<TUint16>(availability));CleanupStack::PushL(attrVal);iSdpRecords.UpdateAttributeL(iRecordHandle,KSdpAttrIdServiceAvailability,*attrVal);CleanupStack::PopAndDestroy(attrVal);The above code snippet, although it assigns a value to the ProtocolDescriptorList attribute, is enough to demonstrate how otherattributes can be set.4.3.5 Finding the Example Service on Remote DevicesThe example application attempts to automatically build large Bluetoothnetworks.

To make the process automatic the device and service discoveryprocedures are combined into the service discovery application profile;which is provided with the example application.The interesting part to look at is the code parsing SDP service recordsand attributes obtained from the remote device.In the SDAP example, when an SDP record matching the UUID searchpattern is found, the following method is called (note the method isdefined in MSdpAgentNotifier, and implemented in the example byCSdapEngine):void CSdapEngine::NextRecordRequestComplete(TInt aError,TSdpServRecordHandle aHandle,TInt aTotalRecordsCount)116BLUETOOTHWithin this method, if the client of SDAP has asked that SDAP shouldretrieve attributes from the record (the client would have supplied anon-NULL CSdpAttrIdMatchList pointer) an attribute request is performed:// iMatchList is a client supplied instance of CSdpAttrIdMatchList// containing attributes that should be retrieved from the record foundiSdpAgent->AttributeRequestL(aHandle, *iMatchList);For each attribute retrieved the following method is called (note thatthe method is defined in MSdpAgentNotifier, and implemented inthe example by CSdapEngine):void CSdapEngine::AttributeRequestResult(TSdpServRecordHandle,TSdpAttributeID aAttrID,CSdpAttrValue* aAttrValue){// tell the client of SDAPiNotify.MsanAttributeObtained(iPotentialDevices[iDeviceIndex], aAttrID,*aAttrValue);// we still own the SDP attribute, and we’re now finished with itdelete aAttrValue;}Once all attributes have been retrieved, MSdpAgentNotifer::AttributeRequestComplete() is called, SDAP uses this to tell itsclient that its task is complete.Now, look at what the example application, as the client of SDAP, doeswith the ProtocolDescriptorList SDP attribute.

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

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

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

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