Skip to content

Instantly share code, notes, and snippets.

@erica
Last active January 22, 2019 20:42
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save erica/d249ff13aec353e8a8d72a1f5e77d3f8 to your computer and use it in GitHub Desktop.
Save erica/d249ff13aec353e8a8d72a1f5e77d3f8 to your computer and use it in GitHub Desktop.
import Cocoa
import CoreBluetooth
import PlaygroundSupport
class BTHelper: NSObject, CBCentralManagerDelegate, CBPeripheralDelegate {
var centralManager: CBCentralManager
override init() {
self.centralManager = CBCentralManager(delegate: nil, queue: nil)
super.init()
self.centralManager.delegate = self
}
// Required. Invoked when the central manager’s state is updated.
func centralManagerDidUpdateState(_ manager: CBCentralManager) {
switch manager.state {
case .poweredOff:
print("BLE has powered off")
centralManager.stopScan()
case .poweredOn:
print("BLE is now powered on")
centralManager.scanForPeripherals(withServices: nil, options: nil)
case .resetting: print("BLE is resetting")
case .unauthorized: print("Unauthorized BLE state")
case .unknown: print("Unknown BLE state")
case .unsupported: print("This platform does not support BLE")
}
}
// Invoked when the central manager discovers a peripheral while scanning.
func centralManager(_ manager: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData advertisement: [String : Any], rssi: NSNumber) {
if let name = peripheral.name {
// RSSI is Received Signal Strength Indicator
print("Found \"\(name)\" peripheral (RSSI: \(rssi))")
} else {
print("Found unnamed peripheral (RSSI: \(rssi))")
}
print("Advertisement data:", advertisement)
print("")
}
}
let bt = BTHelper()
PlaygroundPage.current.needsIndefiniteExecution = true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment