Skip to content

Instantly share code, notes, and snippets.

@aurozhkov
Created September 25, 2016 05:21
Show Gist options
  • Save aurozhkov/93806db85752302495d1696f38a83ab6 to your computer and use it in GitHub Desktop.
Save aurozhkov/93806db85752302495d1696f38a83ab6 to your computer and use it in GitHub Desktop.
BLE detecting
import CoreBluetooth
let kServiceUUID = CBUUID(string: "0000a000-0000-1000-8000-00805f9b34fb")
let kCharacteristicUUID = CBUUID(string: "0000a001-0000-1000-8000-00805f9b34fb")
let centralManager = CBCentralManager(delegate: self, queue: nil)
var foundDevice: CBPeripheral?
public func centralManagerDidUpdateState(central: CBCentralManager) {
if centralManager.state == .PoweredOn {
centralManager.scanForPeripheralsWithServices([kServiceUUID], options: nil)
}
}
public func centralManager(central: CBCentralManager, didDiscoverPeripheral peripheral: CBPeripheral,
advertisementData: [String : AnyObject], RSSI: NSNumber) {
centralManager.stopScan()
foundDevice = peripheral
centralManager.connectPeripheral(foundDevice!, options: nil)
}
public func centralManager(central: CBCentralManager, didConnectPeripheral peripheral: CBPeripheral) {
foundDevice?.delegate = self
foundDevice?.discoverServices([kServiceUUID])
}
public func peripheral(peripheral: CBPeripheral, didDiscoverServices error: NSError?) {
guard let services = peripheral.services where services.count > 0 else {
return
}
for service in services {
foundDevice?.discoverCharacteristics([kCharacteristicUUID], forService: service)
}
}
public func peripheral(peripheral: CBPeripheral, didDiscoverCharacteristicsForService service: CBService, error: NSError?) {
guard let characteristics = service.characteristics where characteristics.count > 0 else {
return
}
for characteristic in characteristics {
if characteristic.UUID == kCharacteristicUUID {
foundDevice?.setNotifyValue(true, forCharacteristic: characteristic)
}
}
}
public func peripheral(peripheral: CBPeripheral, didUpdateValueForCharacteristic characteristic: CBCharacteristic, error: NSError?) {
//characteristic изменилась. предположим, что значения характеристики - 0 и 1
var out: NSInteger = 0
characteristic.value?.getBytes(&out, length: sizeof(NSInteger))
if out == 1 {
//произошло событие 1
} else {
//произошло событие 2
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment