BabyBluetooth

repository·master·Indexed 26 days ago

https://github.com/coolnameismy/babybluetooth

A lightweight, open-source wrapper for Apple's CoreBluetooth framework designed to simplify BLE (Bluetooth Low Energy) development for iOS and macOS. It provides a block-based API and chainable methods to reduce boilerplate code for both Central Model (scanning for peripherals) and Peripheral Model (simulating a BLE device) implementations.

Tokens
2.3K
Snippets
5
Records
7
Agent score
39%

What's inside BabyBluetooth

  1. Install BabyBluetooth via CocoaPods

    master

    To install BabyBluetooth using CocoaPods, add the following line to your Podfile:

    pod 'BabyBluetooth','~> 0.6.0'

    After installing the pod, import the header file in your Objective-C files:

    #import "BabyBluetooth.h"
    pod 'BabyBluetooth','~> 0.6.0'
  2. Implement Peripheral Model (Simulating a BLE Device)

    master

    In Peripheral Model, your app simulates a BLE 4.0 peripheral that can be discovered and connected to by other devices.

    To implement this:

    1. Create services using makeCBService(UUIDString).
    2. Add characteristics to services using makeCharacteristicToService(service, UUIDString, permissions, value).
      • Permissions include: "r" (read), "w" (write), "rw" (read/write), "n" (notify).
      • Use genUUID() for automatic UUID generation.
      • Use makeStaticCharacteristicToService for characteristics with initial values (read-only).
    3. Initialize BabyBluetooth.
    4. Set up peripheral delegate blocks (e.g., peripheralModelBlockOnPeripheralManagerDidUpdateState, peripheralModelBlockOnDidStartAdvertising, peripheralModelBlockOnDidAddService).
    5. Start advertising with baby.bePeripheral().addServices(@[services]).startAdvertising().

    Note: Use makeCBService and makeCharacteristicToService helper functions provided by the library to simplify service/characteristic construction.

  3. Install BabyBluetooth via CocoaPods or Manual Installation

    master

    You can install BabyBluetooth using CocoaPods or by manually adding the source files to your project.

    CocoaPods Installation

    Add the following line to your Podfile:

    pod 'BabyBluetooth','~> 0.7.0'

    Manual Installation

    1. Drag the files from the Classes/objc folder directly into your Xcode project.
    2. Import the header file in your implementation files:
    #import "BabyBluetooth.h"
  4. Implement Central Model (Scanning for Peripherals)

    master

    In Central Model, your app acts as the central device that connects to other BLE 4.0 peripherals.

    To implement this:

    1. Initialize BabyBluetooth using shareBabyBluetooth.
    2. Set up discovery blocks using setBlockOnDiscoverToPeripherals: to handle found devices.
    3. (Optional) Set a filter using setFilterOnDiscoverPeripherals: to only discover specific devices based on name or advertisement data.
    4. Start scanning with scanForPeripherals().begin().

    Note: You can start scanning immediately after setting up delegates without waiting for the CBCentralManagerStatePoweredOn state manually.

  5. Use BabyBluetooth in Peripheral Model (Mock a Peripheral)

    master

    To make your app act as a BLE 4.0 peripheral, use the bePeripheral() method. You can define services and characteristics using helper functions like makeCBService and makeCharacteristicToService.

    Key steps:

    1. Create CBMutableService objects.
    2. Add characteristics to services with specific properties (read r, write w, notify n, or read/write rw).
    3. Use makeStaticCharacteristicToService for characteristics with cached values.
    4. Initialize BabyBluetooth and set peripheral-specific blocks (e.g., peripheralModelBlockOnPeripheralManagerDidUpdateState:, peripheralModelBlockOnDidStartAdvertising:, peripheralModelBlockOnDidAddService:).
    5. Call baby.bePeripheral().addServices(@[services]).startAdvertising().
    #import "BabyBluetooth.h"
    BabyBluetooth *baby;
    
    -(void)viewDidLoad {
        [super viewDidLoad];
    
        //config first service
        CBMutableService *s1 = makeCBService(@"FFF0");
        //config s1's characteristic
        makeCharacteristicToService(s1, @"FFF1", @"r", @"hello1"); //can read
        makeCharacteristicToService(s1, @"FFF2", @"w", @"hello2"); //can write
        makeCharacteristicToService(s1, genUUID(), @"rw", @"hello3"); //can read,write,uuid be automatically generate
        makeCharacteristicToService(s1, @"FFF4", nil, @"hello4"); //default property is rw
        makeCharacteristicToService(s1, @"FFF5", @"n", @"hello5"); //can notiy
        
        //config seconed service s2
        CBMutableService *s2 = makeCBService(@"FFE0");
        //a static characteristic and has cached vuale, it must be only can read.
        makeStaticCharacteristicToService(s2, genUUID(), @"hello6", [@"a" dataUsingEncoding:NSUTF8StringEncoding]);
       
        //init BabyBluetooth
        baby = [BabyBluetooth shareBabyBluetooth];
        //config delegate
        [self babyDelegate];
        //let peripheral add services and start advertising
        baby.bePeripheral().addServices(@[s1,s2]).startAdvertising();
    }
    
    //set baby peripheral model delegate
    -(void)babyDelegate{
    
        [baby peripheralModelBlockOnPeripheralManagerDidUpdateState:^(CBPeripheralManager *peripheral) {
            NSLog(@"PeripheralManager trun status code: %ld", (long)peripheral.state);
        }];
        
        [baby peripheralModelBlockOnDidStartAdvertising:^(CBPeripheralManager *peripheral, NSError *error) {
            NSLog(@"didStartAdvertising !!!");
        }];
        
        [baby peripheralModelBlockOnDidAddService:^(CBPeripheralManager *peripheral, CBService *service, NSError *error) {
            NSLog(@"Did Add Service uuid: %@ ", service.UUID);
        }];
    }
  6. Use BabyBluetooth in Central Model (Scan for Peripherals)

    master

    To use your app as a Central to connect to BLE 4.0 peripherals, initialize BabyBluetooth using the shareBabyBluetooth singleton. You can use blocks instead of traditional delegates to handle discovery and filtering.

    Key steps:

    1. Initialize with [BabyBluetooth shareBabyBluetooth].
    2. Set a discovery block using setBlockOnDiscoverToPeripherals: to handle found devices.
    3. (Optional) Set a filter block using setFilterOnDiscoverPeripherals: to only accept specific devices based on name or advertisement data.
    4. Start scanning with baby.scanForPeripherals().begin().
    #import "BabyBluetooth.h"
    BabyBluetooth *baby;
    
    -(void)viewDidLoad {
        [super viewDidLoad];
    
        //init BabyBluetooth
        baby = [BabyBluetooth shareBabyBluetooth];
        //set delegate
        [self babyDelegate];
        //direct use, no longer wait for status Of CBCentralManagerStatePoweredOn
        baby.scanForPeripherals().begin();
    }
    
    //set babybluetooth delegate
    -(void)babyDelegate{
    
        //when scanfor perihphel
        [baby setBlockOnDiscoverToPeripherals:^(CBCentralManager *central, CBPeripheral *peripheral, NSDictionary *advertisementData, NSNumber *RSSI) {
            NSLog(@"搜索到了设备:%@",peripheral.name);
        }];
       
        //filter
        //discover peripherals filter
        [baby setFilterOnDiscoverPeripherals:^BOOL(NSString *peripheralName, NSDictionary *advertisementData, NSNumber *RSSI) {
            //设置查找规则是名称大于1
            if (peripheralName.length > 1) {
                return YES;
            }
            return NO;
        }];
    }