IOS BLE4.0 Bluetooth and Peripherals Connect and send and receive data flow

Source: Internet
Author: User
Tags call back

Objective:

Apple starts to support ble 4.0,iphone4s,ipod 5,ipad after iOS 6 system After the 3 model starts to embed BLE4.0 hardware, so before development, please confirm that your development environment meets the above requirements, and Apple after BLE4.0, the external connection device is no longer required MFI certification, of course, your peripherals must have Bluetooth 4.0 module

Review:

To develop the BLE4.0 app, you need to import the framework into your project:

Corebluetooth.framework

In the file you need to use to Bluetooth, you need to import the header file:

#import <CoreBluetooth/CoreBluetooth.h>

#import <CoreBluetooth/CBService.h>

And you need to implement two protocols in your Bluetooth class, cbcentralmanagerdelegate, Cbperipheraldelegate

Now we need to have two instance objects Cbcentralmanager and Cbperipheral, the first of which is the Bluetooth center manager, which is used primarily to search for peripherals, connect peripherals and handle disconnected peripherals, and the second is primarily for a series of actions after the Bluetooth hub manager successfully connects the peripherals. For example: Read Peripheral service number Cbservice, eigenvalue number cbcharacteristic and read and write to these eigenvalue numbers, and so on, let's take a look at the iOS side and peripherals online a general process:

1): iOS this way the Bluetooth center Manager starts scanning the broadcast packet (the length of the scan can write itself a timer control, and can set the specific conditions of the scan)

2): Peripheral start Broadcast (of course, the broadcast length of the peripheral can also be set, this is the hardware side of the matter, I do not understand)

3): iOS found a broadcast packet, on request to connect peripherals (this is the bottom of the automatic implementation, we do not need to write code), then the peripheral will receive the connection request, if the peripheral receives the connection request, will send a connection request to the iOS side of the confirmation package, when the iOS side received this package, On both sides of the device to complete the connection (of course, because the connection layer has been written, more complex, I speak relatively superficial, just a approximate step)

4): After the connection is successful, iOS will be able to read the peripheral information, such as service number Cbservice, eigenvalue number cbcharacteristic, and peripheral hardware information, battery charge, signal strength RSSI, etc.

5): Of course, in the normal connection of the process will always have a point of accident, if two devices suddenly broken off the connection, generally we still want them to be able to connect again, here will have to look at the hardware and iOS program in the connection to the disconnection of the processing code

6): Of course, the peripherals and iOS can also proactively initiate a disconnected request

Let's take a look at the specific code flow and basic meanings of iOS, you just have to follow my order, and the following sequence conforms to the iOS BLE4.0 online process:

In the initialization of your Bluetooth class, first instantiate the central Device Manager

_centralman = [[Cbcentralmanager alloc] initwithdelegate:self Queue:nil];

The code is very simple, only need a row on it, the main object is to set the delegate, as to whether to join a queue, it depends on your needs, remember our Bluetooth class inside inherited Cbcentralmanagerdelegate, Cbperipheraldelegate two protocols, you can follow up to see the protocol inside the method, I will not say, first of all, the first need to implement a protocol method

-(void) Centralmanagerdidupdatestate: (Cbcentralmanager *) Central

This method is mainly to check the status of the Bluetooth hardware of the iOS device, for example, your device does not support Bluetooth 4.0, or your device Bluetooth is not turned on, not authorized anything, usually you are sure that your iOS device Bluetooth is open, you should perform the scan action, [_ Centralman Scanforperipheralswithservices:nil Options:nil]; I remember that I did not check the status of Bluetooth scan directly, although the project can be run, but the console gives a lot of warning what, looking very annoying, then we perform the scanning action, if the scan to the peripheral, it will automatically callback the following protocol method

-(void) Centralmanager: (Cbcentralmanager *) Central diddiscoverperipheral: (cbperipheral *) Peripheral Advertisementdata: (nsdictionary *) advertisementdata Rssi: (NSNumber *) Rssi

The amount of information in this method is relatively large ah, look at that cbperipheral, you in this method you can already get its name can use Peripheral.name to get the name, of course, here can also get a broadcast name of the device NSString * Cbname=[advertisementdata Valueforkeypath:cbadvertisementdatalocalnamekey]; These two names are generally not the same, unless you have the hardware to write the same, of course, there are many other information, specific to the code bar, in this callback we can get the broadcast packet information of the peripheral, of course, we can according to broadcast packet information in accordance with the Protocol does not conform to your custom, Compliant, you can initiate a connection request, which avoids connecting to other peripherals that you do not want to connect to; Of course, you should have seen the value of a rssi here, which comes with a broadcast packet, which we can probably estimate how far away our iOS devices are in the broadcast device. If the signal is too weak and too far away, do we not consider connecting the peripheral; Here we assume that the broadcast packet data is eligible, and we initiate a connection request [_centralman connectperipheral:_peripheral Options:nil]; If the connection succeeds, the following protocol method will be recalled:

-(void) Centralmanager: (Cbcentralmanager *) Central didconnectperipheral: (cbperipheral *) Peripheral

If you can call back to the above method, indicating that you have successfully connected peripherals, specifically you can hit a breakpoint to try, since the connection has been successful, we should consider whether to stop the central management Device scanning action, or if you and already connected peripherals for data communication, If another peripheral is broadcasting and meets your connection criteria, your iOS device will also connect to the device (because iOS BLE4.0 supports one-to-many connections), causing confusion in the data.  So we stop the scanning action in this method: [_centralman Stopscan]; Now is the time to let our second instance of the cbperipheral out of the game, it should be noted here, remember to set cbperipheral delegate object _peripheral.delegate =self, in order to facilitate later use, We also read all the services of the peripherals at once Uuid:[_peripheral Discoverservices:nil]; so that once we read the associated service UUID to the peripheral, the following method is recalled:

-(void) Peripheral: (cbperipheral *) Peripheral diddiscoverservices: (Nserror *) error

Then in this method we can then peel, read a cbservice inside the eigenvalues uuid:[peripheral Discovercharacteristics:nil forservice:s]; ditto, If we successfully read a eigenvalues UUID, we will call back the following method:

-(void) Peripheral: (Cbperipheral *) Peripheraldiddiscovercharacteristicsforservice: (Cbservice *) Service error: ( Nserror *) Error

Can enter this method, you have read to a certain eigenvalue uuid, to get to this step, we basically completed the outer layer of delamination, followed by some of the read and write operation of a certain eigenvalue, of course, we first need to find the data we want to write the eigenvalues uuid, Here we can simply iterate through the loop to find a feature value UUID that the peripheral contains:

for (int i=0; i < Service.characteristics.count; i++) {

Cbcharacteristic *c = [SERVICE.CHARACTERISTICSOBJECTATINDEX:I];

if ([[[C UUID] isequal:[cbuuiduuidwithstring:@ "FFF1"]])

{//Your action}

}

Here we need to emphasize that since the eigenvalues UUID is set by the peripheral, and the properties of the eigenvalue uuid are many, such as read,writewithoutresponse,write,notify and so on, So you need to decide what to do with a certain eigenvalue uuid, depending on your agreement, and of course you can read it yourself. Properties of the eigenvalue uuid: c.properties, here we assume a eigenvalues uuid: "FFF1" The property is Writewithoutresponse, we write a data inside

Byte dataarr[2];

DATAARR[0]=0XAA; DATAARR[1]=0XBB;

NSData * MyData = [NSData Datawithbytes:dataarr length:2];

[_peripheral writevalue:mydata forcharacteristic:c Type:cbcharacteristicwritewithresponse];

This allows us to write the data to the peripherals once, but what if the characteristic uuid of the peripheral is read? For example, to get the battery level information of the peripheral (note: This belongs to the standard service inside), service uuid: "180F", eigenvalue uuid: "2a19", we can write:

[_peripheral READVALUEFORCHARACTERISTIC:CBC];

CBC refers to eigenvalues of "2a19" eigenvalue object, of course, the property is notify, and the method is similar to this: [Peripheralsetnotifyvalue:yes forcharacteristic:c];

Then we set to read the value of this eigenvalue object, how to receive the value it sent over, in fact, if the value of the object has been updated, it will automatically callback the following method:

-(void) Peripheral: (Cbperipheral *) peripheraldidupdatevalueforcharacteristic: (cbcharacteristic *) characteristic Error: (NSERROR *) error

In this callback function we can be based on the value of characteristic to determine which eigenvalue UUID sent over the value, the peripheral is mainly used to determine which peripheral sent the value, mainly used for Bluetooth one-to-many cases, if it is one-on, basic useless. So let's talk about how to output the received value, just to receive the battery charge, look at the code:

if ([[[Characteristic UUID] isequal:[cbuuid uuidwithstring:@ "2a19"]) {

Const unsigned char *hexbyteslight = [Characteristic.valuebytes];

NSString * battery = [nsstringstringwithformat:@ "%02x", Hexbyteslight[0]];

NSLog (@ "batteryinfo:%@", battery);

}

In fact, the peripheral to the iOS side of the data, will automatically callback the above method, so you receive the data sent by the peripheral, you can only in this method, through the different eigenvalues to determine which UUID sent over, parse out the data and then perform the corresponding action on it, Well, here we should be very clear about how iOS and peripherals communicate data, if you want to go deep on your own, of course, we finally say that if the connection of the two devices suddenly disconnected, the program will automatically callback the following method:

-(void) Centralmanager: (Cbcentralmanager *) Central diddisconnectperipheral: (cbperipheral *) Peripheral Error: ( Nserror *) Error

In this method, we can do some remedial measures, such as back-up, we can write in this method:

[_centralman connectperipheral:_peripheral Options:nil];

From this method, We can also output the connection disconnect reason: We write: Error.code, follow-up to see the cause of the error can be found in many ways, such as Cberrorconnectiontimeout,cberroroperationcancelled,cberrorperipherald IsConnected, you can according to the wrong reason to carry out different actions, well, actually there are many callback methods, we can go to see the official Apple documents, here are only a few commonly used only, the level is limited, there is no place, also please testify! If you have any questions can add my qq:631965569, the best is to send mail to QQ mailbox!

The last two days wrote a Demo, put on GitHub above, address is: https://github.com/Allen-L/BLE4.0-Demo-IOS.git, imitate LightBlue write, for various reasons, did not write completely, can be used for reference, Reprint http://m.blog.csdn.net/blog/liang_ke_ke/39251951

IOS BLE4.0 Bluetooth and Peripherals Connect and send and receive data flow

Related Article

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.