< iOS development; > Bluetooth usage

This article describes the simple use of Bluetooth

Bluetooth concept

For the traditional Bluetooth Bluetooth 2, Bluetooth clrm. Traditional Bluetooth
Bluetooth 4 because of low power consumption, low power consumption and therefore is also called the blue (BLE). It will be the three one set of specifications, including traditional Bluetooth technology, high technology and low energy technology.

Two.BLE supports two deployments

  1. Dual mode
    low-power Bluetooth classic Bluetooth controller integrated in existing, or increase the low power consumption in the current stack of Bluetooth chip, the overall structure is basically unchanged, so the cost increase is limited.
  2. Single mode
    for highly integrated and compact device, using a lightweight connection layer (Link Layer) operation, ultra low power standby mode simple equipment recovery and reliable point to multipoint data transmission, can make networked sensors arranged in the Bluetooth Bluetooth low power flow transmission in the order, as well as advanced energy saving and secure encrypted connections.

Three. Bluetooth version selection

  1. Bluetooth 2, no shelves,
    use private API, mobile phones need to jailbreak
  2. Bluetooth 2, to go on
    , MFI certification, use the ExternalAccessory framework. Mobile phones do not need to jailbreak
  3. Bluetooth 4, to
    , use the CoreBluetooth framework, the phone does not need to jailbreak (CoreBluetooth is based on BLE to develop)
  4. for small hardware vendors, MFI certification is not likely, not only the consumption of money is time-consuming, so, or recommend the use of Bluetooth 4.0.
    (MFI:Make for iPad, iPhone iTouch, specifically for Apple devices, production equipment)

Four. Problem description

The company asked iOS need and Piano and data communication of Bluetooth connection, I think the piano is Bluetooth 4, and then quickly integrate the CoreBluetooth framework to write a demo scan, peripherals, piano Bluetooth name not found, but iPhone open system settings, to find the piano corresponding asked colleagues Android Bluetooth. Learn the piano, only 2 of the Bluetooth module, so, An Zhuoduan is to interact with Bluetooth 2. The company decided not to do MFI certification, 4.0. in the process of dealing with the Bluetooth hardware vendors, that piano Bluetooth 4, however, when they are in the design of Bluetooth board, not integrated low power technology after the return, the board hardware manufacturers, add the BLE module. It embarked on a Bluetooth 4 track.

Five. Bluetooth 4 usage parsing

1. basic knowledge

Central: center, connecting hardware equipment.
peripheral: peripherals connected hardware.
: peripheral has been broadcast, when you create the object in the center of the scanning peripherals, you can find
peripherals. As shown in figure

< iOS development; > Bluetooth usage
center and peripheral diagram

Service Description: a peripheral comprises a plurality of services, each service also includes a number of features, including the feature description feature values and characteristics. Each service contains a plurality of fields, field permissions read (read), write (writing), notify (notice of

< iOS development; > Bluetooth usage,
devices, services, and feature diagrams
2. Bluetooth 4 is divided into two modes
  • Center mode flow establishing center role [[CBCentralManager alloc] initWithDelegate:self queue:nil] cancelPeripheralConnection found that peripheral didDiscoverPeripheral scan peripherals connect peripherals connectPeripheral
    4.1 didFailToConnectPeripheral
    4.2 connection failed to disconnect didDisconnectPeripheral
    4.3 connection didConnectPeripheral scan peripherals in the service discoverServices
    5.1 didDiscoverServices scan and obtain service service in the corresponding peripheral peripheral features of discoverCharacteristics
    6.1 and have access to peripherals the corresponding service features of didDiscoverCharacteristicsForService
    6.2 to the corresponding characteristics of write data writeValue:forCharacteristic:type: subscription notification feature setNotifyVa Lue:forCharacteristic:
    7.1 reads data based on characteristics didUpdateValueForCharacteristic
  • The peripheral mode flow establishes the peripheral roles, sets the services and features of the local peripherals, releases the peripherals and features the broadcast services, responds to the read and write requests of the response center, sends updated feature values to the subscriber Center

Six. Bluetooth 4 development steps

1. the central mode of
into the CoreBluetooth framework, #import < CoreBluetooth/CoreBluetooth.h>
2. CBPeripheralDelegate 3.
to comply with CBCentralManagerDelegate protocol to add attributes

Center Manager (Management / scanning equipment and connection) @property (nonatomic, strong) CBCentralManager *centralManager; / / storage device @property (nonatomic, strong) NSMutableArray *peripherals; / / scan to device @property (nonatomic, strong) CBPeripheral *cbPeripheral; / / text @property (weak, nonatomic) IBOutlet UITextView *peripheralText; / / @property status (nonatomic, assign) CBManagerState peripheralState;

Constants, specific services, and features are types of reading or writing, asking the company hardware manufacturer, or asking colleagues

4 / Bluetooth device name static NSString * const kBlePeripheralName = @ "company name Bluetooth hardware"; / / static NSString const notification service * kNotifyServerUUID = @ "FFE0"; / / static NSString const kWriteServerUUID writing service * @ = "FFE1"; / / notice eigenvalue NSString * static const kNotifyCharacteristicUUID = "FFE2"; / / @ write static NSString * const kWriteCharacteristicUUID eigenvalue = "@ FFE3";

4. create central managers

- (CBCentralManager *) centralManager {if ({_centralManager) {_centralManager = [[CBCentralManager alloc] initWithDelegate:self queue:nil]} return _centralManager}

Creating a storage device array

- (NSMutableArray *) peripherals {if ({_peripherals) {_peripherals = [NSMutableArray array]} return _peripherals}

The method of changing the central manager’s status is called before the 5. scan device

When the call / / status updates (if not collapse) - (void) centralManagerDidUpdateState: (CBCentralManager * central) {switch (central.state) {case CBManagerStateUnknown:{NSLog (@ "unknown"); self.peripheralState = central.state;} {NSLog break; case CBManagerStateResetting: (@ "reset"); self.peripheralState = central.state;} break; case CBManagerStateUnsupported: {NSLog (@ "without the support of the state"); self.peripheralState = central.state;} {NSLog break; case CBManagerStateUnauthorized: (@ "unauthorized"); self.per IpheralState = central.state;} {NSLog break; case CBManagerStatePoweredOff: (@ "closed"); self.peripheralState = central.state;} {NSLog break; case CBManagerStatePoweredOn: (@ "open - available"); self.peripheralState = central.state; break default: break;};}}

Scanning equipment

/ / scanning equipment - (IBAction) scanForPeripherals [self.centralManager NSLog ({stopScan]; @ "scanning equipment"); [self showMessage:@; if scanning device (self.peripheralState = = CBManagerStatePoweredOn) {/ / scan all equipment, incoming nil, on behalf of all scanForPeripheralsWithServices:nil equipment. [self.centralManager options:nil];}}

6. scan to the device and start the connection

@param advertisementData @param RSSI advertising equipment information signal strength / @param peripheral scan to scan to @param central / * * Equipment Management Center - (void) centralManager: (CBCentralManager * central) didDiscoverPeripheral: (CBPeripheral *) peripheral advertisementData: (NSDictionary< NSString id> * *, advertisementData) RSSI: (NSNumber *) RSSI showMessage:[NSString stringWithFormat:@ {[self "equipment, device name, peripheral.name]]; if:% @" ([self.peripherals! ContainsObject:peripheral]) {[self.peripherals addObject:peripheral]; NSLog (@ "% @", peripheral); if ([peripheral.name isEqualToString:kBlePeripheralName]) {[self showMessage:[NSString "stringWithFormat:@ device name:% @" Self.cbPeripheral, peripheral.name]]; [self = peripheral; showMessage:@; [self.centralManager "connection" connectPeripheral:peripheral options:nil];}}}

7., the three state of the connection. If the connection is successful, scan all services (or scan the specified service). The
connection failed to reconnect

@param central / * * connection failure management center @param error @param peripheral connection equipment failure error message * / - (void) centralManager: (CBCentralManager * central) didFailToConnectPeripheral: (CBPeripheral * peripheral) error: (NSError * error) {[self showMessage:@ "failed to connect"]; if ([peripheral.name isEqualToString:kBlePeripheralName]) {[self.centralManager connectPeripheral:peripheral options:nil]}};

Connection disconnect

@param error / * * disconnect the @param Central Center Manager @param peripheral connection disconnect error message * / - (void) centralManager: (CBCentralManager * central) didDisconnectPeripheral: (CBPeripheral * peripheral) error: (NSError * error) {[self showMessage:@] "disconnect"; if ([peripheral.name isEqualToString:kBlePeripheralName]) {[self.centralManager connectPeripheral:peripheral options:nil];}}

Connect successfully and scan service

@param central / * * connection center manager @param peripheral connection equipment - * / (void) centralManager: (CBCentralManager * central) didConnectPeripheral: (CBPeripheral * peripheral) {NSLog (@ "% @ connected devices: success", peripheral.name); [self showMessage:[NSString stringWithFormat:@ "connection device:% @ success", peripheral.name]]; / / peripheral.delegate = self agent set of equipment; / / services: nil service [peripheral scan all incoming discoverServices:nil];}

8. finds the service and scans the corresponding features of the service

Error scanning equipment @param service @param service peripheral / * * to scan the corresponding error message * / - (void) peripheral: (CBPeripheral * peripheral) didDiscoverServices: (NSError * error) {/ / traverse all service for (CBService *service in peripheral.services (NSLog) {@ "% @: service", service.UUID.UUIDString); / / get the corresponding service if ([service.UUID.UUIDString isEqualToString:kWriteServerUUID] || [service.UUID.UUIDString isEqualToString:kNotifyServerUUID]) {/ / to scan features of [peripheral discoverCharacteristics:nil forService:service]}}} according to the service;

9. scans the corresponding features, writes the values of the features, and subscribes the specified feature notifications

Scanning to the corresponding characteristics of @param / * * peripheral @param service equipment correspondence service @param error error message - (void) peripheral: * (CBPeripheral *) peripheral didDiscoverCharacteristicsForService: (CBService * service) error: (NSError * error) {/ / traversal of all the features of for (CBCharacteristic *characteristic in service.characteristics (NSLog) {@ "% @: characteristic value", characteristic.UUID.UUIDString); / / get the corresponding characteristics of if ([characteristic.UUID.UUIDString isEqualToString: kWriteCharacteristicUUID]) {/ / [self showMessage:@ write data write feature value] for (Byte; I = 0x0; I < 0x73; i++) {/ / let the piano every light a Byte byte[] = {0xf0, 0x3d, 0x3d, I, 0x02,0xf7}; NSData *data = [NSData dataWithBytes:byte length:6] [peripheral writeValue:data forCharacteristic:characteristic; type:CBCharacteristicWriteWithResponse] if;}} ([characteristic.UUID.UUIDString isEqualToString:kNotifyCharacteristicUUID]) {/ / [peripheral setNotifyValue:YES forCharacteristic:characteristic] subscription notification feature;}}}

10. read the data according to the characteristics

According to the characteristics of @param equipment @param characteristic / * * * / error error message read feature data @param to read peripheral data corresponding to the (void) - peripheral: (CBPeripheral *) peripheral didUpdateValueForCharacteristic: (nonnull CBCharacteristic * characteristic error: (nullable) NSError * error) {if ([characteristic.UUID.UUIDString isEqualToString:kNotifyCharacteristicUUID]) {NSData *data = characteristic.value NSLog (@ "% @";, data);}}

Read value print result:

2017-04-25 12:34:41.876974+0800 4.0Demo[1745:346611] < 9f5436> Bluetooth; Bluetooth 2017-04-25 12:34:41.983016+0800 4.0Demo[1745:346611] < 8f5440> 2017-04-25 12:34:42.154821+0800; 4.0Demo[1745:346611] < 9f5649> Bluetooth; Bluetooth 2017-04-25 12:34: 42.239481+0800 4.0Demo[1745:346611] < 8f5640>

Tip: Download LightBlue on Appstore and test for Bluetooth communication

GitHub: Bluetooth 4.0Demo

Bluetooth usage for CSDN:iOS development

If you have any help, please call it a favor. If there is any deficiency, please let me know…