Bluetooth Basics
Bluetooth library
In the current iOS bluetooth development is a system used to own bluetooth library < > CoreBluetooth/CoreBluetooth. H
Bluetooth device version requirements
Bluetooth devices must be 4.0 or above
The core of the CoreBluetooth framework
The core in the CoreBluetooth framework is the Peripheral and central, which represent the center and the center respectively. On the device, the phone can be considered as the center and the Bluetooth device as the peripheral
Services and Features
Bluetooth device has a number of services, each service contains a number of characteristics, features are to provide data
Relationships among peripherals, services, and features
The architecture of CoreBluetooth framework
The specific implementation of bluetooth connection
The implementation process
Scan peripherals 3. Connect peripherals 4. Obtain services and features of peripherals 5. Interact with peripherals
Implementation steps
1. Import the CoreBluetooth header file, add the proxy, and establish the central role
#import <CoreBluetooth/CoreBluetooth.h>
@interface ViewController : UIViewController<CBCentralManagerDelegate.CBPeripheralDelegate>
@property (strong.nonatomic) CBCentralManager *centralManager; // Bluetooth manager
@property(strong.nonatomic)CBPeripheral *peripheral; // Store the peripherals that matched successfully- (void)viewDidLoad {
[super viewDidLoad];
// The last thread argument can be nil, default is main thread
self.centralManager = [[CBCentralManager alloc] initWithDelegate:self queue:dispatch_get_main_queue()];
}
Copy the code
2. Scan peripherals
2. Must implement proxy, return centralManager state 3. You can only start scanning peripherals */ if the state is CBManagerStatePoweredOn- (void)centralManagerDidUpdateState:(CBCentralManager *)central {
switch (central.state) {
case CBManagerStateUnknown:
NSLog(Unknown "@" > > >);
break;
case CBManagerStateResetting:
NSLog("@" > > > reset);
break;
case CBManagerStateUnsupported:
NSLog(@">>> Device not supported");
break;
case CBManagerStateUnauthorized:
NSLog(@">>> Device not authorized");
break;
case CBManagerStatePoweredOff:
{
NSLog(@">>> Device shutdown");
self.bleStatusBlock(NO);
}
break;
case CBManagerStatePoweredOn:
{
NSLog(@">>> Device open");
// Start scanning peripherals, and then go to the didDiscoverPeripheral method
/* 1. Two arguments nil means all visible Bluetooth devices are scanned by default. 2. NSDictionary *options = [NSDictionary dictionaryWithObject:[NSNumber] the second parameter sets whether to repeat the scan of discovered devices numberWithBool:YES] forKey:CBCentralManagerScanOptionAllowDuplicatesKey]; The Bool value is Yes, indicating repeated scanning; otherwise, indicating no repeated scanning */
[self.centralManager scanForPeripheralsWithServices:nil options:nil];
}
break;
default:
break; }}Copy the code
Connecting peripherals
// Devices scanned can be printed in this method- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(nonnull CBPeripheral *)peripheral advertisementData:(nonnull NSDictionary<NSString *,id> *)advertisementData RSSI:(nonnull NSNumber *)RSSI {
NSLog(@">>>advertisementData :%@ name :%@ ",advertisementData,peripheral.name);
// Some products are paired according to the Mac address, here we can get, what is the specific rule, according to the bluetooth device
NSData *data = [advertisementData objectForKey:@"kCBAdvDataManufacturerData"];
/ / parsing
/ /...
if(Own judgment) {// The device found must hold it, otherwise the Peripheral will not be saved in CBCentralManager and the methods in CBPeripheralDelegate will not be called!!
self.peripheral = peripheral;
// Stop scanning
[self.centralManager stopScan];
// Connect peripherals
[_centralManager connectPeripheral:peripheral options:nil]; }}// Connect to Peripherals- successful
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral
{
NSLog(@">>> Connect to device named (%@) - success",peripheral.name);
}
// Connect to Peripherals- failed- (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
{
NSLog(@">>> Connect to device named (%@) - failed because :%@",[peripheral name],[error localizedDescription]);
}
// The Peripherals are disconnected
- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
{
NSLog(@">>> Peripheral connection disconnected %@: %@\n", [peripheral name], [error localizedDescription]);
}
Copy the code
Gets services and characteristics in peripherals
// The peripheral connection succeeded- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral {
NSLog(@">>> Connect to device named (%@) - success",peripheral.name);
peripheral.delegate=self;// This method calls the discovery service protocol
[peripheral discoverServices:nil];
}
// Services are detected- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error {
NSLog(>>> Service detected: %@,peripheral.services);
if (error) {
NSLog(@">>>Discovered services for %@ with error: %@", peripheral.name, [error localizedDescription]);
return;
}
for (CBService *service in [peripheral services]){
[peripheral discoverCharacteristics:nilforService:service]; }}// The signature is detected
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error {
if (error) {
NSLog(@"error Discovered characteristics for %@ with error: %@", service.UUID, [error localizedDescription]);
return;
}
for (CBCharacteristic *characteristic in service.characteristics) {
NSLog(>>> Service :%@,service.UUID,characteristic.UUID);
// Filter the UUID you need to connect
if([characteristic.UUID isEqual:yourUUID) {subscribe [peripheral setNotifyValue:YESforCharacteristic:characteristic]; }}}Copy the code
Read the data
// Get the data for the specified feature
- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
{
// Receive bluetooth data
NSLog(@"characteristic uuid:%@ value:%@",characteristic.UUID,characteristic.value);
}
Copy the code
Write data
// Write data- (void)writeData {
[self.peripheral writeValue:data forCharacteristic:self.characteristic type:CBCharacteristicWriteWithResponse];
}
// Write data callback
- (void)peripheral:(CBPeripheral *)peripheral didWriteValueForCharacteristic:(CBCharacteristic *)characteristic error:(nullable NSError *)error
{
if (error) {
NSLog(@"error Discovered characteristics for %@ with error: %@", characteristic.UUID, [error localizedDescription]);
return;
}
NSLog(@"characteristic uuid:%@ value:%@",characteristic.UUID,characteristic.value);
}
Copy the code
disconnect
- (void)disConnect{
[self.centralManager cancelPeripheralConnection:self.peripheral];
}
Copy the code