[swift]CoreBluetooth(Client)

小黑
發佈於APP
2023/11/13閱讀時間約 10 分鐘

CBCentralManager:藍芽管理中心,做外部設備搜尋、連接。

CBPeripheral:外部設備

CBCharacteristic:外部設備的特徵。

首先先宣告:

var centralManager: CBCentralManager = CBCentralManager.init(delegate: self, queue: .main)


判斷手機藍牙狀態:

// 判斷手機藍牙狀態
func centralManagerDidUpdateState(_ central: CBCentralManager) {
switch central.state {
case .resetting:
print("resetting")
case .unsupported:
print("unsupported")
case .unauthorized:
print("unauthorized")
case .poweredOff:
print("poweredOff")
case .poweredOn:
print("poweredOn")
central.scanForPeripherals(withServices: [CBUUID.init(string: service_UUID)], options: nil)
default:
print("unknown")
}
}


發現符合要求的外設:

/** 發現符合要求的外設 */
func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
self.peripheral = peripheral
// 根據外設名稱來過濾
// if (peripheral.name?.hasPrefix("WH"))! {
// central.connect(peripheral, options: nil)
// }
self.centralManager?.stopScan()
central.connect(peripheral, options: nil)
}


連接成功的回調:

/** 連接成功 */
func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
peripheral.delegate = self
peripheral.discoverServices([CBUUID.init(string: service_UUID)])
print("連接成功")
}


連接失敗的回調:

/** 連接失敗的回調 */
func centralManager(_ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: Error?) {
print("連接失敗")
}


斷開連接的回調:

/** 斷開連接 */
func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) {
print("斷開連接")
// 重新連接
central.connect(peripheral, options: nil) }
}


發現服務的回調:

/** 發現服務 */
func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
for service: CBService in peripheral.services! {
print("外設中的服務有:\(service)")
}
//本例的外設中只有一個服務
let service = peripheral.services?.last
// 根據UUID尋找服務中的特徵
peripheral.discoverCharacteristics([CBUUID.init(string: characteristic_UUID)], for: service!)
}


發現特徵的回調:

/** 發現特徵 */
func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
for characteristic: CBCharacteristic in service.characteristics! {
print("外設中的特徵有:\(characteristic)")
}
self.characteristic = service.characteristics?.last
// 讀取特徵裏的數據
peripheral.readValue(for: self.characteristic!)
// 訂閱
peripheral.setNotifyValue(true, for: self.characteristic!)
}


訂閱狀態的回調:

/** 訂閱狀態 */
func peripheral(_ peripheral: CBPeripheral, didUpdateNotificationStateFor characteristic: CBCharacteristic, error: Error?) {
if let error = error {
print("訂閱失敗: \(error)")
return
}
if characteristic.isNotifying {
print("訂閱成功")
} else {
print("取消訂閱")
}
}


接收到數據的回調:

/** 接收到數據 */
func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
let data = characteristic.value
print(String.init(data: data!, encoding: String.Encoding.utf8)!)
}


主動傳送:

//主動傳送
func didClickPost(_ sender: Any) {
self.peripheral?.writeValue(Data(), for: self.characteristic!, type: CBCharacteristicWriteType.withResponse)
}


寫入數據:

/** 寫入數據 */
func peripheral(_ peripheral: CBPeripheral, didWriteValueFor characteristic: CBCharacteristic, error: Error?) {
print("寫入數據")
}


主動接收:

//主動接收
func didClickGet(_ sender: Any) {
self.peripheral?.readValue(for: self.characteristic!)
}
7會員
78內容數
嗨,我是一名程式設計師,會在這分享開發與學習紀錄。
留言0
查看全部
發表第一個留言支持創作者!