IOS Core Bluetooth是based on BLE(Bluetooth low energy) protocol
Major players in Bluetooth communication:
A central typically uses the information served up by peripherals to accomplish some particular task
A peripheral typically has data that is needed by other devices
Data structure on Peripheral:
A service is a collection of data and associated behaviors for accomplishing a function or feature of a device (or portions of that device).
Note: Services themselves are made up of either characteristics or included services (that is, references to other services).
A characteristic provides further details about a peripheral’s service.
The way that central and peripheral communicate:
After a central has successfully established a connection to a peripheral, it can discover the full range of services and characteristics the peripheral has to offer (advertising data might contain only a fraction of the available services).
A central can also interact with a peripheral’s service by reading or writing the value of that service’s characteristic. For example, your app may request the current room temperature from a digital thermostat, or it may provide the thermostat with a value at which to set the room’s temperature.
centralManager = CBCentralManager(delegate: self, queue: DispatchQueue.main, options: [CBCentralManagerOptionShowPowerAlertKey: false])
(p.s. 藍芽狀態可能是: On/Off/resetting/unauthorized/unknown/unsupported)
centralManager?.scanForPeripherals(withServices: nil, options:[CBCentralManagerScanOptionAllowDuplicatesKey: true])
centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber)
centralManager.connect(peripheral, options: nil)
- 通知連到指定的peripheral: func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral)
- 尋找指定的service: peripheral.discoverServices([CBUUID(string: BluetoothConstants.service_uuid)])
func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?)
peripheral.discoverCharacteristics(nil, for: service)
func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?)
peripheral.setNotifyValue(true, for: characteristic)
Note: the peripheral then calls the peripheral(_:didUpdateValueFor:error:) method of its delegate object whenever the characteristic value changes 補充 1: CBCharacteristicProperties: read/write/writeWithoutResponse/notify/… 補充 2: https://www.oreilly.com/library/view/getting-started-with/9781491900550/ch04.html
func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?)
peripheral.writeValue(dataVal, for: characteristic, type: CBCharacteristicWriteType.withResponse)
func peripheral(CBPeripheral, didWriteValueFor: CBCharacteristic, error: Error?)