Connect and read major value
suggest change- This example uses one Minew beacon that speaks the iBeacon protocol, in a room with no other beacons.
BLEControllermust adoptCBPeripheralDelegate.- After the scan stops, connect to the first peripheral that was found.
- Change
StopSearchBLE()as follows.bles.firstis optional, so connect only when a peripheral was found.
class BLEController: CBCentralManagerDelegate, CBPeripheralDelegate{
//...
func StopSearchBLE() {
let when = DispatchTime.now() + 5 // 5 is the delay in seconds
DispatchQueue.main.asyncAfter(deadline: when) {
self.cb_manager.stopScan()
if let peripheral = bles.first {
self.cb_manager.connect(peripheral)
}
}
}
// ...
}
- In the documentation for the BLE device, look up the service UUID and the major-value characteristic UUID.
var service_uuid = CBUUID(string: "0000fff0-0000-1000-8000-00805f9b34fb")
var major_uuid = CBUUID(string: "0000fff2-0000-1000-8000-00805f9b34fb")
func centralManager(_ central: CBCentralManager, didConnect peripheral:
CBPeripheral) {
peripheral.delegate = self
peripheral.discoverServices([service_uuid])
}
func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
print("Services: \(String(describing: peripheral.services))\n error: \(String(describing: error))")
peripheral.discoverCharacteristics([major_uuid], for: (peripheral.services?[0])!)
}
service_uuidandmajor_uuidabove use the Bluetooth base UUID.fff0is this device’s service, andfff2is its major characteristic. The leading0000pads that 16-bit ID into the 128-bit base UUID.discoverCharacteristics([major_uuid], for:)asks the GATT server for that characteristic. Its value is still nil until you read it. Force-unwrappingperipheral.services?[0]crashes whenservicesis nil or empty.
func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
for characteristic in service.characteristics! {
print("Characteristic: \(characteristic)\n error: \(error)")
if(characteristic.uuid.uuidString == "FFF2"){
peripheral.readValue(for: characteristic)
}
}
}
func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
print("Characteristic read: \(characteristic)\n error: \(error)")
// UInt16(data:) comes from the DataConvertible extension. It loads host-order bytes.
let major = UInt16(bigEndian: UInt16(data: characteristic.value!)!)
print("major: \(major)")
}
- The characteristic value can be read only after
peripheral.readValue(for:). - That read calls
peripheral(_:didUpdateValueFor:error:)with the value asData.characteristic.value!crashes when the read failed andvalueis nil.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents