• Train of thought

    CoreBluetooth, the communication method between mobile phones and devices, is relatively common and universal. There are a few things to be clear about in iOS development

    1. Bluetooth 4.0 can be connected to up to 7 devices, and bluetooth 4.0 is available on all iPhone6 and above
    2. The two iphones don’t search and pair directly with each other via Bluetooth
    3. Apple devices don’t support Bluetooth with other non-Apple devices, except, of course, bluetooth headsets and in-car Bluetooth
    4. The byte order of Bluetooth transmission is the little endian
    5. CoreBluetooth’s maximum transfer unit is 20 bytes

    Knowledge popularization:

    Byte order is only for built-in data types

    For example, a whole type (int, int is built-in data types), such as 0 x123456 big-end mode: high address -- -- -- -- -- -- -- -- -- -- > low address 0 x56 | 0 x34 | 0 x12 small side mode: High address -- -- -- -- -- -- -- -- -- -- > low address 0 x12 | 0 x34 | 0 x56Copy the code
  • process

    Take the central equipment as an example to analyze the whole process

    1. Instantiate the device manager of the center

    cManager = CBCentralManager(delegate: self, queue: nil)
    Copy the code

    2. The monitor status is PowOn, and search for nearby devices

    func centralManagerDidUpdateState(_ central: CBCentralManager) {
        if central.state == .poweredOn {
            scanForServices()
        } else {
            print("\(central.state)")
        }
    }
    Copy the code

    3. Discover peripherals, save and display them

    func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) { if let name = peripheral.name { if ! list.contains(name) { list.append(name) dict[name] = peripheral table.reloadData() } } }Copy the code

    4. Select a peripheral as required

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {if let pheral = dict[list[indepath.row]] {cManager? .connect(pheral, options: nil) } }Copy the code

    5. Connect to peripherals. If the connection fails or succeeds, scan for peripheral services

    func centralManager(_ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: Error?) Func centralManager(_ Central: CBCentralManager, didConnect Peripheral: CBPeripheral) {// Stop scanning central.stopscan () print(" peripheral = peripheral = peripheral ") peripheral. Delegate = self self Scanning a peripheral service peripheral. DiscoverServices ([CBUUID (string: "print")])}Copy the code

    6. Services are found in the callback

    func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) { var findService: CBService? for item in peripheral.services ?? [] {print(item.uuid) // If item.uuid. IsEqual (CBUUID(string: "Print")) {findService = item}} if let findService = findService {peripheral. DiscoverCharacteristics (nil, for: findService) } }Copy the code

    7. Query the following characteristics of the service, return then send print data in the callback

    func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) { for item in service.characteristics ?? [] { if item.uuid.isEqual(CBUUID(string: "Print")) {/ / read the success callback didUpdateValueForCharacteristic self. The characteristic = item / / receiving a (read the information or data is often receive real-time as the case may be, Before deciding which one to use) peripheral. ReadValue (item) that / / subscribe, real-time receive peripheral setNotifyValue (true, for: Let data = "the hardware engineer gave me the command, send the command to bluetooth, Bluetooth will return me a data. ". Data (using: .utf8) else { return } self.peripheral? .writeValue(data, for: item, type: WithResponse)} / / when found descriptor characteristic, the callback didDiscoverDescriptorsForCharacteristic peripheral.discoverDescriptors(for: item) } }Copy the code

    8. Read data from peripheral devices

    func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) Print ("\(String(describing: character.value))")}Copy the code

    9. The central device reads peripheral real-time data

    func peripheral(_ peripheral: CBPeripheral, didUpdateNotificationStateFor characteristic: CBCharacteristic, error: Error?) { if characteristic.isNotifying { peripheral.readValue(for: characteristic) } else { print("notification stoped on \(characteristic)") self.cManager? .cancelPeripheralConnection(peripheral) } }Copy the code
  • The end of the