BlueSwift icon indicating copy to clipboard operation
BlueSwift copied to clipboard

Write successfully occurs, but the handler is not called

Open ksinghal opened this issue 5 years ago • 0 comments

I am attempting to write to a characteristic. The first time I run the code below, it works and my peripheral is written to and I receive a callback handler for "write" function with no error. Then, when I attempt to run the same exact code a second time, the peripheral is written to but I do not receive a callback handler.

Note: I am using the "develop" branch because the changes to read/write validation were necessary to make the write work in the first place... If you can merge this into master I would much appreciate it.

Here is the example code:

        let characteristic1 = try! Characteristic(uuid: "EXAMPLE")
        let characteristic2 = try! Characteristic(uuid: "EXAMPLE")
        let service = try! Service(uuid: uuid, characteristics: [characteristic1, characteristic2])
        let configuration = try! Configuration(services: [service], advertisement: uuid)
        let peripheral = Peripheral(configuration: configuration)

        // connect to the peripheral
        connection.connect(peripheral) { [weak self] error in
            guard error == nil else {
                return
            }
            
            let command = Command.int8(1)
            

            // write command to characteristic1
            peripheral.write(command: command,
                             characteristic: characteristic1,
                             type: .withResponse)
            { (error) in
                // on second run, this handler code does not execute
                guard error == nil else {
                    // if error writing, read characteristic2
                    peripheral.read(errorCharacteristic) { (result, error) in
                        guard let result = result else {
                            self?.connection.disconnect(peripheral)
                            return
                        }
                        
                        var resultNumber: UInt8 = 0
                        result.copyBytes(to:&resultNumber, count: MemoryLayout<UInt8>.size)
                        print(resultNumber)
                        self?.connection.disconnect(peripheral)
                    }
                    return
                }
                
                // always disconnect
                self?.connection.disconnect(peripheral)
            }
        }

ksinghal avatar Feb 17 '20 06:02 ksinghal