Я пытаюсь записать значение с центрального на периферийное через CoreBluetooth, но это не работает. Но я получаю ошибку, что периферийное устройство не имеет таких характеристик c, но оно имеет. Вот расширение CoreBluetooth:
CentralManager:
extension MapViewController: CBCentralManagerDelegate {
func centralManagerDidUpdateState(_ central: CBCentralManager) {
switch central.state {
case .unknown:
print("central.state is .unknown")
case .resetting:
print("central.state is .resetting")
case .unsupported:
print("central.state is .unsupported")
case .unauthorized:
print("central.state is .unauthorized")
case .poweredOff:
print("central.state is .poweredOff")
case .poweredOn:
print("central.state is .poweredOn")
centralManager.scanForPeripherals(withServices: [BLEModels.serviceUUID])
print ("Started scanning")
default:
print("Unknown error for CentralManger.state")
}
}
func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral,
advertisementData: [String : Any], rssi RSSI: NSNumber) {
print(peripheral)
print("\(String(describing: peripheral.name))")
availablePeripherals.append(peripheral)
self.centralManager.connect(peripheral, options: nil)
}
func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
print("Connected to peripheral!")
peripheral.delegate = self
peripheral.discoverServices([BLEModels.serviceUUID])
}
}
PeripheralManager:
extension MapViewController: CBPeripheralManagerDelegate {
func peripheralManagerDidUpdateState(_ peripheral: CBPeripheralManager) {
switch peripheral.state {
case .unknown:
print("peripheral.state is .unknown")
case .resetting:
print("peripheral.state is .resetting")
case .unsupported:
print("peripheral.state is .unsupported")
case .unauthorized:
print("peripheral.state is .unauthorized")
case .poweredOff:
print("peripheral.state is .poweredOff")
case .poweredOn:
print("peripheral.state is .poweredOn")
peripheralManager.add(likeUService)
peripheralManager.startAdvertising([CBAdvertisementDataServiceUUIDsKey:[BLEModels.serviceUUID]])
print ("Started advertising")
default:
print("Unknown error for PeripheralManger.state")
}
}
func peripheralManager(_ peripheral: CBPeripheralManager, central: CBCentral, didSubscribeTo characteristic: CBCharacteristic) {
var centrals = self.subscribedCentrals[characteristic, default: [CBCentral]()]
centrals.append(central)
print ("Central subscribed")
self.subscribedCentrals[characteristic] = centrals
}
func peripheralManager(_ peripheral: CBPeripheralManager, didReceiveWrite requests: [CBATTRequest]) {
for request in requests{
let text = String(data: request.value!, encoding: .utf8)
print (text)
}
}
func peripheralManager(_ peripheral: CBPeripheralManager, willRestoreState dict: [String : Any]) {
// Just for using background
}
}
Периферийное устройство: здесь я пытаюсь записать значение в didDiscoverServices.
extension MapViewController: CBPeripheralDelegate{
func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?){
for service in peripheral.services ?? []{
if service.uuid == BLEModels.serviceUUID{
if !checkedPeripherals.contains(peripheral){
checkedPeripherals.append(peripheral)
newCompanion.peripheral = peripheral
peripheral.discoverCharacteristics(nil, for: service)
}
}
}
}
func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service:CBService, error: Error?){
for characteristic in service.characteristics ?? []{
switch characteristic.uuid{
case BLEModels.userInfoUUID:
peripheral.setNotifyValue(true, for: characteristic)
peripheral.readValue(for: characteristic)
case BLEModels.descriptionUUID:
peripheral.readValue(for: characteristic)
case BLEModels.sendInfoUUID:
peripheral.setNotifyValue(true, for: characteristic)
print ("Found send characteristic")
let data = "Send message".data(using: .utf8)
peripheral.writeValue(data!, for: sendInfoCharacteristic, type: .withoutResponse)
default:
print ("Get unknown type of characteristic")
}
}
}
func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?){
switch characteristic.uuid {
case BLEModels.userInfoUUID:
let nameDataStr = String(data: characteristic.value!, encoding: .utf8)
userTitles.append(nameDataStr!)
newCompanion.firstName = nameDataStr!
print ("User info: \(String(describing: nameDataStr)))")
case BLEModels.descriptionUUID:
let descrDataStr = String(data: characteristic.value!, encoding: .utf8)
newCompanion.description = descrDataStr!
default:
print("Unknown characteristic")
}
if !(addedPeripherals.contains(newCompanion.peripheral!)){
addedPeripherals.append(newCompanion.peripheral!)
companions.append(newCompanion)
print ("Companion added")
print ("\(companions.count)")
DispatchQueue.main.async {
self.usersList.reloadData()
}
}
}
}
Вот мой sendInfoCharacteristi c:
sendInfoCharacteristic = CBMutableCharacteristic(type: BLEModels.sendInfoUUID, properties: [ CBCharacteristicProperties.read, CBCharacteristicProperties.indicate], value: nil, permissions: [CBAttributePermissions.readable] )
Вот ошибка:
[CoreBluetooth] WARNING: <CBMutableCharacteristic: 0x283d5e4c0 UUID =
FF68B080-7028-11EA-BC55-0242AC130003, Value = {length = 20, bytes =
0xd0af20d182d0b5d0b1d18f20d0b2d0b8d0b6d183}, Properties = 0x4,
Permissions = 0x2, Descriptors = (null), SubscribedCentrals = (
)> is not a valid characteristic for peripheral <CBPeripheral:
0x282758000, identifier = 845358A5-0FA5-3009-8939-02B6FA6A43AF, name =
iPhone, state = connected>
А также didSubscribeCentral не работает, я сделал периферийное.SetNotifyValue, но Central не подписывается.
Буду очень признателен за совет.