0

What function do I need to pass 0x04 as a Data value to Peripheral characteristic in BLE? What int value can I pass to get a byte 0x04?

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

    if let characteristics = service.characteristics {

        // I WANT TO WRITE 0x04 TO THE PERIPHERAL USING enableBytes below
        // enableByte MUST BE A SINGLE BYTE

        var enableValue:UInt8 = 4
        let enableByte = Data(bytes: &enableValue, count: MemoryLayout<UInt8>.size)
        // This returns 04
        // print("enableByte is \(enableByte as NSData)")

        // writing to Characteristics
        for characteristic in characteristics {

            if characteristic.uuid == Device.OnOffUUID {
                self.peripheral?.setNotifyValue(true, for: characteristic)

                self.peripheral?.writeValue(enableByte, for: characteristic, type: .withResponse)

                peripheral.readValue(for: characteristic) // this will call peripheral(_: didUpdateValueFor characteristic)
            }
        }
    }
}
richc
  • 1,648
  • 5
  • 20
  • 48
  • 2
    Your code should work. I don't like `Data` "Swift version of `NSData` because its `description` method isn't helpful. If you do `let enableByteNSData = enableByte as NSData; print("enableByteNSData: \(enableByteNSData)")` you'll see you have sent `04`. – Larme Oct 04 '17 at 16:07
  • https://stackoverflow.com/a/33548238/2303865 – Leo Dabus Oct 04 '17 at 17:32
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/155955/discussion-between-richc-and-leo-dabus). – richc Oct 04 '17 at 17:45
  • @LeoDabus - do you know a function that converts back from <04> to UInt8? – richc Oct 05 '17 at 13:39
  • just get your `data.first` it will return the first byte out of you data (collection of bytes UInt8) – Leo Dabus Oct 05 '17 at 13:40
  • @LeoDabus and how to convert byte to an Int? – richc Oct 05 '17 at 16:41
  • byte is a UInt8 `Int(yourbyte)` – Leo Dabus Oct 05 '17 at 16:42
  • Let int = Int(data.first) gives error cannot invoke initialiser for type Int with type data.element – richc Oct 05 '17 at 16:49
  • You just need to unwrap your optional byte `let data = Data([4]) if let byte = data.first { let int = Int(byte) }`. first returns an optional because your collection my be empty – Leo Dabus Oct 05 '17 at 20:49

0 Answers0