At the beginning

  • This is a sub-chapter. For the whole article, see the Learning Diary of Zero-based iOS development

BabyBluetooth

Bluetooth Development Steps

  1. Scanning peripherals
  2. Find a peripheral
  3. Connecting peripherals
  4. Get read and write features of peripherals
  5. Gets and sends messages to peripherals
  • Based on the above steps, it is implemented through the block function
  • Bluetooth Bluetooth

The basic use

  • Here’s a case of my recent Bluetooth project throughtableViewDisplay the devices that are scanned. The central device is connected to a Bluetooth device to send data by writing characteristic values and monitor messages by listening characteristic values
  • Create the baby object
self.baby = [BabyBluetooth shareBabyBluetooth];
Copy the code
  • Start scanning
self.baby.scanForPeripherals().begin();
Copy the code
  • Connected devices
[self.baby cancelScan]; / / cancel all of the peripherals connect [self. Baby cancelAllPeripheralsConnection]; // Establish connections and discover services and eigenvalues //pp as target peripherals self.baby.having(pp).and.then.connectToPeripherals().discoverServices().discoverCharacteristics().readValueForCharacteri stic().discoverDescriptorsForCharacteristic().readValueForDescriptors().begin();Copy the code
  • To send data
/ / by the connected peripherals call [self. ConnectPeripheral writeValue: data forCharacteristic: self. WriteCharacteristic type:CBCharacteristicWriteWithResponse];Copy the code
  • To initialize the baby object, set the corresponding block function
[self babyDelegate];
Copy the code
  • In babyDelegate, configure blocks
WeakSelf = self; weakSelf = self; weakSelf = self; / / determine whether the center device status can scan [self. The baby setBlockOnCentralManagerDidUpdateState: ^ (CBCentralManager * central) {if (the central state = = CBManagerStatePoweredOn) {[SVProgressHUD showInfoWithStatus:@" Device opened successfully, scan device "];} NSLog(@"%@", central);}]; // Scan the peripheral blCOK and add it to an array, In the subsequent processing to [self. Baby setBlockOnDiscoverToPeripherals: ^ (CBCentralManager * central and peripheral CBPeripheral *, NSDictionary *advertisementData, NSNumber * RSSI) {/ / NSLog (@ "search the device: % @", peripheral, name); the if (! [weakSelf. PeripheralArray containsObject: peripheral]) { [weakSelf. PeripheralArray addObject: Peripheral]; // Through the proxy, Weakself. delegate respondsToSelector:@selector(reloadData)]) {[weakself. delegate reloadData];}} NSLog(@"%@", weakSelf.peripheralArray); }]; [self.baby setBlockOnConnected:^(CBCentralManager *central, CBPeripheral * peripheral) {[SVProgressHUD showInfoWithStatus: @ "connection is successful"]; / / keep connected peripherals weakSelf connectPeripheral = peripheral; }]; / / read all the eigenvalues [self. Baby setBlockOnReadValueForCharacteristic: ^ (CBPeripheral * peripheral, CBCharacteristic *characteristics, NSError *error) { NSLog(@"characteristic name:%@ value is:%@",characteristics.UUID,characteristics.value); }]; // Get read and listen eigenvalues, According to the service to filter [self. Baby setBlockOnDiscoverCharacteristics: ^ (CBPeripheral * peripheral, CBService * service, NSError *error) { NSLog(@"service name: %@", service); NSLog(@"service uuidstring name: %@", service.UUID.UUIDString); NSLog(@"%@", If ([service.uuid.UUIDString isEqualToString:@" 6e400001-b5A3-f393-e0a9-e50e24dcca9e "]) {if([service.uuid.  for (CBCharacteristic * tempChara in service.characteristics) { NSLog(@"%@", TempChara); / / to monitor eigenvalue if ([tempChara. UUID. UUIDString isEqualToString: @ "6 e400003 - B5A3 - F393 - E0A9 - E50E24DCCA9E"]) { weakSelf.notifyCharacteristic = tempChara; NSLog(@"self.notifyCharacteristic : % @ ", weakSelf. NotifyCharacteristic); / / to subscribe to monitor characteristic value, To process the data and will listen to [weakSelf. Notify baby: peripheral characteristic: weakSelf. NotifyCharacteristic block: ^ (CBPeripheral *peripheral, CBCharacteristic *characteristics, NSError *error) { NSLog(@"notify %@", characteristics.value); NSLog(@"notify Str %@", [[nsstrings alloc] initWithData: characteristics. The value encoding: NSUTF8StringEncoding]); / / processing data [weakSelf The handleData: characteristics. The value];}];} / write/save eigenvalue else if ([tempChara. UUID. UUIDString isEqualToString:@"6E400002-B5A3-F393-E0A9-E50E24DCCA9E"]) { weakSelf.writeCharacteristic = tempChara; NSLog(@"self.writeCharacteristic : %@", weakSelf.writeCharacteristic); } } } }]; / / set up the lookup equipment filter [self. Baby setFilterOnDiscoverPeripherals: ^ BOOL (peripheralName nsstrings * and * advertisementData NSDictionary, NSNumber *RSSI) {if ([peripheralName hasPrefix:@"Pxxxx"]) {// return YES; //} // return NO; // if ([peripheralName hasPrefix:@"Pxxxx"]) {// return NO; // NSData *data = advertisementData[@""]; // NSLog(@"%@", advertisementData);  the search rule is peripheral.name length > 0 if (peripheralName.length >0) { return YES; } return NO; }]; / / write success [self. Baby setBlockOnDidWriteValueForCharacteristic: ^ (CBCharacteristic * characteristic, NSError *error) {dismissWithDelay:1]; // Disconnect device [self.baby setBlockOnDisconnect:^(CBCentralManager *central, CBPeripheral * Peripheral, NSError *error) {[SVProgressHUD showInfoWithStatus:@"; [SVProgressHUD showInfoWithStatus:@"]; [SVProgressHUD dismissWithDelay:1] ([weakSelf.delegate respondsToSelector:@selector(disconnect)]) { [weakSelf.delegate disconnect]; } }]; / / cancel all devices connected [self. Baby setBlockOnCancelAllPeripheralsConnectionBlock: ^ (CBCentralManager * centralManager) { NSLog(@"setBlockOnCancelAllPeripheralsConnectionBlock"); }]; / / cancel scan [self. Baby setBlockOnCancelScanBlock: ^ (CBCentralManager * centralManager) {NSLog (@ "setBlockOnCancelScanBlock"); }]; / / set babyOptions / / scanning options - > CBCentralManagerScanOptionAllowDuplicatesKey: ignore the same Peripheral end found multiple events are aggregated into a found NSDictionary *scanForPeripheralsWithOptions = @{CBCentralManagerScanOptionAllowDuplicatesKey:@YES}; / * connection option - > CBConnectPeripheralOptionNotifyOnConnectionKey: when applications pending, if there is a connection is successful, if we want to system for the specified peripheral displays a prompt, using the key value. CBConnectPeripheralOptionNotifyOnDisconnectionKey: when applications pending, if the connection is disconnected, if we want the system for the specified peripheral shows a disconnected when prompted, use the key values. CBConnectPeripheralOptionNotifyOnNotificationKey: When the application is suspended, Use this key to display a mention */ NSDictionary *connectOptions = whenever a notification is received on the given Peripheral @{CBConnectPeripheralOptionNotifyOnConnectionKey:@YES, CBConnectPeripheralOptionNotifyOnDisconnectionKey:@YES, CBConnectPeripheralOptionNotifyOnNotificationKey:@YES}; / / connected devices - > [self. Baby setBabyOptionsWithScanForPeripheralsWithOptions: scanForPeripheralsWithOptions connectPeripheralWithOptions:connectOptions scanForPeripheralsWithServices:nil discoverWithServices:nil discoverWithCharacteristics:nil];Copy the code

Data conversion

  • For Bluetooth peripherals, the general data is hexadecimal, so it involves the conversion of data format. For iOS, the convenient data format must be data, which can be processed differently according to the frame structure
  • Every element in this array is stored as an NSNumber
  • NSArray to NSData
- (NSData *)convertArrayToDataWithArray:(NSArray *)array {
    NSUInteger len = array.count;
    UInt8 buffer[len];
    for (int i = 0; i < len; i++)
    {
        buffer[i] = [[array objectAtIndex:i] unsignedCharValue];
    }
    NSData *data = [NSData dataWithBytes:buffer length:len];
    return data;
}
Copy the code
  • Turn NSData NSArray
- (NSArray *) convertDataToArrayWithData: (NSData *) data {/ / make a copy of data is read NSData * recvBuffer = [NSData dataWithData: data]; NSUInteger recvLen = [recvBuffer length]; UInt8 *recv = (UInt8 *)[recvBuffer bytes]; if (recvLen > 1000) { return nil; RecvData = [[NSMutableArray alloc] init]; NSUInteger j = 0; while (j < recvLen) { [recvData addObject:[NSNumber numberWithUnsignedChar:recv[j]]]; j++; } return recvData; }Copy the code
  • Adds the form of data to an array
[dataArr addObject:[NSNumber numberWithUnsignedInteger:0x00]];
Copy the code
  • The contents of an array are compared in hexadecimal terms
[dataArr[0] unsignedIntValue] == 0x81
Copy the code

conclusion

  • This is just a single device connection, it’s said that you can do multiple devices connection, looking for an opportunity to fill the hole
  • The above summary is only the states I used in the project, and I can also listen to a lot of Bluetooth states, so as to dig a hole
  • Specifically, it encapsulates a layer of Manager management class.