0

Im trying to decode the following BLE message that my app receives from a piece of hardware

enter image description here

Here is both my Codable Stuct and also where I am trying to decode the message, But it keeps dropping into the else statement and is unable to decode the payload.

struct AccelerometerData: Codable {
    let timestamp: UInt64
    let x: Int8
    let y: Int8
    let z: Int8
}

    if let value = characteristic.value {
        if let accelerometerData = try? decoder.decode(AccelerometerData.self, from: value) {
            print("accelerometer data is: \(accelerometerData)")
        } else {
            print("Some error when decoding the data")
        }
    }
  • 1
    What's `decoder`? a `JSONDecoder`? If yes, do you what you received is JSON? Usually it's not, that's why I'm asking. – Larme Mar 12 '21 at 11:41
  • Also, even if your `decoder` is capable of decoding your input, don't use `try ?`, use `do/try/catch` so you can catch any error – Paulw11 Mar 12 '21 at 11:45
  • @Larme, Yes `decoder` is a `JSONDecoder` . As you will see from the document above the format I should expect the data in is `M1:uint64 M2:sint8 M3:sint8 M4:sint8` so I'm unsure of what format this follows. –  Mar 12 '21 at 11:46
  • 1
    You don't have json so you can use a json decoder. You will have a series of bytes. You need to decode these. Yes to the various values. – Paulw11 Mar 12 '21 at 11:47
  • Might want to print the hex data? https://stackoverflow.com/questions/39075043/how-to-convert-data-to-hex-string-in-swift But solution might be there: https://stackoverflow.com/questions/53053799/how-to-send-struct-into-the-ble-writevalue – Larme Mar 12 '21 at 11:52
  • What you get is not json. It is a byte array that contains these values, all concatenated. – Martijn van Welie Mar 12 '21 at 16:56
  • @MartijnvanWelie How do you recommend I decode the message then? –  Mar 12 '21 at 17:03
  • @OliverFerris Can you show a sample of data you have? And the other link I gave seems to be a valid solution, but did you check it out or try at least? – Larme Mar 13 '21 at 09:54

0 Answers0