3

Im working on ios Ble app to charge mobile phone.Im done everything correct upto discover characteristics.First Scannig peripheral and connected to it. Discover the services(FFB0) and characteristics(FFB1,FFB2) which having notify and write with out response properties. And i found Client Characteristic Configuration Descriptor. I want send command to pcb to unlock for charging i want write value to FFB2 characteristics but peripheral doesn't responds . Here is my code. Im searching everything related to this but i did't find any solution If any body give solution to this problem it helpfull to me

Thank You

// MARK: -  CBCentral,CBperipheral Delegates methods

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:
        centralManager.scanForPeripherals(withServices: [batteryServiceCBUUID])
        print("central.state is .poweredOn")

    @unknown default:
        fatalError()
    }
    print("state: \(central.state)")
  }

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:            
        let advertisementData = [CBAdvertisementDataLocalNameKey: "Test Device"]
        peripheralManager.startAdvertising(advertisementData)
        service.characteristics = [characteristicMut]
        peripheralManager.add(service)

        // peripheralManager.delegate = self
        print("peripheral.state  is .poweredOn")

    @unknown default:
        fatalError()
    }

    print("state: \(peripheral.state)")
}

func peripheralManagerDidStartAdvertising(_ peripheral: CBPeripheralManager, error: Error?) {
    if let error = error {
        print("Failed… error: \(error)")
        return
    }
    print("Succeeded!")

    //  peripheralManager.stopAdvertising()
}

func peripheralManager(peripheral: CBPeripheralManager, didAddService service: CBService, error: NSError?)
{
    if let error = error {
        print("error: \(error)")
        return
    }

    print("service: \(service)")
}

func peripheralManager(_ peripheral: CBPeripheralManager, central: CBCentral, didSubscribeTo characteristic: CBCharacteristic) {
    print("Subscribed Central=======>\(central)Characteristics \(characteristic)")
}

func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {

    print(peripheral)
    batteryServicePeripheral = peripheral
    batteryServicePeripheral.delegate = self
    centralManager.stopScan()
    centralManager.connect(batteryServicePeripheral)

}

func peripheralManager(peripheral: CBPeripheralManager, didReceiveReadRequest request: CBATTRequest)
{
    if request.characteristic.uuid == characteristicMut.uuid
    {
        // Set the correspondent characteristic's value
        // to the request
        request.value = characteristicMut.value

        // Respond to the request
        peripheralManager.respond(
            to: request,
            withResult: .success)
    }
}

func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {

    print("Connected=======>\(String(describing: peripheralManager))")
    batteryServicePeripheral.delegate = self
    batteryServicePeripheral.discoverServices([batteryServiceCBUUID])

}

func centralManager(_ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: Error?) {

    print("Fail To Connect=======>\(String(describing: error))")
}


func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) {

    if error == nil {

        print("Disconnected========>\(peripheral)")
    }else {

        print("Disconnected========>\(String(describing: error))")
    }
}

// MARK: -  CBPeripheral Delegate Methods

func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
    guard let services = peripheral.services else { return }
    for service in services {
        print("SPAKA:PERIPHERALSERVICES============>\(service)")
        peripheral.discoverCharacteristics(nil, for: service)
    }      
}

func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {

    if let characteristics = service.characteristics {
        //else { return }

        for characteristic in characteristics {

            print(characteristic)
            if characteristic.uuid == batteryServiceCBUUID {

                batteryServicePeripheral.setNotifyValue(true, for: characteristic)
                batteryServicePeripheral.readValue(for: batteryCharacteristics)
            }

            if characteristic.uuid == batteryServiceRequestCBUUID2 {

                batteryCharacteristics = characteristic

                let str1 = "55e100"
                let data = String(format: "%@%@",str1,hexTimeForChar)
                guard let valueString = data.data(using: String.Encoding.utf8)  else {return}

                peripheral.writeValue(valueString, for: characteristic , type: CBCharacteristicWriteType.withoutResponse)
                print("Value String===>\(valueString.debugDescription)")
                  batteryServicePeripheral.readValue(for: batteryCharacteristics)
                peripheral.setNotifyValue(true, for: characteristic)

    peripheral.discoverDescriptors(for: batteryCharacteristics)
}

func peripheral(_ peripheral: CBPeripheral, didWriteValueFor characteristic: CBCharacteristic, error: Error?) {        
    if error == nil {
        print("Message sent=======>\(String(describing: characteristic.value))")
    }else{

        print("Message Not sent=======>\(String(describing: error))")
    }
}

func peripheral(_ peripheral: CBPeripheral, didUpdateNotificationStateFor characteristic: CBCharacteristic, error: Error?) {

    if error == nil {
        print("SPAKA : IS NOTIFYING UPDATED STATE ======>\(characteristic.isNotifying)")
        print("SPAKA : UPDATED DESCRIPTION ======>\(String(describing: characteristic.description))")
    }else{
        print("SPAKA : ERRORUPDATEDNOTIFICATION\(String(describing: error))")
    }
}

func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {

    print("SPAKA: UPDATED VALUE RECEIVED========>\(String(describing: characteristic.value))")
    print("characteristic UUID: \(characteristic.uuid), value: \(characteristic.value)")        
    guard let str = characteristic.value else { return  }        
    if let string = String(bytes: str, encoding: .utf8) {
        print("SPAKA==========>:::\(string)")
    } else {
        print("not a valid UTF-8 sequence")
    }
}

func peripheral(_ peripheral: CBPeripheral, didDiscoverDescriptorsFor characteristic: CBCharacteristic, error: Error?) {

    guard let desc = batteryCharacteristics.descriptors else { return 
  }  
    for des in desc {
        print("BEGIN:SPAKA DESCRIPTOR========>\(des)")
        discoveredDescriptor = des          
        peripheral.setNotifyValue(true, for: batteryCharacteristics)
    }

}

func peripheral(_ peripheral: CBPeripheral, didWriteValueFor descriptor: CBDescriptor, error: Error?) {
    if let error = error {
        print("Failed… error: \(error)")
        return
    }

    print("Descriptor Write Value uuid: \(descriptor.uuid), value: \(String(describing: descriptor.value))")
}

func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor descriptor: CBDescriptor, error: Error?) {

    if let error = error {
        print("Failed… error: \(error)")
        return
    }

    print("Descriptor Updated Value uuid: \(descriptor.uuid), value: \(String(describing: descriptor.value))")

    batteryServicePeripheral.readValue(for: batteryCharacteristics)

}

func peripheralManager(_ peripheral: CBPeripheralManager, didReceiveWrite requests: [CBATTRequest]) {
    for request in requests {
        print(request)
        if let value = request.value {
            if let messageText = String(data: value, encoding: String.Encoding.utf8) {
                print(messageText)
            }
        }
    }
}

func peripheralManager(_ peripheral: CBPeripheralManager, didReceiveRead request: CBATTRequest){

    print("Received Request==========>\(request)")
}
Aman Gupta
  • 156
  • 2
  • 16
Bhasker
  • 73
  • 2
  • 8
  • Some observations: Your iOS device has the central manager role; you can delete all *peripheralManager* code. `setNotifyValue` is for readable characteristics; it seems to be used for writeable charactersitics as well; you better remove it. The data is sent as a string; most devices use a binary protocol. `didWriteValueFor:` won't be called as the `.withoutResponse` option is used. `setNotifyValue` is used in too many places; use it for readable characteristics only, and it's sufficien to do it in `didDiscoverCharacteristicsFor:`. – Codo Sep 17 '19 at 10:47
  • Your chances for a helpful answer will dramatically increase if you provide a more minimal example and more complete information. I suggest you remove all the *peripheralManager* code and provide more information about the services and characteristics of the BLE peripheral. – Codo Sep 17 '19 at 10:49
  • @codo Thank you how can i provide services.Im new to ios please give me some example or more explanation – Bhasker Sep 17 '19 at 10:53
  • There are plenty of generic examples available on the internet. If you want more specific advise, to as I have proposed: update the question with a smaller example (in particular remove the *peripheralManager* code) and provide information about the devices GATT characteristics (UUID, if they are readable, writeable, use notification and/or indication, what data they expect etc.). – Codo Sep 17 '19 at 11:14
  • Devices Charecteristics UUIDs are FFB1 and FFB2 and both having .notify , .writewithoutresponse properties and FFB0 is service UUID – Bhasker Sep 17 '19 at 11:20
  • What data format do the characteristics expect? What data should be written to which characteristic? Is it a custom device or can you provide a link to a description? I propose you edit the question and append all the information related to the characteristic. – Codo Sep 17 '19 at 11:47
  • @Codo Can you give example for converting hex string to byte protocal and we have to write a value to characteristcs is Data type. – Bhasker Sep 17 '19 at 11:49
  • The characteristic expect byte data type and i have hex string value. I don't know whether it's custom device or not sorry for that. We need to add a value to FFB2 char which is write without response property – Bhasker Sep 17 '19 at 11:53
  • Descriptor Present Value : Client Characteristic Configuration, value: nil Descriptor Updated Value : Client Characteristic Configuration, value: Optional(1) These are the values im getting in console of my xcode – Bhasker Sep 17 '19 at 12:24
  • I cannot help you unless you provide more information about the required BLE communication: what's the data format for writing the characteristics (*expect byte data type* is not sufficient), do certain characteristics need to be written and why etc. Can't you provide a documentation of the device? And please add the relevant information to the question and not as a comment. This is neither a forum nor a chat. – Codo Sep 17 '19 at 14:18

0 Answers0