Search code examples
iosswiftbluetooth-lowenergycore-bluetoothbluetooth-peripheral

Getting CBATTErrorDomain Code=6 The request is not supported error while writing value to peripheral


I created my custom peripheral to write data to peripheral and tried to write data from my central. when write value function is executed i am getting request is not supported error. Here is my code.Hope you understand my problem. Looking for the solution to fix. Thanks in advance.

connectedPeripheral?.writeValue(data, for: characteristic, type: .withResponse)

Setup up my custom BLEPeripheral and startAdvertising in Peripheral

// MARK: CBPeripheralManagerDelegate

func peripheralManagerDidUpdateState(_ peripheral: CBPeripheralManager) {
    if peripheral.state == .poweredOn {
        setup()
    } else {
        print("peripheral is not available: \(peripheral.state.rawValue)")
    }
}

func peripheralManager(_ peripheral: CBPeripheralManager, didAdd service: CBService, error: Error?) {
    if let error = error {
        print("Could not add service: \(error.localizedDescription)")
    } else {
        print("peripheral added service. Start advertising")
        let advertisementData: [String: Any] = [
            CBAdvertisementDataServiceUUIDsKey: [CBUUID(string: BLEIdentifiers.serviceIdentifier)],
            CBAdvertisementDataLocalNameKey: "BLE Sensor"  // This key will not be transmitted when app is backgrounded
        ]
        manager.startAdvertising(advertisementData)
    }
}

func peripheralManagerDidStartAdvertising(_ peripheral: CBPeripheralManager, error: Error?) {
    if let error = error {
        print("Could not start advertising: \(error.localizedDescription)")
    } else {
        print("peripheral started advertising")
    }
}

func peripheralManager(_ peripheral: CBPeripheralManager, didReceiveRead request: CBATTRequest) {
    print("Did receive read request: \(request)")
    if !request.characteristic.uuid.isEqual(characteristic.uuid) {
        peripheral.respond(to: request, withResult: .requestNotSupported)
    } else {
        guard let value = characteristic.value else {
            peripheral.respond(to: request, withResult: .invalidAttributeValueLength)
            return
        }
        if request.offset > value.count {
            peripheral.respond(to: request, withResult: .invalidOffset)
        } else {
            request.value = value.subdata(in: request.offset..<value.count-request.offset)
            peripheral.respond(to: request, withResult: .success)
        }
    }
    
}
func setup() {
    let characteristicUUID = CBUUID(string: BLEIdentifiers.characteristicIdentifier)
    
    characteristic = CBMutableCharacteristic(type: characteristicUUID, properties: [.read, .write,.notify], value: nil, permissions: [.readable,.writeable])

    let descriptor = CBMutableDescriptor(type: CBUUID(string: CBUUIDCharacteristicUserDescriptionString), value: "BLESensor prototype")
    characteristic.descriptors = [descriptor]
    
    let serviceUUID = CBUUID(string: BLEIdentifiers.serviceIdentifier)
    let service = CBMutableService(type: serviceUUID, primary: true)
    
    service.characteristics = [characteristic]
    manager.add(service)
}

Writing data to Peripheral in Central

func writeDataToPeripheral(data: Data){
     if let characteristics =  ctService?.characteristics {
         for characteristic in characteristics {
             if characteristic.uuid == CBUUID(string: BLEIdentifiers.characteristicIdentifier) {
                 if characteristic.properties.contains(.write) {
                    connectedPeripheral?.writeValue(data, for: characteristic, type: .withResponse)
                 }
             }
         }
     }
 }

func peripheral(_ peripheral: CBPeripheral, didWriteValueFor characteristic: CBCharacteristic, error: Error?) {
         guard error == nil else {
            print("Error discovering didWriteValueFor: error", error.debugDescription)
            //Getting Error Domain=CBATTErrorDomain Code=6 "The request is not supported."
             return
         }
         print("Message sent")
     }

func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
    if let error = error {
        print("peripheral failed to discover services: \(error.localizedDescription)")
    } else {
        peripheral.services?.forEach({ (service) in
            print("service discovered: \(service)")
            peripheral.discoverCharacteristics([CBUUID(string: BLEIdentifiers.characteristicIdentifier)], for: service)
        })
    }
}

func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
    if let error = error {
        print("NSA A peripheral failed to discover characteristics: \(error.localizedDescription)")
    } else {
        ctService = service
        service.characteristics?.forEach({ (characteristic) in
            print("NSA A characteristic discovered: \(characteristic)")
            if characteristic.uuid == CBUUID(string: BLEIdentifiers.characteristicIdentifier)  {
                // keep a reference to this characteristic so we can write to it
                writeCharacteristic = characteristic
            }
            if characteristic.properties.contains(.read) {
                peripheral.readValue(for: characteristic)
            }
            peripheral.discoverDescriptors(for: characteristic)
        })
    }
}

Solution

  • In order to support writes, you must implement the didReceiveWrite method in your CBPeripheralManagerDelegate.

    Since you don't have this method, you get a "not supported" response to your write request.