Skip to content

Instantly share code, notes, and snippets.

@bricklife
Created July 26, 2017 12:13
Show Gist options
  • Save bricklife/45e4a2f53ce4e9ce1c87969070b8f24b to your computer and use it in GitHub Desktop.
Save bricklife/45e4a2f53ce4e9ce1c87969070b8f24b to your computer and use it in GitHub Desktop.
//
// BLEPeripheral.swift
// BLEPeripheral
//
// Created by ooba on 26/07/2017.
// Copyright © 2017 mercari. All rights reserved.
//
import Foundation
import CoreBluetooth
class BLEPeripheral: NSObject {
var peripheralManager: CBPeripheralManager?
let serviceUUID = CBUUID(string: "00001523-1212-EFDE-1523-785FEABCD123")
let characteristicUUID = CBUUID(string: "00001524-1212-EFDE-1523-785FEABCD123")
var characteristic: CBMutableCharacteristic?
override init() {
super.init()
peripheralManager = CBPeripheralManager(delegate: self, queue: nil)
}
func startAdvertising() {
let advertisementData: [String : Any] = [
CBAdvertisementDataLocalNameKey: "BLE Peripheral",
CBAdvertisementDataServiceUUIDsKey: [serviceUUID],
]
peripheralManager?.startAdvertising(advertisementData)
}
func stopAdvertising() {
peripheralManager?.stopAdvertising()
}
func addService() {
peripheralManager?.removeAllServices()
let service = CBMutableService(type: serviceUUID, primary: true)
let characteristic = CBMutableCharacteristic(type: characteristicUUID, properties: [.read, .write, .notify], value: nil, permissions: [.readable, .writeable])
service.characteristics = [characteristic]
peripheralManager?.add(service)
characteristic.value = "ABC".data(using: .utf8)
self.characteristic = characteristic
}
func updateValue(string: String) {
guard let characteristic = characteristic else { return }
guard let data = string.data(using: .utf8) else { return }
characteristic.value = data
peripheralManager?.updateValue(data, for: characteristic, onSubscribedCentrals: nil)
}
}
extension BLEPeripheral: CBPeripheralManagerDelegate {
func peripheralManagerDidUpdateState(_ peripheral: CBPeripheralManager) {
switch peripheral.state {
case .poweredOn:
print("poweredOn")
addService()
case .poweredOff:
print("poweredOff")
case .resetting:
print("resetting")
case .unsupported:
print("unsupported")
case .unauthorized:
print("unauthorized")
case .unknown:
print("unknown")
}
}
func peripheralManagerDidStartAdvertising(_ peripheral: CBPeripheralManager, error: Error?) {
print("didStartAdvertising:", error ?? "success")
}
func peripheralManager(_ peripheral: CBPeripheralManager, didAdd service: CBService, error: Error?) {
print("didAdd:", service, error ?? "success")
}
func peripheralManager(_ peripheral: CBPeripheralManager, didReceiveRead request: CBATTRequest) {
print("didReceiveRead:", request)
if let characteristic = characteristic, request.characteristic.uuid == characteristic.uuid {
request.value = characteristic.value
peripheralManager?.respond(to: request, withResult: .success)
} else {
peripheralManager?.respond(to: request, withResult: .requestNotSupported)
}
}
func peripheralManager(_ peripheral: CBPeripheralManager, didReceiveWrite requests: [CBATTRequest]) {
print("didReceiveWrite:", requests)
guard let firstRequest = requests.first else {
fatalError()
}
for request in requests {
if let characteristic = characteristic, request.characteristic.uuid == characteristic.uuid {
characteristic.value = request.value
} else {
peripheralManager?.respond(to: firstRequest, withResult: .requestNotSupported)
return
}
}
peripheralManager?.respond(to: firstRequest, withResult: .success)
}
func peripheralManager(_ peripheral: CBPeripheralManager, central: CBCentral, didSubscribeTo characteristic: CBCharacteristic) {
print("didSubscribeTo:", central, characteristic)
}
func peripheralManager(_ peripheral: CBPeripheralManager, central: CBCentral, didUnsubscribeFrom characteristic: CBCharacteristic) {
print("didUnsubscribeFrom:", central, characteristic)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment