Core Bluetooth Programming guiding-performing Common Central Role Tasks in bold translation

Source: Internet
Author: User

Partial translation of Corebluetooth perform common central tasks

A device that acts as a central role and follows the BLE communication can perform a series of common tasks-for example, discovering and connecting the available peripherals, exploring and interacting with the data provided by the peripheral. A device that acts as a peripheral role can perform some column tasks, but the task content is different from central, or even vice versa-for example, publishing and advertising services, the corresponding external read and write operations, have been subscribed from the connected central

In this section you will learn how to use the Core Bluetooth framework to perform some of the most common ble tasks on the central side. The code-based examples in this post will help you implement the local central side of your app. Specifically, you will learn to:

    • Start a central Manager object
    • Find and connect to a peripheral device that is advertising
    • Search for data on connected peripheral devices
    • A read-write request that sends a corresponding characteristic value to a service of peripheral
    • Subscribe to a characteristic value to alert when value is updated

In the next section, you will learn how to implement the local peripheral when developing your app.

The sample code you find in this section is simple and abstract; You may need to make some changes to your app before incorporating it into your own. More about achieving central-including tips, tricks, and best practices--will be in the back of the Core Bluetooth Background processing for IOS Apps and best Pra Ctices for interacting with a Remote peripheral device

Start a central Manager

InitWithDelegate:queue:options:

Queue: If nil, the default is added to the primary queue

When you create a central manager, it calls the methods in your proxy:

Centralmanagerdidupdatestate:

This method must be implemented to ensure that the current device can support ble

Content for more agents: Cbcentralmanagerdelegate Protocol Reference

Find peripheral devices that are advertising

Scanforperipheralswithservieces:options:

If the first parameter is set to nil, the central manager calling the method will return all detected peripheral devices regardless of support services

In a real app, it is common to pass an array containing a specific Cbuuid object to the first parameter, each of which represents an ad-peripheral device.

Scanforperipheralswithservieces:options is called: after each discovery of a peripheral, central manager calls the Centralmanager in its proxy: DidDiscoverPeripheral:advertisementData:RSSI: Method. Each detected peripheral device is returned with the Cbperipheral object. Following the Proxy method implementation you will get a list of detected peripheral devices:

- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral      advertisementData:(NSDictionary *)advertisementData                            RSSI:(NSNumber *)RSSI {     NSLog(@"Discovered %@", peripheral.name);    ...

When you find the peripheral device you need to find, stop scanning other devices to save power

[myCentralManager stopScan];NSLog(@"Scanning stopped");
Connect a detected peripheral device

Call the Connectperipheral:option: Method in the Cbcentralmanager class to send a connection request to the specific peripheral device you detected

  [myCentralManager connectPeripheral:peripheral options:nil];

Assuming you are successfully connected, central manager invokes the method in the proxy: centralmanger:didconnectperipheral, so you can intuitively know that the connection has been successfully established.

- (void)centralManager:(CBCentralManager *)central    didConnectPeripheral:(CBPeripheral *)peripheral {     NSLog(@"Peripheral connected");    ...

Before interacting with the peripheral, set the peripheral agent to receive the callback normally again.

 peripheral.delegate = self;
Obtaining services for peripheral on a connection

Once you have established a connection with a peripheral, you can explore the data provided by the device. The first step in exploring is to retrieve all of the services available in this peripheral. There is a size limit to the amount of data a peripheral can advertise, so you may find that the services that your connection peripheral can retrieve are more than this peripheral ad data. You can do this by implementing a method in the Cbperipheral class: Discoverservices: To get all the services that a peripheral provides, like this

  [peripheral discoverServices:nil];

Note: In general, a nil is not passed as a parameter in a real app, as this returns all of the peripheral's service. A peripheral may contain far more services than you want, and retrieving all of the services is likely to deplete battery life and waste unnecessary time. Identify the UUID of the services you are interested in, Explore a peripheral ' s Data wisely refer to these

When the specified services are found, peripheral (the Cbperipheral object you are connecting to) calls the peripheral:diddiscoverservices in the proxy: method. Core Bluetooth creates an array of elements that are all Cbservice objects--every service is found in peripheral. You can implement this proxy method to get the array that contains the found services:

- (void)peripheral:(CBPeripheral *)peripheraldidDiscoverServices:(NSError *)error {     for (CBService *service in peripheral.services) {        NSLog(@"Discovered service %@", service);        ...    }    ...
Retrieving the characteristics in a service

Now if you have successfully retrieved the service you want (or that you are interested in) from the connected peripheral, the next step is to retrieve the characteristics that you want in the service (which you are interested in). Retrieve all the characteristics in a service as long as you simply call Discovercharacteristics:forservice in the Cbperipheral class:

NSLog(@"Discovering characteristics for service %@", interestingService);[peripheral discoverCharacteristics:nil forService:interestingService];

Note: In a real app, a nil is normally not passed as the value of the first parameter, because it returns all the characteristics of a peripheral service. In addition to the few characteristics you are interested in, a peripheral service must have something else to find all the characteristic to lose battery life and waste time. So when discovering characteristics, it's a good idea to specify the UUID of the characteristics you're interested in.

When characteristics is found in the specified services, peripheral invokes the Proxy method: Peripheral:didDiscoverCharacteristicsForServices:error:, C Ore Bluetooth creates an array of elements that are all cbcharacteristic objects-each one is found characteristic. The following example simply tells you how to show the characteristics you have found:

- (void)peripheral:(CBPeripheral *)peripheraldidDiscoverCharacteristicsForService:(CBService *)service             error:(NSError *)error {     for (CBCharacteristic *characteristic in service.characteristics) {        NSLog(@"Discovered characteristic %@", characteristic);        ...    }    ...
Retrieving the value of a characteristic

A characteristic contains details about a service that represents peripheral. For example, the temperature measurement of a temperature-sensing service characteristic is likely to contain a value that represents the Celsius temperature. You can retrieve its value by reading directly a characteristic or subscribing to it.

Read the value of the characteristic

When you find the characteristic of the service you are interested in, you can read the value of characteristic by calling the Readvalueforcharacteristic: Method of the Cbperipheral class. Remember to specify characteristic:

NSLog(@"Reading value for characteristic %@", interestingCharacteristic);[peripheral readValueForCharacteristic:interestingCharacteristic];

When you try to read a characteristic value, peripheral also calls its Proxy method peripheral:didUpdateValueForCharacteristic:error to retrieve the data. If the value is successfully retrieved, you can get the value directly from the characteristic Value property:

- (void)peripheral:(CBPeripheral *)peripheraldidUpdateValueForCharacteristic:(CBCharacteristic *)characteristic             error:(NSError *)error {     NSData *data = characteristic.value;    // parse the data as needed    ...

Note: There is no guarantee that all characteristic will have a readable value. You can determine the readability of a characteristic value by Cbcharacteristicpropertyread this constant, as described in Cbcharacteristic Class Reference. If you want to read a non-readable value, then the proxy method Peripheral:didUpdateValueForCharacteristic:error: Returns a corresponding error

Subscribe to a characteristic value

Although it is possible to read the value of characteristic in some cases by using Readvalueforcharacteristic: The method is not the most effective when the release of a duty changes. For most numeric changes-for example, your heartbeat rate at any given moment-you should retrieve them by subscribing. Subscribed to a characteristic value, you will receive a notification from peripheral as long as this value changes

You can call the Cbperipheral class's setnotifyvalue:forcharacteristic: method to subscribe to the Value of the characteristic you are interested in. Specifies that the value of the first parameter is YES:

[peripheral setNotifyValue:YES forCharacteristic:interestingCharacteristic];

When you try to subscribe (or unsubscribe) a characteristic Value, peripheral calls the Proxy method: peripheral: Didupdatenotificationstateforcharacteristic:error:. If the subscription request fails, you can implement this method to get the cause of the failure (error type), such as the following example:

- (void)peripheral:(CBPeripheral *)peripheraldidUpdateNotificationStateForCharacteristic:(CBCharacteristic *)characteristic             error:(NSError *)error {     if (error) {        NSLog(@"Error changing notification state: %@",           [error localizedDescription]);    }    ...

Note: Not all characteristic will allow values to be subscribed to. You can use the enumeration: characteristic Properties to get the relevant constants to determine whether a characteristic value can be subscribed

Once you have successfully subscribed to a characteristic value, the peripheral device notifies you of the app once the values are changed. Each time the value is changed, peripheral invokes the proxy method Peripheral:didupdateva Lueforcharacteristic:error:. To retrieve the updated value, you can implement the method mentioned in the value above to read characteristic.

Writes the Value of a characteristic

In some cases, it is meaningful to write a value to a characteristic. For example, if your app interacts with an electronic thermostat that supports BLE, you want to set a value for your room temperature for constant stability. If the value of a characteristic is writable, you can write some data (the NSData instance object) by calling the WriteValue:forCharacteristic:type: Method of the Cbperipheral class, as in:

NSLog(@"Writing value for characteristic %@", interestingCharacteristic);[peripheral writeValue:dataToWrite forCharacteristic:interestingCharacteristic        type:CBCharacteristicWriteWithResponse];

When you try to write a characteristic value, you need to specify the type you write, in this example, the write type is specified as Cbcharacteristicwritewithresponse, which represents peripheral Allows your app to learn if the write was successful. For information about other write types provided by the Core Bluetooth framework, see Cbcharacteristicwritetype enumeration in Cbperipheral Class Reference

Peripheral invokes the Peripheral:didWriteValueForCharacteristic:error in the proxy method: and specifies cbcharacteristicwritewithresponse to respond to the write operation. If the write fails, you can implement the following proxy method to get the error:

- (void)peripheral:(CBPeripheral *)peripheraldidWriteValueForCharacteristic:(CBCharacteristic *)characteristic             error:(NSError *)error {     if (error) {        NSLog(@"Error writing characteristic value: %@",            [error localizedDescription]);    }    ...

Note: Characteristics may only allow a specific type of write to write to its value. To determine whether the current type is allowed to write to the value of the current characteristic, refer to the related property in the characteristic properties enumeration in Cbcharacteristic Class Reference.

Core Bluetooth Programming guiding-performing Common Central Role Tasks in bold translation

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.