iOS Bluetooth 4.0 Protocol Brief Introduction

Source: Internet
Author: User

IOS Development Bluetooth 4.0 framework is Corebluetooth, this article mainly introduces the use of Corebluetooth, about the code fragment in this article is mostly from a demo on GitHub, the address is myz1104/bluetooth.
There are two main sections in Corebluetooth, central and peripheral, a little like client Server. Cbperipheralmanager as a peripheral device is a server. Cbcentralmanager as the central device is the client. All available iOS devices can be used as a peripheral (peripheral) or as central, but can not be both peripheral and central.

The general mobile phone is the client, the device (such as the bracelet) is the server, because it is the phone to connect the hand ring this server. The perimeter (peripheral) is a device that generates or stores data, and Central is the device that uses that data. You can think of the perimeter as a device for broadcasting data, and he broadcasts it to the outside world saying he has data here, and also explains the services that can be provided. On the other side, the central start scanning nearby there is no service, if the central found the desired service, then the central will request to connect the perimeter, once the connection is established successfully, between the two devices began to exchange data transfer.
In addition to the central and peripheral, we also have to consider the data structure they exchanged. The data is structured in the service and each service is composed of different characteristics (characteristics), characterized by an attribute type that contains a single logical value.

Implementation steps of Peripheral

The first is to create a perimeter

_peripheralmanager = [[Cbperipheralmanager alloc]initwithdelegate:self Queue:nil];

Next, it responds to the proxy's Peripheralmanagerdidupdatestate method, and can obtain information such as the status of peripheral,

-(void) Peripheralmanagerdidupdatestate: (Cbperipheralmanager *) peripheral{    switch (peripheral.state)    { Case        Cbperipheralmanagerstatepoweredon:        {            [self setupservice];        }            break;                    Default:        {            NSLog (@ "Peripheral Manager did change State");        }            break;    }}

When it is possible to find Bluetooth on the peripherals, it is necessary to prepare the services and features that you need to broadcast to other central devices, which are implemented by calling the Setupservice method.
Each service and feature needs to be identified with a UUID (unique identifier), and the UUID is a 16bit or 128bit value. If you want to create your central-peripheral app, you need to create your own 128bit uuid. You have to be sure that your own UUID cannot conflict with other services that already exist. If you are about to create your own device, you need to implement the UUID of the standard committee needs; If you just create a central-peripheral app, I suggest you turn on Mac OS x Terminal.app and generate a 128bit uuid with the Uuidgen command. You should use the command two times to generate two uuid, one for the service and one for the feature. Then, you need to add them to the central and peripheral apps. Now, before the implementation of the view controller, we add the following code:

Static NSString * Const KSERVICEUUID = @ "1c85d7b7-17fa-4362-82cf-85dd0b76a9a5"; static NSString * const Kcharacteristicuuid = @ "7e887e40-95de-40d6-9aa0-36ede2bae253";

Here's the Setupservice method.

-(void) setupservice{    cbuuid *characteristicuuid = [Cbuuid uuidwithstring:kcharacteristicuuid];        Self.customcharacteristic = [[Cbmutablecharacteristic alloc] Initwithtype:characteristicuuid properties: Cbcharacteristicpropertynotify Value:nil permissions:cbattributepermissionsreadable];        Cbuuid *serviceuuid = [Cbuuid uuidwithstring:kserviceuuid];        Self.customservice = [[Cbmutableservice alloc] Initwithtype:serviceuuid Primary:yes];    [Self.customservice Setcharacteristics:@[self.customcharacteristic]];    [Self.peripheralmanager AddService:self.customService];       }

When the AddService method of Cbperipheralmanager is called, it responds to the Cbperipheralmanagerdelegate-(void) Peripheralmanager: ( Cbperipheralmanager *) Peripheral Didaddservice: (Cbservice *) Service error: (Nserror *) Error method. This is the time to start broadcasting the service we just created.

-(void) Peripheralmanager: (Cbperipheralmanager *) Peripheral Didaddservice: (Cbservice *) Service error: (Nserror *) error{    if (Error = = nil)    {        [Self.peripheralmanager startadvertising:@{Cbadvertisementdatalocalnamekey: @ "Icserver", Cbadvertisementdataserviceuuidskey: @[[cbuuid Uuidwithstring:kserviceuuid]]}];}    }

Of course, you have finished the Peripheralmanager work, the central equipment has been able to accept your service. But this is still data, you can also call-(BOOL) Updatevalue: (NSData *) value forcharacteristic: (cbmutablecharacteristic *) characteristic Onsubscribedcentrals: (Nsarray *) Centrals method can give the center a place to generate dynamic data.

-(void) Sendtosubscribers: (NSData *) Data {  if (self.peripheral.state! = Cbperipheralmanagerstatepoweredon) {    Lxcblog (@ "Sendtosubscribers:peripheral not ready for sending State:%d", self.peripheral.state);    return;  }  BOOL success = [Self.peripheral updatevalue:data                            forCharacteristic:self.characteristic                         Onsubscribedcentrals:nil];  if (!success) {    lxcblog (@ "Failed to send data, buffering data for retry once-ready.");    Self.pendingdata = data;    return;}  }

Central subscribes to the value of characteristic, and peripheral calls UpdateValue:forCharacteristic:onSubscribedCentrals when the value is updated: (nsarray*) Centrals go to the Centrals in the array to update the value corresponding to characteristic, after the update peripheral for each central go through the following proxy method

-(void) Peripheralmanager: (Cbperipheralmanager *) Peripheral Central: (Cbcentral *) Central Didsubscribetocharacteristic: (cbcharacteristic *) characteristic

Peripheral accepts a read or write request, it responds to the following two proxy methods

-(void) Peripheralmanager: (Cbperipheralmanager *) Peripheral didreceivereadrequest: (Cbattrequest *) request-(void) Peripheralmanager: (Cbperipheralmanager *) Peripheral didreceivewriterequests: (Nsarray *) Requests

So now peripheral is ready to be created.

Create a Central

Create the center and connect the perimeter
Now that we've got a perimeter, let's create our center. The center is the device that handles the data sent from the perimeter.

Self.manager = [[Cbcentralmanager alloc] initwithdelegate:self queue:dispatch_get_main_queue ()];

When Central manager is initialized, we check its status to check that the device running the app is BLE-enabled. To implement Cbcentralmanagerdelegate proxy methods:

-(void) Centralmanagerdidupdatestate: (Cbcentralmanager *) central{    switch (central.state)    {        case Cbcentralmanagerstatepoweredon:        {            [Self.manager scanforperipheralswithservices:@[[CBUUID UUIDWithString: Kserviceuuid]]                                                 options:@{cbcentralmanagerscanoptionallowduplicateskey: @YES}];        }            break;        Default:        {            NSLog (@ "Central Manager does Change State");        }            break;    }}

When the app's device is Bluetooth-enabled, you need to call the-(void) Scanforperipheralswithservices of the Cbcentralmanager instance: (Nsarray *) serviceuuids options: ( Nsdictionary *) The options method, which is used to find the peripheral of a specified service. Once a perimeter is found in the search, the central agent receives the following callback:

-(void) Centralmanager: (Cbcentralmanager *) Central diddiscoverperipheral: (cbperipheral *) Peripheral Advertisementdata: (nsdictionary *) advertisementdata RSSI: (NSNumber *) rssi{        nsstring *uuid = [ Peripheral.identifier uuidstring];    NSString *uuid1 = Cfbridgingrelease (cfuuidcreatestring (NULL, peripheral. UUID));    NSLog (@ "----found peripheral----%@%@", UUID,UUID1);    [Self.manager Stopscan];        if (self.peripheral! = peripheral)    {        self.peripheral = peripheral;        NSLog (@ "Connecting to peripheral%@", peripheral);        [Self.manager connectperipheral:peripheral Options:nil];    }

This time an accompanying broadcast data and signal quality (rssi-received Signal strength Indicator) were found around the perimeter. This is a cool parameter, knowing the signal quality, you can use it to judge the distance. Any broadcast, scanned response data is saved in Advertisementdata and can be accessed through cbadvertisementdata.
This time you can connect this peripheral device,

[Self.manager connectperipheral:peripheral Options:nil];

It responds to the following proxy methods,

-(void) Centralmanager: (Cbcentralmanager *) Central didconnectperipheral: (cbperipheral *) peripheral{    NSLog (@ "-- --Successfully connected peripherals----");    [Self.peripheral setdelegate:self];    [Self.peripheral discoverservices:@[[Cbuuid Uuidwithstring:kserviceuuid]];}

Access to the surrounding services
The Cbcentralmanagerdelegate proxy above returns the Cbperipheral instance, its-(void) Discoverservices: (Nsarray *) Serviceuuids method is to access the surrounding services, This method responds to the Cbperipheraldelegate method.

-(void) Peripheral: (cbperipheral *) aperipheral diddiscoverservices: (Nserror *) error{    NSLog (@ "---- Diddiscoverservices----error:%@ ", Error);    if (Error)    {        NSLog (@ "Error discovering service:%@", [Error localizeddescription]);        [self cleanup];        return;    }        For (Cbservice *service-aperipheral.services)    {        NSLog (@ "service found with UUID:%@", service. UUID);        if ([Service. UUID isequal:[cbuuid Uuidwithstring:kserviceuuid])        {            [self.peripheral discovercharacteristics:@[[ Cbuuid Uuidwithstring:kcharacteristicuuid],[cbuuid Uuidwithstring:kwrritecharacteristicuuid]] ForService:service] ;        }    }}

In the above method if there is no error, you can call the Discovercharacteristics method to request the perimeter to find the features listed in its service, it will respond to the following method

-(void) Peripheral: (cbperipheral *) Peripheral Diddiscovercharacteristicsforservice: (Cbservice *) Service error         :(Nserror *) error{if (error) {NSLog (@ "error discovering characteristic:%@", [Error localizeddescription]);    Return } if ([Service. UUID Isequal:[cbuuid Uuidwithstring:kserviceuuid]) {for (cbcharacteristic *characteristic in Service.character            Istics) {NSLog (@ "----diddiscovercharacteristicsforservice---%@", characteristic); if ([characteristic. UUID Isequal:[cbuuid Uuidwithstring:kcharacteristicuuid]) {[Peripheral Readvalueforcharacteris                Tic:characteristic];            [Peripheral Setnotifyvalue:yes forcharacteristic:characteristic]; } if ([characteristic. UUID Isequal:[cbuuid Uuidwithstring:kwrritecharacteristicuuid]) {writecharacteristic = Charact            eristic; }                    }    }}

This time peripheral can call two methods,
[Peripheral readvalueforcharacteristic:characteristic] This is read eigenvalues, will respond-(void) Peripheral: (Cbperipheral *) Peripheral Didupdatevalueforcharacteristic: (cbcharacteristic *) characteristic error: (Nserror *) error;

[Peripheral Setnotifyvalue:yes forcharacteristic:characteristic]; response-(void) Peripheral: (Cbperipheral *) Peripheral Didupdatenotificationstateforcharacteristic: (cbcharacteristic *) characteristic error: (Nserror *) error;

-(void) Peripheral: (cbperipheral *) Peripheral didupdatenotificationstateforcharacteristic: (CBCharacteristic *) Characteristic error: (Nserror *) error{if (error) {NSLog (@ "Error changing notification State:%@", Error.loc    Alizeddescription); }//Exits If it ' s not the transfer characteristic if ([characteristic. UUID Isequal:[cbuuid Uuidwithstring:kcharacteristicuuid]) {//Notification has started if (Characteris            tic.isnotifying) {NSLog (@ "Notification began on%@", characteristic);        [Peripheral readvalueforcharacteristic:characteristic]; } else {//Notification have stopped//So disconnect from the peripheral NSLog (@ "Noti  Fication stopped on%@.            Disconnecting ", characteristic);        [Self.manager cancelPeripheralConnection:self.peripheral]; }}}-(void) Peripheral: (cbperipheral *) Peripheral didupdatevalueforcharacteristic: (cbcharacteristic *) Characteristic ERROR: (Nserror *) error{NSLog (@ "----Value---%@", characteristic.value); if ([characteristic. UUID Isequal:[cbuuid Uuidwithstring:kcharacteristicuuid]] {if (writecharacteristic) {Byte A            Ckvalue[3] = {0}; Ackvalue[0] = 0xe0; ACKVALUE[1] = 0x00;            ACKVALUE[2] = ackvalue[0] + ackvalue[1];            NSData *data = [NSData datawithbytes:&ackvalue length:sizeof (ackvalue)];                                   [Self.peripheral writevalue:data forcharacteristic:writecharacteristic        Type:cbcharacteristicwritewithoutresponse]; }    }}

In the method above,-(void) WriteValue: (NSData *) data forcharacteristic: (cbcharacteristic *) characteristic type: ( Cbcharacteristicwritetype) Type is a method of writing data to a peripheral device, and it responds to the following method

-(void) Peripheral: (cbperipheral *) Peripheral didwritevalueforcharacteristic: (cbcharacteristic *) characteristic Error: (Nserror *) error{    NSLog (@ "---didwritevalueforcharacteristic-----");    if ([characteristic. UUID isequal:[cbuuid Uuidwithstring:kwrritecharacteristicuuid])    {        NSLog (@ "----value update----");}    }

In this way, the central device also realizes the function of reading and writing data.

In addition, GitHub has a packaged third-party open-source Bluetooth framework with the address Kickingvegas/ymscorebluetooth

iOS Bluetooth 4.0 Protocol Brief Introduction

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.