"iOS Official Document Translator" iOS Bluetooth connection, data receive and send

Source: Internet
Author: User

Description: Some nouns are involved in Apple's official development documentation: Central (center device), peripheral (peripheral), Advertising (advertising), services (service), characteristic (features), etc., I translate in brackets in Chinese, and do not explain in detail, there may be misleading, please understand.


Directory:

Step 1: Create a central manager instance for Bluetooth management

Step 2: Search Peripheral devices

Step 3: Connect peripheral devices

Step 4: Access to peripheral equipment services

Step 5: Features of the Access service

Step 6. Read data from peripheral devices (two ways to read and subscribe directly)

Step 7: Send data to peripheral devices


Step one. Open Central Manager

Cbcentralmanager is a core Bluetooth object that represents a local hub device, and you must allocate memory and initialization to the Cbcentralmanager instance before using any Bluetooth transmission. You can pass the initWithDelegate:queue:options of the Cbcentralmanager class : method:

<p style= "margin-top:0px; margin-bottom:0px; font-size:18px; Font-family:courier; Color:rgb (102, 102, 102); -webkit-text-stroke-color:rgb (102, 102, 102); -webkit-text-stroke-width:initial; " >mycentralmanager = [[Cbcentralmanager alloc] initwithdelegate:self queue:nil options:nil];</p>

In this example, self is set to receive the agent for all events of the central device role, and when set dispatch queue is nil, central Manager handles these events through the main thread. Viewcontroller need to implement cbcentralmanagerdelegate,cbperipheraldelegate these two agents


when a central manager is created, it will callback the proxy's centralmanagerdidupdatestate: method, you must implement this proxy method to determine if the hub device supports BLE and is available .


Step two: Search for a peripheral device that is advertising


The first task of the central device is to search for peripherals that your app can connect to, as mentioned in the previous article, Advertising (advertising) is the primary method by which peripherals make it discoverable by peripheral devices, and you can Cbcentralmanager Class Scanforperipheralswithservices:options: method to search for any peripheral devices that are advertising:

[Mycentralmanager Scanforperipheralswithservices:nil Options:nil];

When you call the scanforperipheralswithservices:options: method to search for a peripheral device that you can connect to, Central manager will callback its proxy each time a peripheral device is searched. CentralManager:didDiscoverPeripheral:advertisementData:RSSI: method. Any peripheral devices that are searched are returned in the Cbperipheral class. Like the following code, you can implement this proxy method to list all the Bluetooth devices that are being searched:

-(void) Centralmanager: (Cbcentralmanager *) Central diddiscoverperipheral: (cbperipheral *) Peripheral     Advertisementdata: (nsdictionary *) Advertisementdata                  rssi: (NSNumber *) Rssi {     NSLog (@ "discovered%@", Peripheral.name);    ...

When you have found a peripheral device that you need to connect to, stop searching for other devices to save power.

[Mycentralmanager Stopscan]; NSLog (@ "scanning stopped");

Step three: Connect a peripheral device that you have searched for and want to connect

After you have searched for a peripheral device and it advertises the service you need, you can request and connect to this peripheral device by calling the Cbcentralmanager class of Connectperipheral:options: method, In short, call this method and describe the peripherals you need to connect to:

[Mycentralmanager connectperipheral:peripheral Options:nil];

Assuming the connection succeeds, Central manager will callback its proxy method centralmanager:didconnectperipheral: , you can implement this method to print "Peripheral connection":

-(void) Centralmanager: (Cbcentralmanager *) Central  didconnectperipheral: (cbperipheral *) Peripheral {     NSLog (@ "Peripheral connected");    ...

Before you start interacting with peripherals, you should set up a proxy for the perimeter to make sure it receives the appropriate callbacks, like this

Peripheral.delegate = self;

Step four: Search for the services of the peripherals you have connected to

After you have established a connection with the peripheral device, you can start surveying its data. The first step is to investigate what services the peripherals provide, because there is a size limit to the data on the perimeter, and you may find that the peripherals offer more services than it advertised. You can discover all the services that a peripheral provides by using the discoverservices: method of the Cbperipheral class:

[Peripheral Discoverservices:nil];


When a specific service is found, the perimeter device (the connected cbperipheral Class) will callback its proxy's peripheral:diddiscoverservices: method. Core Bluetooth builds array arrays of Cbservice classes-each service that stores peripherals. Like the following code, you can implement this proxy method to get a list of discovered services:

-(void) Peripheral: (Cbperipheral *) peripheraldiddiscoverservices: (Nserror *) error {for     (Cbservice *service in peripheral.services) {        NSLog (@ "discovered service%@", service);        ...    }    ...

Five. Features of the Search service

Assuming you have found the service you need, the next step is to explore all the "features" of the service (characteristics), searching for all the features of a service as long as the cbperipheral class is called Discovercharacteristics:forservice: methods, parameters for the specific service:

    NSLog (@ "Discovering Characteristics for service%@", interestingservice);    [Peripheral Discovercharacteristics:nil Forservice:interestingservice];

When the characteristics of the specified service are discovered, the perimeter device will callback the Peripheral:didDiscoverCharacteristicsForService:error: proxy method. Core Bluetooth sets up array arrays that store cbcharacteristic instances ——— each represents a discovered feature. The following example implements this proxy method to simply print each discovered feature:


-(void) Peripheral: (Cbperipheral *) Peripheraldiddiscovercharacteristicsforservice: (Cbservice *) Service             Error :(Nserror *) error {for     (cbcharacteristic *characteristic in service.characteristics) {        NSLog (@ "discovered Characteristic%@ ", characteristic);        ...    }    ...

Six. Get the value of the feature (that is, take data from the peripheral device)


A feature contains a simple value that represents the service of a peripheral device, for example, a health thermometer service that has a temperature measurement feature that has a value of Celsius, which you can read directly or subscribe to to obtain the corresponding value of this feature.


Directly read the value of a feature


After you get a feature of the service you want, you can read the value of this feature by calling the readvalueforcharacteristic: method of the Cbperipheral class, which is the feature that needs to be read:

  NSLog (@ "Reading value for characteristic%@", interestingcharacteristic);  [Peripheral readvalueforcharacteristic:interestingcharacteristic];

When you try to read a value that corresponds to a feature, the peripheral will callback its proxy method

Peripheral:didUpdateValueForCharacteristic:error: to fetch the value, if the value returns successfully, you can obtain it by using the Value property of the feature:

-(void) Peripheral: (Cbperipheral *) peripheraldidupdatevalueforcharacteristic: (cbcharacteristic *) characteristic             Error: (Nserror *) error {     NSData *data = characteristic.value;    Parse the data as needed ...    

Subscribe to the value of a feature


In some use cases, it is very efficient to read the value of a feature through readvalueforcharacteristic: But this is not the most efficient way to get a change in value, for most of the eigenvalue changes-for example, your heart rate at a given time, You should get it by subscribing to it. When you subscribe to the value of a feature, you can receive a notification when the value changes. You can subscribe to the features you need through the setnotifyvalue:forcharacteristic: method of the Cbperipheral class, the parameters are yes, and the features that need to be subscribed to:

[Peripheral Setnotifyvalue:yes forcharacteristic:interestingcharacteristic];

When you try to subscribe (or unsubscribe) a feature, the perimeter device calls its proxy's Peripheral:didUpdateNotificationStateForCharacteristic:error: method, If the subscription request fails, you can implement this method to get the wrong reason:

-(void) Peripheral: (Cbperipheral *) peripheraldidupdatenotificationstateforcharacteristic: (CBCharacteristic *) Characteristic             error: (Nserror *) Error {     if (error) {        NSLog (@ "Error changing notification State:%@",           [ Error localizeddescription]);    }    ...

When you successfully subscribe to a feature, the peripheral notifies your app when the value of the feature changes, each time the value changes, and the peripheral calls its agent's Peripheral:didUpdateValueForCharacteristic:error: Method. You can do this by implementing this method to get the value of the change, which is the same way as when you read the callback directly above.


Step Seven: Write the value into the feature (that is, send the data to the peripheral device)

In some use cases, it is possible to write data into a feature. For example, your app interacts with a BLE electronic temperature regulator, and you may need to give the regulator a value to set the temperature of the room, and if the value of the feature can be written, you can pass the writevalue of the cbperipheral class : Forcharacteristic:type: Method writes data (an instance of NSData) to the value of the feature:

NSLog (@ "Writing value for characteristic%@", interestingcharacteristic);    [Peripheral Writevalue:datatowrite forcharacteristic:interestingcharacteristic        Type: Cbcharacteristicwritewithresponse];

When you try to write the value of a feature, you need to explain what type of writing method you need to use. In the above example, the method for writing is Cbcharacteristicwritewithresponse, and in this way the peripherals will let your app know if the write operation was successful. For more ways to write, see the Cbcharacteristicwritetype enumeration inside cbperipheral Class Reference .


When writing data to peripherals using the cbcharacteristicwritewithresponse method, the peripheral:didwritevalueforcharacteristic of their agents is recalled : Error: method. If the write data fails, this method can be used to find the cause of the failure. Like this:


-(void) Peripheral: (Cbperipheral *) peripheraldidwritevalueforcharacteristic: (cbcharacteristic *) characteristic             Error: (Nserror *) Error {     if (error) {        NSLog (@ "Error writing characteristic value:%@",            [Error Localizeddescription]);    }    ...

simply write a test demo, see, the input box for the text to be sent, label for the received text, my Bluetooth test module is to return the data I sent.

This demo only connects Bluetooth devices with the specified Bluetooth name, and when testing, please put the tenth line Hmsoft instead of their own peripheral device name, this demo comparison of water, each viewdidload after the search for Bluetooth devices and connections, not easy to test, you can add breakpoints debugging.

In addition, because my test Bluetooth device does not support Cbcharacteristicwritewithresponse, send the data to return no permission error, so I use the Cbcharacteristicwritewithoutresponse. No callback Didwritevalueforcharacteristic method after success

Download Demo:https://github.com/dolacmeng/bluetooth













"iOS Official Document Translator" iOS Bluetooth connection, data receive and send

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.